dsh-codearts-dock 0.0.0-stage → 1.0.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.
Files changed (49) hide show
  1. package/DISCLAIMER.md +47 -0
  2. package/LICENSE +21 -0
  3. package/README.md +169 -2
  4. package/SECURITY.md +45 -0
  5. package/THIRD_PARTY_NOTICES.md +64 -0
  6. package/client.js +3491 -0
  7. package/cordis.patch.yml +10 -0
  8. package/docs/DETAIL.md +24 -0
  9. package/docs/DETAIL.zh.md +24 -0
  10. package/docs/PUBLISHING.md +43 -0
  11. package/docs/preview.svg +78 -0
  12. package/icons/dsh-connect-codearts-128.png +0 -0
  13. package/icons/dsh-connect-codearts-256.png +0 -0
  14. package/locale/en.json +7 -0
  15. package/locale/zh.json +7 -0
  16. package/package.json +88 -4
  17. package/scripts/build-market-index.mjs +24 -0
  18. package/scripts/check-legal.sh +33 -0
  19. package/scripts/check-release.mjs +29 -0
  20. package/scripts/test.mjs +11 -0
  21. package/src/account.js +217 -0
  22. package/src/accounts.js +481 -0
  23. package/src/adapter.js +715 -0
  24. package/src/backup.js +89 -0
  25. package/src/catalog.js +269 -0
  26. package/src/checkin.js +271 -0
  27. package/src/credentials.js +435 -0
  28. package/src/features.js +79 -0
  29. package/src/gateway.js +521 -0
  30. package/src/health.js +15 -0
  31. package/src/index.js +1029 -0
  32. package/src/models.js +147 -0
  33. package/src/paths.js +36 -0
  34. package/src/preferences.js +87 -0
  35. package/src/protocol/crypto.js +160 -0
  36. package/src/protocol/sign.js +176 -0
  37. package/src/protocol/sm4.js +264 -0
  38. package/src/protocol/sse.js +134 -0
  39. package/src/sts.js +118 -0
  40. package/test/accounts.test.mjs +344 -0
  41. package/test/adapter.test.mjs +234 -0
  42. package/test/assembler.test.mjs +86 -0
  43. package/test/features.test.mjs +240 -0
  44. package/test/live-probe.mjs +55 -0
  45. package/test/protocol.test.mjs +167 -0
  46. package/test/registration.test.mjs +303 -0
  47. package/test/sm4.test.mjs +64 -0
  48. package/test/ui.test.mjs +732 -0
  49. package/test/visual.test.mjs +420 -0
package/src/gateway.js ADDED
@@ -0,0 +1,521 @@
1
+ /**
2
+ * The 码道 (CodeArts Agent) gateway client.
3
+ *
4
+ * One chat request draws on all three layers:
5
+ *
6
+ * 1. `SDK-HMAC-SHA256` signing over the AK/SK/STS triple
7
+ * 2. a P-256 agreement that yields the SM4 session key
8
+ * 3. an SM4-GCM sealed request body with a per-chunk decrypted SSE stream
9
+ *
10
+ * The wire format is not a JSON envelope. The ciphertext travels in the raw
11
+ * body as Base64 TEXT, and IV, tag, key id, and timestamp travel in
12
+ * `X-Encrypt-*` headers:
13
+ *
14
+ * Content-Type: application/octet-stream
15
+ * X-Encrypt-Algo: sm4-gcm
16
+ * X-Encrypt-Key-Id: <keyId>
17
+ * X-Encrypt-Iv: <base64>
18
+ * X-Encrypt-Tag: <base64>
19
+ * X-Encrypt-Ts: <epoch ms, also part of the request AAD>
20
+ * body: <base64 ciphertext>
21
+ *
22
+ * The reply is an SSE stream whose frames are `iv:tag:ciphertext` triples,
23
+ * each decrypted with AAD `${keyId}|${chunkIndex}`. The gateway signals that
24
+ * by answering `x-encrypt-algo: sm4-gcm`; without that header the stream is
25
+ * already plaintext.
26
+ *
27
+ * Base: https://snap-access.cn-north-4.myhuaweicloud.com
28
+ */
29
+
30
+ import { createHash, randomBytes, randomUUID } from 'node:crypto'
31
+ import { signRequest } from './protocol/sign.js'
32
+ import { completeKeyExchange, createEcdhPair, deriveRequestEnvelope, openChunk } from './protocol/crypto.js'
33
+ import { parseStreamEvent, splitSseEvents } from './protocol/sse.js'
34
+
35
+ /** The gateway root used when configuration names none. */
36
+ export const DEFAULT_GATEWAY = 'https://snap-access.cn-north-4.myhuaweicloud.com'
37
+
38
+ /** Chat completions (sealed body, streamed and sealed response). */
39
+ export const CHAT_PATH = '/api/v2/chat/completions'
40
+ /** Session-key agreement. */
41
+ export const KEY_EXCHANGE_PATH = '/api/v1/security/key-exchange'
42
+ /** Plain (unsealed) JSON reads. */
43
+ export const MODELS_PATH = '/v1/model/builtin'
44
+ export const THINKING_VARIANTS_PATH = '/v1/model/thinking-variants'
45
+ export const CREDIT_STATISTICS_PATH = '/snap-manager/v1/statistics/plugin'
46
+ export const ROLES_PATH = '/snap-manager/v1/member/roles'
47
+ export const BENEFITS_PATH = '/v1/ops/delivery?channel=IDE'
48
+ export const BENEFIT_CLAIM_PATH = '/v1/ops/claim'
49
+ export const HEARTBEAT_PATH = '/snap-manager/v1/chat-session/heartbeat'
50
+
51
+ /** Renew the session key this long before it expires. */
52
+ const REFRESH_MARGIN_MS = 300_000
53
+
54
+ /**
55
+ * Headers every request to this gateway must carry. Each one is required:
56
+ * omitting `Agent-Type` or `x-language` answers HTTP 400 with no explanation.
57
+ */
58
+ const BUSINESS_HEADERS = {
59
+ 'Agent-Type': 'PromptCenter',
60
+ }
61
+
62
+ /**
63
+ * The client identity asserted to the gateway. These mirror the official
64
+ * CodeArts Agent extension — product names and version numbers, not secrets.
65
+ */
66
+ const DEFAULT_IDENTITY = {
67
+ pluginName: 'codemate_vscode',
68
+ pluginVersion: '26.11.100',
69
+ ideName: 'VSCode',
70
+ ideVersion: '26.11.100',
71
+ userAgent: 'ai-sdk/provider-utils/4.0.21 runtime/bun/1.3.14',
72
+ }
73
+
74
+ /** An upstream failure carrying the HTTP status and the gateway's own text. */
75
+ export class GatewayError extends Error {
76
+ /**
77
+ * @param {string} message human-readable failure.
78
+ * @param {object} [details] failure facts.
79
+ * @param {number} [details.status] HTTP status.
80
+ * @param {string} [details.code] gateway business code.
81
+ * @param {boolean} [details.retryable] whether a retry could succeed.
82
+ */
83
+ constructor(message, { status, code, retryable = false } = {}) {
84
+ super(message)
85
+ this.name = 'GatewayError'
86
+ this.status = status
87
+ this.code = code
88
+ this.retryable = retryable
89
+ }
90
+ }
91
+
92
+ export class MadaoClient {
93
+ /**
94
+ * @param {object} options client options.
95
+ * @param {{ak: string, sk: string, securityToken: string}} options.credentials the signed triple.
96
+ * @param {string} [options.gateway] gateway root override.
97
+ * @param {typeof fetch} [options.fetch] fetch implementation, for tests.
98
+ * @param {object} [options.identity] client identity overrides.
99
+ * @param {string} [options.language] language header value.
100
+ * @param {string} [options.sessionId] fixed `user-session-id`.
101
+ */
102
+ constructor(options) {
103
+ this.gateway = (options.gateway ?? DEFAULT_GATEWAY).replace(/\/+$/, '')
104
+ this.credentials = options.credentials
105
+ this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis)
106
+ this.identity = { ...DEFAULT_IDENTITY, ...options.identity }
107
+ this.language = options.language ?? 'zh-cn'
108
+ this.sessionKey = null
109
+ this.negotiating = null
110
+ this.sessionId = options.sessionId ?? null
111
+
112
+ // The gateway counts concurrent sessions per `user-session-id` with a
113
+ // small ceiling (three). Without the header every request opens a new
114
+ // session, and a handful of requests exhausts the quota permanently.
115
+ // One stable value per credential keeps the plugin inside one session.
116
+ this.defaultSessionId =
117
+ this.sessionId ??
118
+ `codearts-${createHash('sha256')
119
+ .update(options.credentials.ak ?? 'default')
120
+ .digest('hex')
121
+ .slice(0, 16)}`
122
+ }
123
+
124
+ /** The identity headers the gateway requires on every call. */
125
+ #identityHeaders() {
126
+ return {
127
+ ...BUSINESS_HEADERS,
128
+ 'x-language': this.language,
129
+ 'plugin-name': this.identity.pluginName,
130
+ 'plugin-version': this.identity.pluginVersion,
131
+ 'ide-name': this.identity.ideName,
132
+ 'ide-version': this.identity.ideVersion,
133
+ }
134
+ }
135
+
136
+ // ── key agreement ────────────────────────────────────────────────────────
137
+
138
+ /**
139
+ * Return a usable session key, negotiating one when the cached key is
140
+ * near expiry. Concurrent callers share a single negotiation.
141
+ * @returns {Promise<{keyId: string, key: Buffer, expiresAt: number}>} the key.
142
+ */
143
+ async ensureSessionKey() {
144
+ if (this.sessionKey && Date.now() < this.sessionKey.expiresAt - REFRESH_MARGIN_MS) {
145
+ return this.sessionKey
146
+ }
147
+ if (this.negotiating) return this.negotiating
148
+ this.negotiating = this.negotiate().finally(() => {
149
+ this.negotiating = null
150
+ })
151
+ return this.negotiating
152
+ }
153
+
154
+ /** Run one P-256 agreement and cache its result. */
155
+ async negotiate() {
156
+ const pathname = KEY_EXCHANGE_PATH
157
+ const url = new URL(this.gateway + pathname)
158
+ const pair = createEcdhPair()
159
+ const body = JSON.stringify({
160
+ clientPublicKey: pair.publicKeyB64,
161
+ sessionId: randomBytes(16).toString('hex'),
162
+ timestamp: Date.now(),
163
+ })
164
+
165
+ const headers = signRequest({
166
+ method: 'POST',
167
+ url,
168
+ contentType: 'application/json',
169
+ body,
170
+ credentials: this.credentials,
171
+ })
172
+
173
+ const response = await this.fetch(url, {
174
+ method: 'POST',
175
+ headers: {
176
+ ...headers,
177
+ 'Content-Type': 'application/json',
178
+ 'User-Agent': this.identity.userAgent,
179
+ ...this.#identityHeaders(),
180
+ },
181
+ body,
182
+ })
183
+
184
+ if (!response.ok) {
185
+ const text = await response.text().catch(() => '')
186
+ throw new GatewayError(summariseFailure(response.status, text), {
187
+ status: response.status,
188
+ code: extractBusinessCode(text),
189
+ retryable: response.status >= 500,
190
+ })
191
+ }
192
+
193
+ const payload = await response.json()
194
+ const serverKey = payload?.serverPublicKey ?? payload?.data?.serverPublicKey
195
+ const keyId = payload?.keyId ?? payload?.data?.keyId
196
+ const expiresInSec = payload?.expiresIn ?? payload?.data?.expiresIn ?? 7200
197
+
198
+ if (!serverKey || !keyId) {
199
+ throw new GatewayError(
200
+ `key-exchange response missing fields: ${JSON.stringify(payload).slice(0, 300)}`,
201
+ )
202
+ }
203
+
204
+ const sharedSecret = pair.ecdh.computeSecret(Buffer.from(serverKey, 'base64'))
205
+ this.sessionKey = {
206
+ keyId: String(keyId),
207
+ key: completeKeyExchange(sharedSecret),
208
+ expiresAt: Date.now() + Number(expiresInSec) * 1000,
209
+ }
210
+ return this.sessionKey
211
+ }
212
+
213
+ // ── plain JSON reads ─────────────────────────────────────────────────────
214
+
215
+ /**
216
+ * GET a plain (unsealed) JSON endpoint.
217
+ * @param {string} pathname request path, including any query string.
218
+ * @returns {Promise<any>} the parsed body.
219
+ */
220
+ async getJson(pathname) {
221
+ return this.#requestJson('GET', pathname)
222
+ }
223
+
224
+ /**
225
+ * POST a plain (unsealed) JSON body and read the JSON reply.
226
+ * @param {string} pathname request path.
227
+ * @param {unknown} body JSON-serialisable request body.
228
+ * @returns {Promise<any>} the parsed body.
229
+ */
230
+ async postJson(pathname, body) {
231
+ return this.#requestJson('POST', pathname, body)
232
+ }
233
+
234
+ /** Shared implementation for the unsealed JSON endpoints. */
235
+ async #requestJson(method, pathname, body) {
236
+ // Sign the path and carry the query separately: the signature covers the
237
+ // canonical path only.
238
+ const [pathOnly, query] = pathname.split('?')
239
+ const url = new URL(this.gateway + pathOnly)
240
+ if (query) url.search = query
241
+
242
+ const text = body === undefined ? '' : JSON.stringify(body)
243
+ const headers = signRequest({
244
+ method,
245
+ url,
246
+ contentType: body === undefined ? null : 'application/json',
247
+ body: text,
248
+ credentials: this.credentials,
249
+ })
250
+
251
+ const response = await this.fetch(url, {
252
+ method,
253
+ headers: {
254
+ ...headers,
255
+ ...(body === undefined ? {} : { 'Content-Type': 'application/json' }),
256
+ 'User-Agent': this.identity.userAgent,
257
+ ...this.#identityHeaders(),
258
+ },
259
+ ...(body === undefined ? {} : { body: text }),
260
+ })
261
+
262
+ const replyText = await response.text()
263
+ if (!response.ok) {
264
+ throw new GatewayError(summariseFailure(response.status, replyText), {
265
+ status: response.status,
266
+ code: extractBusinessCode(replyText),
267
+ retryable: response.status === 429 || response.status >= 500,
268
+ })
269
+ }
270
+ try {
271
+ return JSON.parse(replyText)
272
+ } catch {
273
+ throw new GatewayError(`non-JSON reply from ${pathOnly}: ${replyText.slice(0, 200)}`)
274
+ }
275
+ }
276
+
277
+ /**
278
+ * PUT the session heartbeat, marking this session busy or idle.
279
+ *
280
+ * The gateway counts concurrent sessions per `user-session-id`; declaring
281
+ * idle releases the slot immediately instead of leaving it held for the
282
+ * full timeout. Failure is ignored — this only optimises quota, and must
283
+ * never break a conversation.
284
+ *
285
+ * @param {'busy'|'idle'} status current session state.
286
+ * @returns {Promise<boolean>} whether the gateway accepted it.
287
+ */
288
+ async heartbeat(status) {
289
+ try {
290
+ const path = `${HEARTBEAT_PATH}?status=${status}`
291
+ const url = new URL(this.gateway + HEARTBEAT_PATH)
292
+ url.search = `?status=${status}`
293
+ const headers = signRequest({
294
+ method: 'PUT',
295
+ url,
296
+ contentType: null,
297
+ body: '',
298
+ credentials: this.credentials,
299
+ })
300
+ const response = await this.fetch(url, {
301
+ method: 'PUT',
302
+ headers: {
303
+ ...headers,
304
+ 'User-Agent': this.identity.userAgent,
305
+ ...this.#identityHeaders(),
306
+ 'user-session-id': this.defaultSessionId,
307
+ },
308
+ })
309
+ return response.ok
310
+ } catch {
311
+ return false
312
+ }
313
+ }
314
+
315
+ // ── chat ─────────────────────────────────────────────────────────────────
316
+
317
+ /**
318
+ * Stream one chat completion.
319
+ *
320
+ * The reply is normally an encrypted SSE stream; this yields
321
+ * already-decrypted parsed events and stops after the terminal frame.
322
+ *
323
+ * @param {object} request chat request.
324
+ * @param {string} request.model model id.
325
+ * @param {Array<object>} request.messages OpenAI-shaped messages.
326
+ * @param {number} [request.maxTokens] output cap.
327
+ * @param {number} [request.temperature] sampling temperature.
328
+ * @param {string} [request.reasoningEffort] thinking level.
329
+ * @param {Array<object>} [request.tools] tool schemas.
330
+ * @param {string|string[]} [request.stop] stop sequences.
331
+ * @param {AbortSignal} [request.signal] cancellation.
332
+ * @returns {AsyncGenerator<import('./protocol/sse.js').ParsedEvent>} parsed events.
333
+ */
334
+ async *streamChat(request) {
335
+ const session = await this.ensureSessionKey()
336
+ const pathname = CHAT_PATH
337
+ const url = new URL(this.gateway + pathname)
338
+ const timestamp = Date.now()
339
+
340
+ const body = {
341
+ model: request.model,
342
+ messages: request.messages,
343
+ max_tokens: request.maxTokens ?? 65536,
344
+ stream: true,
345
+ ...(typeof request.temperature === 'number' ? { temperature: request.temperature } : {}),
346
+ ...(request.stop ? { stop: request.stop } : {}),
347
+ ...(request.tools && request.tools.length > 0 ? { tools: request.tools } : {}),
348
+ // The gateway reads `reasoning_effort`; it silently ignores `strength`,
349
+ // which is why an earlier build appeared to change nothing.
350
+ ...(request.reasoningEffort
351
+ ? { reasoning_effort: request.reasoningEffort === 'off' ? 'none' : request.reasoningEffort }
352
+ : {}),
353
+ }
354
+
355
+ const envelope = deriveRequestEnvelope({
356
+ key: session.key,
357
+ keyId: session.keyId,
358
+ method: 'POST',
359
+ pathname,
360
+ timestamp,
361
+ plaintext: JSON.stringify(body),
362
+ })
363
+
364
+ // The signature must cover the bytes actually sent — the Base64
365
+ // ciphertext text, not the JSON request body.
366
+ const signed = signRequest({
367
+ method: 'POST',
368
+ url,
369
+ contentType: envelope.headers['Content-Type'],
370
+ body: envelope.body,
371
+ credentials: this.credentials,
372
+ })
373
+
374
+ let response
375
+ try {
376
+ response = await this.fetch(url, {
377
+ method: 'POST',
378
+ headers: {
379
+ ...signed,
380
+ ...envelope.headers,
381
+ Accept: 'text/event-stream',
382
+ 'X-Encrypt-Capable': 'sm4-gcm',
383
+ 'User-Agent': this.identity.userAgent,
384
+ ...this.#identityHeaders(),
385
+ 'user-session-id': this.defaultSessionId,
386
+ 'user-msg-id': randomUUID(),
387
+ },
388
+ body: envelope.body,
389
+ signal: request.signal,
390
+ })
391
+ } catch (error) {
392
+ if (error?.name === 'AbortError') throw error
393
+ throw new GatewayError(`无法连接码道网关:${error?.message ?? error}`, { retryable: true })
394
+ }
395
+
396
+ if (!response.ok) {
397
+ const errorText = await response.text().catch(() => '')
398
+ // A 4xx body is also sealed, so it is unreadable until decrypted;
399
+ // trying is what turns "HTTP 400" into something actionable.
400
+ const detail = openSealedBody(errorText, session.key, session.keyId)
401
+ throw new GatewayError(summariseFailure(response.status, detail, true), {
402
+ status: response.status,
403
+ code: extractBusinessCode(detail),
404
+ retryable: response.status === 429 || response.status >= 500,
405
+ })
406
+ }
407
+
408
+ const sealed = response.headers.get('x-encrypt-algo') === 'sm4-gcm'
409
+ if (!response.body) throw new GatewayError('chat response carried no body')
410
+
411
+ const decoder = new TextDecoder()
412
+ let buffer = ''
413
+ let index = 0
414
+
415
+ for await (const bytes of response.body) {
416
+ buffer += decoder.decode(bytes, { stream: true })
417
+ const { blocks, rest } = splitSseEvents(buffer)
418
+ buffer = rest
419
+
420
+ for (const block of blocks) {
421
+ // Decrypt first, then parse: a sealed block carries no `data:` prefix
422
+ // until it is opened.
423
+ const plaintext = sealed ? openChunk(block, session.key, session.keyId, index) : block
424
+ index += 1
425
+ if (plaintext === null) continue
426
+ for (const event of parseFrames(plaintext)) {
427
+ if (event.error) {
428
+ throw new GatewayError(`码道上游返回错误:${event.error}`, {
429
+ code: event.error,
430
+ retryable: false,
431
+ })
432
+ }
433
+ yield event
434
+ if (event.done) return
435
+ }
436
+ }
437
+ }
438
+
439
+ // A stream that ends without `[DONE]` still has to settle.
440
+ if (buffer.trim() !== '') {
441
+ const plaintext = sealed ? openChunk(buffer.trim(), session.key, session.keyId, index) : buffer.trim()
442
+ if (plaintext) {
443
+ for (const event of parseFrames(plaintext)) {
444
+ if (event.error) {
445
+ throw new GatewayError(`码道上游返回错误:${event.error}`, { code: event.error })
446
+ }
447
+ yield event
448
+ if (event.done) return
449
+ }
450
+ }
451
+ }
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Split one decrypted block into SSE payloads.
457
+ *
458
+ * A decrypted block is `data:{...}` with no trailing newline, so it may hold
459
+ * one payload and may also be a multi-line body. Every `data:` line is
460
+ * treated as its own payload.
461
+ */
462
+ function parseFrames(plaintext) {
463
+ const trimmed = plaintext.trim()
464
+ if (trimmed === '') return []
465
+ const lines = trimmed.split(/\r?\n/).filter((line) => line.startsWith('data:'))
466
+ if (lines.length === 0) {
467
+ // Not SSE-framed: a bare JSON object or the [DONE] sentinel.
468
+ const event = parseStreamEvent(trimmed)
469
+ return Object.keys(event).length > 0 ? [event] : []
470
+ }
471
+ return lines.map((line) => parseStreamEvent(line.slice(5).replace(/^ /, '')))
472
+ }
473
+
474
+ /**
475
+ * Try to open a sealed error body, falling back to the raw text.
476
+ * @returns {string} readable failure text.
477
+ */
478
+ function openSealedBody(text, key, keyId) {
479
+ const trimmed = (text ?? '').trim()
480
+ if (trimmed === '') return '(空响应体)'
481
+ try {
482
+ return openChunk(trimmed, key, keyId, 0) ?? trimmed.slice(0, 300)
483
+ } catch {
484
+ return trimmed.slice(0, 300)
485
+ }
486
+ }
487
+
488
+ /** Turn one gateway failure body into a readable sentence. */
489
+ function summariseFailure(status, text, alreadyReadable = false) {
490
+ const code = alreadyReadable ? extractBusinessCode(text) : extractBusinessCode(text)
491
+ let detail = ''
492
+ try {
493
+ const parsed = JSON.parse(text)
494
+ // The gateway's own failures use `error_code` / `error_msg`; a proxy in
495
+ // front of it may use `msg` / `message`. Accept both, or the message is
496
+ // an empty shell with only the status.
497
+ detail =
498
+ parsed?.error_msg ??
499
+ parsed?.msg ??
500
+ parsed?.message ??
501
+ parsed?.error?.message ??
502
+ ''
503
+ if (detail === '' && typeof parsed?.error === 'string') detail = parsed.error
504
+ } catch {
505
+ detail = text.slice(0, 300)
506
+ }
507
+ const suffix = code ? ` (code ${code})` : ''
508
+ return `码道网关返回 HTTP ${status}${suffix}${detail ? `:${detail}` : ''}`
509
+ }
510
+
511
+ /** Pull a gateway business code out of a failure body. */
512
+ function extractBusinessCode(text) {
513
+ try {
514
+ const parsed = JSON.parse(text)
515
+ const code =
516
+ parsed?.error_code ?? parsed?.code ?? parsed?.error?.code ?? parsed?.error?.type
517
+ return code === undefined || code === null ? undefined : String(code)
518
+ } catch {
519
+ return undefined
520
+ }
521
+ }
package/src/health.js ADDED
@@ -0,0 +1,15 @@
1
+ /** Fixed, actionable health categories; never persist error text or credentials. */
2
+ export function accountHealth({ error, credit, checkedAt = Date.now() } = {}) {
3
+ let state = 'unknown'
4
+ if (error) {
5
+ const code = String(error.code ?? '')
6
+ const text = String(error.message ?? '').toLowerCase()
7
+ const status = Number(error.status ?? error.statusCode ?? text.match(/http\s*(\d{3})/)?.[1])
8
+ if (status === 429 || /rate.?limit|throttl|限流/.test(text)) state = 'rate_limited'
9
+ else if (/insufficient|quota.*exceed|余额不足|积分不足|额度不足/.test(text) || status === 402) state = 'insufficient'
10
+ else if (status === 401 || status === 403 || error.name === 'CredentialError' || (error.name === 'StsError' && !/无法连接|network|timeout|fetch failed/.test(text)) || /expired.*token|invalid.*(credential|access.?key)|凭证.*(失效|过期)/.test(text)) state = 'credentials'
11
+ else if (['ETIMEDOUT', 'ECONNREFUSED', 'ENOTFOUND', 'ECONNRESET', 'UND_ERR_CONNECT_TIMEOUT'].includes(code) || error.name === 'AbortError' || error.name === 'TimeoutError' || /fetch failed|network|timeout|timed out|无法连接|网络|超时/.test(text)) state = 'network'
12
+ else state = 'gateway'
13
+ } else if (Number.isFinite(credit?.remain)) state = credit.remain <= 0 ? 'insufficient' : 'available'
14
+ return { state, checkedAt, action: state === 'credentials' ? 'credentials' : state === 'insufficient' ? 'switch' : 'recheck' }
15
+ }