dsh-codearts-dock 0.0.0-stage → 1.0.0

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 (50) hide show
  1. package/DISCLAIMER.md +47 -0
  2. package/LICENSE +21 -0
  3. package/README.md +172 -2
  4. package/SECURITY.md +47 -0
  5. package/THIRD_PARTY_NOTICES.md +64 -0
  6. package/client.js +3519 -0
  7. package/cordis.patch.yml +10 -0
  8. package/docs/DETAIL.md +25 -0
  9. package/docs/DETAIL.zh.md +25 -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 +742 -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 +18 -0
  31. package/src/index.js +1108 -0
  32. package/src/models.js +147 -0
  33. package/src/paths.js +36 -0
  34. package/src/preferences.js +90 -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/src/usage.js +55 -0
  41. package/test/accounts.test.mjs +322 -0
  42. package/test/adapter.test.mjs +234 -0
  43. package/test/assembler.test.mjs +86 -0
  44. package/test/features.test.mjs +257 -0
  45. package/test/live-probe.mjs +55 -0
  46. package/test/protocol.test.mjs +167 -0
  47. package/test/registration.test.mjs +301 -0
  48. package/test/sm4.test.mjs +64 -0
  49. package/test/ui.test.mjs +370 -0
  50. package/test/visual.test.mjs +438 -0
package/src/index.js ADDED
@@ -0,0 +1,1108 @@
1
+ /**
2
+ * Host half of the 码道 (CodeArts) connector.
3
+ *
4
+ * Responsibilities, in order of importance:
5
+ *
6
+ * 1. Register a native LLM adapter for the `codearts` provider route, so
7
+ * the 码道 models appear in the model selector and answer real traffic.
8
+ * 2. Refresh the model catalog from the gateway, on a timer and on demand.
9
+ * 3. Serve the small read-only HTTP surface the settings page and the
10
+ * composer chip call: credentials, catalog, credit, and diagnostics.
11
+ *
12
+ * There is no local bridge process: the adapter speaks the gateway's
13
+ * encrypted protocol in-process, so a model selection takes effect without a
14
+ * restart and no port is occupied.
15
+ */
16
+
17
+ import { randomUUID, createHash } from 'node:crypto'
18
+ import { join } from 'node:path'
19
+ import { CredentialProvider, CredentialError } from './credentials.js'
20
+ import { Catalog } from './catalog.js'
21
+ import { MadaoClient, GatewayError } from './gateway.js'
22
+ import { createCodeArtsAdapter, PROVIDER_ID, PROVIDER_NAME } from './adapter.js'
23
+ import {
24
+ claimBenefit,
25
+ listBenefits,
26
+ parseIdentity,
27
+ readCredit,
28
+ readRoles,
29
+ } from './account.js'
30
+ import {
31
+ CREDENTIAL_PATH,
32
+ clearCredentials,
33
+ listCandidates,
34
+ maskKey,
35
+ readSavedCredentials,
36
+ saveCredentials,
37
+ } from './credentials.js'
38
+ import {
39
+ STORE_VERSION,
40
+ activeAccount,
41
+ accountIdOf,
42
+ addAccount,
43
+ addAccounts,
44
+ defaultLabel,
45
+ exportStore,
46
+ parseImport,
47
+ locateStore,
48
+ publicAccount,
49
+ readStore,
50
+ rememberAccountName,
51
+ removeAccount,
52
+ renameAccount,
53
+ setActiveAccount,
54
+ } from './accounts.js'
55
+ import {
56
+ claimDaily,
57
+ readCheckin,
58
+ readCheckinState,
59
+ runAutoCheckin,
60
+ todaySummary,
61
+ } from './checkin.js'
62
+ import { getSts } from './sts.js'
63
+ import { CONFIG_DIR } from './paths.js'
64
+ import { FEATURE_DEFAULTS, InputError, readPreferences, persistPreferences, validatePreferences } from './preferences.js'
65
+ import { registerFeatureRoutes, applyPreferences } from './features.js'
66
+ import { createUsageStore } from './usage.js'
67
+ import { accountHealth, isLowBalance } from './health.js'
68
+
69
+ /** Plugin name; also the client module id. */
70
+ export const name = 'dsh-connect-codearts'
71
+
72
+ /** Services this plugin needs before it can activate. */
73
+ import z from '@deepseek-ai/schemastery'
74
+
75
+ /**
76
+ * The plugin's Config schema.
77
+ *
78
+ * REQUIRED, and not only for typing. Settings → Models builds one row per
79
+ * configurable provider and resolves that row's form by looking its
80
+ * `settingsNs` up in the Host's settings service — which only holds namespaces
81
+ * for plugins that declare a Config schema. No schema means no namespace, and
82
+ * the page then skips the row with `return null`: the provider is routable and
83
+ * its models are selectable, yet the card where a user manages it never appears,
84
+ * with no error anywhere. Declaring this is what makes the row render at all.
85
+ *
86
+ * `volatile()` is deliberately NOT used: this plugin's fields are simple scalars,
87
+ * and the volatile path exists for plugins that must rebuild a running stack on
88
+ * change. Values here are read live at each use, so a plain schema suffices.
89
+ */
90
+ export const Config = z.object({
91
+ enabled: z.boolean().default(true).description('关掉即禁用这个 provider,无需卸载插件'),
92
+ gateway: z.string().description('网关地址,留空用内置地址'),
93
+ refreshIntervalMs: z.number().description('模型目录与积分的刷新间隔(毫秒)'),
94
+ composerChip: z.boolean().default(true).description('在输入框旁显示积分'),
95
+ registerProvider: z.boolean().default(true).description('是否注册码道这个 provider 路由'),
96
+ autoCheckin: z.boolean().default(false).description('每天自动签到一次'),
97
+ lowBalanceEnabled: z.boolean().default(true).description('低余额提醒'),
98
+ lowBalanceThreshold: z.number().default(500).description('低余额提醒阈值'),
99
+ usageEnabled: z.boolean().default(true).description('在本机保留最近 200 条请求元数据'),
100
+ enabledModelIds: z.array(z.string()).description('启用的模型;留空表示全部'),
101
+ modelOverrides: z.dict(z.object({
102
+ images: z.boolean(),
103
+ allowOff: z.boolean(),
104
+ defaultStrength: z.string(),
105
+ })).description('按模型覆盖能力开关与默认推理强度'),
106
+ })
107
+
108
+ export const inject = ['llm']
109
+
110
+ /** Route prefix for this plugin's HTTP surface. */
111
+ const ROUTE_PREFIX = '/plugins/dsh-connect-codearts'
112
+
113
+ /** Default refresh period for the catalog and the credit reading. */
114
+ const DEFAULT_REFRESH_MS = 5 * 60 * 1000
115
+
116
+ /**
117
+ * Default configuration.
118
+ *
119
+ * Deliberately a plain object rather than a Schemastery schema: this bundle is
120
+ * installed as a LINKED directory outside the profile, so a package it
121
+ * imported would have to resolve from its real path — where the profile's own
122
+ * dependency tree is not visible. Adding a schema dependency would make the
123
+ * plugin fail to import on exactly the setup it is shipped in. The row's
124
+ * `config` block is read field-by-field at activation instead, and the real
125
+ * configuration surface is this plugin's own settings page.
126
+ */
127
+ export const DEFAULTS = {
128
+ ...FEATURE_DEFAULTS,
129
+ /** Turn the provider off without uninstalling the bundle. */
130
+ enabled: true,
131
+ /** Claim the daily bonus in the background, once a day. Off by default. */
132
+ autoCheckin: false,
133
+ /**
134
+ * The user's model selection.
135
+ *
136
+ * `null` means "everything the gateway offers", which is the right default:
137
+ * a user who has never opened the card should see the whole catalog, not an
138
+ * empty picker because nothing was ever ticked.
139
+ *
140
+ * Once edited this is a list of ids; a model the upstream withdrew but the
141
+ * user is still running stays offered, and a model the upstream added shows up
142
+ * only after the user ticks it.
143
+ */
144
+ enabledModelIds: null,
145
+ /** Per-model capability overrides: image input and whether "off" is offered. */
146
+ modelOverrides: {},
147
+ /** Gateway root, for a proxy or a regional deployment. */
148
+ gateway: undefined,
149
+ /** Catalog and credit refresh period, in milliseconds. */
150
+ refreshIntervalMs: DEFAULT_REFRESH_MS,
151
+ /** Show the credit reading beside the composer. */
152
+ composerChip: true,
153
+ /** Register the 码道 provider route at all. */
154
+ registerProvider: true,
155
+ }
156
+
157
+ /**
158
+ * Activate the plugin.
159
+ * @param {any} ctx the Host plugin context.
160
+ * @param {any} config the row's configuration.
161
+ */
162
+ export function apply(ctx, config = {}) {
163
+ /**
164
+ * The settings namespace this plugin owns.
165
+ *
166
+ * Read from the Loader entry rather than hard-coded: the entry id is what the
167
+ * profile patch names, and a hard-coded string silently stops matching the
168
+ * moment a user renames the row. `ctx.fiber.entry` is added by the Loader, so
169
+ * it is absent on a host that mounts the plugin directly — hence the probe
170
+ * with a documented fallback, which mirrors the first-party plugins.
171
+ */
172
+ const settingsNs =
173
+ typeof ctx?.fiber?.entry?.options?.id === 'string' && ctx.fiber.entry.options.id !== ''
174
+ ? ctx.fiber.entry.options.id
175
+ : name
176
+
177
+ const settings = { ...DEFAULTS, ...config }
178
+ // Restore before timers and adapters start; preferences never include credentials.
179
+ try { Object.assign(settings, validatePreferences(readPreferences())) } catch {}
180
+ const usage = createUsageStore({ enabled: () => settings.usageEnabled !== false })
181
+ const healthChecks = new Map()
182
+ const healthCache = new Map()
183
+ let rescheduleCatalog = () => {}
184
+ if (settings.enabled === false) return
185
+
186
+ const logger = createLogger()
187
+ const credentials = new CredentialProvider()
188
+ const catalog = new Catalog({ log: logger })
189
+ // A restart begins on the fallback table until the first refresh lands. A
190
+ // persisted catalog means the picker is right the moment the plugin loads.
191
+ catalog.configure({ enabledIds: settings.enabledModelIds, overrides: settings.modelOverrides })
192
+ const CATALOG_CACHE = join(CONFIG_DIR, 'catalog.json')
193
+ if (catalog.loadPersisted(CATALOG_CACHE)) {
194
+ logger(`已加载上次的模型清单(${catalog.models().length} 个),等待刷新确认`)
195
+ }
196
+
197
+ // One gateway client for the read-only endpoints, rebuilt when the
198
+ // credential is renewed.
199
+ /** @type {{client: MadaoClient, signature: string}|null} */
200
+ let shared = null
201
+ const client = async () => {
202
+ const resolved = await credentials.resolve()
203
+ const signature = `${resolved.key.ak}:${resolved.key.securityToken}`
204
+ if (shared?.signature === signature) return { client: shared.client, resolved }
205
+ const next = new MadaoClient({
206
+ credentials: resolved.key,
207
+ gateway: settings.gateway,
208
+ })
209
+ shared = { client: next, signature }
210
+ return { client: next, resolved }
211
+ }
212
+
213
+ // ── the LLM adapter ──────────────────────────────────────────────────────
214
+ if (settings.registerProvider !== false) {
215
+ const adapter = createCodeArtsAdapter({
216
+ credentials,
217
+ catalog,
218
+ usage,
219
+ gateway: () => settings.gateway,
220
+ attachments: () => ctx.get('attachments'),
221
+ log: logger,
222
+ })
223
+ ctx.effect(() => ctx.llm.registerAdapter([PROVIDER_ID], adapter), 'codearts: llm adapter')
224
+
225
+ // The adapter alone is NOT enough. Settings → Models builds its rows by
226
+ // joining the registered routes with this directory and then rendering the
227
+ // DIRECTORY: a provider with an adapter but no directory entry has no row
228
+ // there at all, so the plugin looked half-installed — its models routable
229
+ // from the picker yet invisible in the page where a user inspects and edits
230
+ // providers. One registration, two surfaces.
231
+ ctx.effect(
232
+ () =>
233
+ ctx.llm.registerConfigurableProviders([
234
+ {
235
+ provider: PROVIDER_ID,
236
+ displayName: PROVIDER_NAME,
237
+ settingsNs,
238
+ settingsPath: [],
239
+ declared: false,
240
+ },
241
+ ]),
242
+ 'codearts: configurable provider directory',
243
+ )
244
+
245
+ // Offer model discovery in the shape that settings surface expects, so a
246
+ // provider edited there can interrogate this plugin's catalog.
247
+ ctx.effect(
248
+ () =>
249
+ ctx.llm.registerModelDiscovery(settingsNs, async () => {
250
+ if (catalog.source !== 'gateway') return []
251
+ return catalog.models().map((model) => ({
252
+ id: model.id,
253
+ name: model.ratio ? `${model.name} · ${model.ratio}` : model.name,
254
+ contextWindow: model.context,
255
+ maxTokens: model.maxOutput,
256
+ inputModalities: model.supportsImages ? ['text', 'image'] : ['text'],
257
+ }))
258
+ }),
259
+ 'codearts: model discovery',
260
+ )
261
+ }
262
+
263
+ // ── catalog refresh ──────────────────────────────────────────────────────
264
+ let refreshing = null
265
+ const refresh = async () => {
266
+ if (refreshing) return refreshing
267
+ refreshing = (async () => {
268
+ try {
269
+ const { client: gateway } = await client()
270
+ const result = await catalog.refresh(gateway)
271
+ if (result.changed) {
272
+ // Persist before announcing, so a crash between the two leaves the
273
+ // cache consistent with what listeners were told.
274
+ catalog.persist(CATALOG_CACHE)
275
+ // Advertise the new catalog; the selector reloads on this event.
276
+ ctx.emit('llm/models-updated', PROVIDER_ID)
277
+ }
278
+ return result
279
+ } catch (error) {
280
+ logger(`刷新失败:${error?.message ?? error}`)
281
+ return { changed: false, source: catalog.source, error: String(error?.message ?? error) }
282
+ } finally {
283
+ refreshing = null
284
+ }
285
+ })()
286
+ return refreshing
287
+ }
288
+
289
+ // A first refresh that fails must not prevent activation: the plugin still
290
+ // serves its settings page, which is where the user fixes the credential.
291
+ void refresh()
292
+
293
+ // Auto check-in runs from the Host, not the page: the settings panel is not
294
+ // open at the hour a daily claim usually becomes available, and a timer in the
295
+ // browser would simply never fire. It reads the saved switch each time, so
296
+ // turning it off takes effect without a restart.
297
+ ctx.effect(() => {
298
+ const sweep = async () => {
299
+ if (settings.autoCheckin !== true) return
300
+ try {
301
+ const store = readStore()
302
+ const targets = []
303
+ for (const account of store.accounts) {
304
+ try {
305
+ targets.push({
306
+ id: account.id,
307
+ client: new MadaoClient({ credentials: await tripleOf(account), gateway: settings.gateway }),
308
+ })
309
+ } catch {
310
+ // An account whose key cannot be exchanged is skipped.
311
+ }
312
+ }
313
+ if (targets.length > 0) {
314
+ await runAutoCheckin({ targets })
315
+ healthCache.clear()
316
+ healthChecks.clear()
317
+ }
318
+ } catch (error) {
319
+ logger(`自动签到失败:${error?.message ?? error}`)
320
+ }
321
+ }
322
+ // Hourly is enough for a once-a-day entitlement, and the day guard makes a
323
+ // frequent timer harmless: it can skip, never double-claim.
324
+ const timer = setInterval(() => void sweep(), 60 * 60 * 1000)
325
+ timer.unref?.()
326
+ void sweep()
327
+ return () => clearInterval(timer)
328
+ }, 'codearts: auto check-in')
329
+
330
+ ctx.effect(() => {
331
+ let timer
332
+ let disposed = false
333
+ const schedule = () => {
334
+ clearTimeout(timer)
335
+ if (disposed) return
336
+ timer = setTimeout(async () => { await refresh(); schedule() }, Math.max(60000, Number(settings.refreshIntervalMs) || DEFAULT_REFRESH_MS))
337
+ timer.unref?.()
338
+ }
339
+ rescheduleCatalog = schedule
340
+ schedule()
341
+ return () => { disposed = true; clearTimeout(timer); rescheduleCatalog = () => {} }
342
+ }, 'codearts: catalog refresh timer')
343
+
344
+ // ── HTTP surface for the settings page and the chip ──────────────────────
345
+ ctx.inject(['webServer'], (webCtx) => {
346
+ const route = (path, handler) => {
347
+ webCtx.effect(
348
+ () =>
349
+ webCtx.webServer.register({
350
+ // EXACT, not prefix: each of these is one path. A prefix registration
351
+ // makes `/models` also claim `/models/select`, so a missing route
352
+ // silently answers with a neighbour's payload instead of a 404 —
353
+ // which is exactly how "saving the model selection did nothing"
354
+ // looked like a save bug.
355
+ kind: 'exact',
356
+ path: `${ROUTE_PREFIX}${path}`,
357
+ handler: (req, res) => {
358
+ void handleRoute(req, res, handler)
359
+ },
360
+ }),
361
+ `codearts: route ${path}`,
362
+ )
363
+ }
364
+
365
+ const deps = { credentials, catalog, client, refresh, logger, settings, ctx, settingsNs, usage, healthChecks, healthCache, rescheduleCatalog: () => rescheduleCatalog(), invalidateAccounts: () => { healthCache.clear(); healthChecks.clear(); tripleCache.clear() } }
366
+
367
+ registerFeatureRoutes(route, deps, readJsonBody)
368
+
369
+ route('/status', () => buildStatus(deps))
370
+ route('/models', () => buildModels(deps))
371
+ route('/account', () => buildAccount(deps))
372
+ route('/save', (req) => handleSave(req, deps))
373
+ route('/test', () => handleTest(deps))
374
+ route('/refresh', () => handleRefresh(deps))
375
+ route('/benefits', () => handleBenefits(deps))
376
+ route('/claim', (req) => handleClaim(req, deps))
377
+ route('/clear', () => handleClear(deps))
378
+
379
+ // The account pool.
380
+ route('/accounts', () => handleAccounts(deps))
381
+ route('/accounts/add', (req) => handleAccountAdd(req, deps))
382
+ route('/accounts/preview', (req) => handleAccountPreview(req, deps))
383
+ route('/accounts/import', (req) => handleAccountImport(req, deps))
384
+ route('/accounts/remove', (req) => handleAccountRemove(req, deps))
385
+ route('/accounts/activate', (req) => handleAccountActivate(req, deps))
386
+ route('/accounts/rename', (req) => handleAccountRename(req, deps))
387
+ route('/accounts/check', (req) => handleAccountCheck(req, deps))
388
+ route('/accounts/export', () => handleAccountExport(deps))
389
+
390
+ // Daily check-in.
391
+ route('/models/select', (req) => handleModelSelection(req, deps))
392
+ route('/checkin', () => handleCheckinStatus(deps))
393
+ route('/checkin/claim', (req) => handleCheckinClaim(req, deps))
394
+ route('/checkin/auto', (req) => handleAutoCheckin(req, deps))
395
+ })
396
+
397
+ // Release the renewal timer when the plugin unloads.
398
+ ctx.effect(() => () => credentials.dispose(), 'codearts: credential renewal')
399
+
400
+ logger(`已注册 provider "${PROVIDER_ID}";目录来源:${catalog.source}`)
401
+ }
402
+
403
+ // ── route handlers ─────────────────────────────────────────────────────────
404
+
405
+ /**
406
+ * A handler receives the parsed request and returns a JSON-serialisable value.
407
+ * Throwing answers 500 with the message, so error reporting is one code path.
408
+ */
409
+
410
+ async function buildStatus(deps) {
411
+ const located = locateStore()
412
+ const saved = readSavedCredentials()
413
+ const candidates = listCandidates()
414
+ return {
415
+ ok: true,
416
+ provider: PROVIDER_ID,
417
+ providerName: PROVIDER_NAME,
418
+ catalog: {
419
+ source: deps.catalog.source,
420
+ models: deps.catalog.models().length,
421
+ refreshedAt: deps.catalog.refreshedAt ?? null,
422
+ error: deps.catalog.lastError ?? null,
423
+ },
424
+ credential: {
425
+ configured: candidates.length > 0,
426
+ // The file actually read, and where a save would go. They differ on an
427
+ // install that predates the account store, and saying only the latter
428
+ // makes a path-based diagnosis report a file that does not exist.
429
+ pathInUse: located.path,
430
+ path: CREDENTIAL_PATH,
431
+ source: deps.credentials.source ?? null,
432
+ sourceLabel: deps.credentials.sourceLabel ?? null,
433
+ savedAk: saved ? maskKey(saved.ak) : null,
434
+ savedSk: saved ? maskKey(saved.sk) : null,
435
+ path: CREDENTIAL_PATH,
436
+ error: deps.credentials.errorText ?? null,
437
+ candidates: candidates.map((candidate) => ({
438
+ source: candidate.source,
439
+ label: candidate.label,
440
+ })),
441
+ },
442
+ // What the settings page gates on, reported rather than guessed. A missing
443
+ // model card has exactly two silent causes, and this answers both:
444
+ // Settings → Models emits a namespace only for an entry whose
445
+ // `fiber.runtime.Config` exists AND has `toJSON`, then hides any row whose
446
+ // namespace did not resolve.
447
+ registration: {
448
+ provider: PROVIDER_ID,
449
+ settingsNs: deps.settingsNs,
450
+ // Gate 1: the Host's `schema(entry)` returns undefined without this.
451
+ configSchema: typeof Config === 'function' && typeof Config.toJSON === 'function',
452
+ // Gate 2: the row is skipped when its namespace is absent.
453
+ settingsPath: [],
454
+ },
455
+ settings: {
456
+ lowBalanceEnabled: deps.settings.lowBalanceEnabled,
457
+ lowBalanceThreshold: deps.settings.lowBalanceThreshold,
458
+ usageEnabled: deps.settings.usageEnabled,
459
+ composerChip: deps.settings.composerChip !== false,
460
+ refreshIntervalMs: deps.settings.refreshIntervalMs ?? DEFAULT_REFRESH_MS,
461
+ gateway: deps.settings.gateway ?? null,
462
+ },
463
+ }
464
+ }
465
+
466
+ async function buildModels(deps) {
467
+ // Effective models, not the raw roster: `defaultStrength` here is what the
468
+ // ADAPTER will use, so a page that reported the upstream value would show one
469
+ // thing and send another.
470
+ const all = deps.catalog.models().map((model) => deps.catalog.effective(model))
471
+ const overrides = deps.settings.modelOverrides ?? {}
472
+ const selectionIsDefault = deps.settings.enabledModelIds === null
473
+ return {
474
+ ok: true,
475
+ source: deps.catalog.source,
476
+ refreshedAt: deps.catalog.refreshedAt ?? null,
477
+ error: deps.catalog.lastError ?? null,
478
+ // The selection, so the card can render the ticks and the "changed" marker.
479
+ enabledIds: selectionIsDefault ? null : deps.catalog.visible().map((model) => model.id),
480
+ total: all.length,
481
+ presets: deps.settings.modelPresets,
482
+ models: all.map((model) => ({
483
+ enabled: deps.catalog.isEnabled(model.id),
484
+ overrides: overrides[model.id] ?? null,
485
+ defaults: (() => {
486
+ const base = deps.catalog.find(model.id)
487
+ return { supportsImages: base?.supportsImages === true, allowOff: base?.allowOff !== false, defaultStrength: base?.defaultStrength ?? null }
488
+ })(),
489
+ id: model.id,
490
+ name: model.name,
491
+ context: model.context,
492
+ maxOutput: model.maxOutput,
493
+ ratio: model.ratio ?? null,
494
+ supportsImages: model.supportsImages,
495
+ allowOff: model.allowOff !== false,
496
+ strengths: model.strengths,
497
+ defaultStrength: model.defaultStrength ?? null,
498
+ description: model.description ?? null,
499
+ })),
500
+ }
501
+ }
502
+
503
+ async function buildAccount(deps) {
504
+ try {
505
+ const { client, resolved } = await deps.client()
506
+ const identity = parseIdentity(resolved.key.securityToken)
507
+ const [credit, roles] = await Promise.all([readCredit(client), readRoles(client)])
508
+ return {
509
+ ok: true,
510
+ account: identity.accountName ?? null,
511
+ accountId: deps.credentials.accountId ?? resolved.source,
512
+ userId: identity.userId ?? null,
513
+ source: resolved.source,
514
+ sourceLabel: resolved.label,
515
+ temporary: resolved.source === 'codearts',
516
+ expiresAt: resolved.expiresAtMs ?? null,
517
+ credit,
518
+ roles,
519
+ lowBalance: isLowBalance(credit, deps.settings),
520
+ lowBalanceThreshold: deps.settings.lowBalanceThreshold,
521
+ composerChip: deps.settings.composerChip !== false,
522
+ health: accountHealth({ credit }),
523
+ }
524
+ } catch (error) {
525
+ return {
526
+ ok: false,
527
+ composerChip: deps.settings.composerChip !== false,
528
+ stage: error instanceof CredentialError ? 'credentials' : 'gateway',
529
+ error: error?.message ?? String(error),
530
+ }
531
+ }
532
+ }
533
+
534
+ async function handleSave(req, deps) {
535
+ const body = await readJsonBody(req)
536
+ if (typeof body.ak !== 'string' || typeof body.sk !== 'string') {
537
+ throw new HttpError(400, 'ak 和 sk 都必须是字符串')
538
+ }
539
+ const saved = await saveCredentials(body.ak, body.sk)
540
+ // A new pair must be exchanged before the next request, so drop the cache.
541
+ deps.credentials.invalidate()
542
+ void deps.refresh()
543
+ return { ok: true, ak: maskKey(saved.ak), sk: maskKey(saved.sk) }
544
+ }
545
+
546
+ async function handleClear(deps) {
547
+ await clearCredentials()
548
+ deps.invalidateAccounts()
549
+ deps.credentials.invalidate()
550
+ return { ok: true }
551
+ }
552
+
553
+ // ── account pool ───────────────────────────────────────────────────────────
554
+
555
+ /**
556
+ * The pool, with per-account credit and check-in state.
557
+ *
558
+ * Credit and check-in are read per account, which costs one gateway round trip
559
+ * each — so they are read only when this route is called (the settings page is
560
+ * open), never on a timer.
561
+ */
562
+ async function inspectAccount(account, deps, force = false) {
563
+ const signature = createHash('sha256').update(`${account.ak}:${account.sk}`).digest('hex')
564
+ const existing = deps.healthChecks.get(account.id)
565
+ if (existing?.signature === signature) return existing.promise
566
+ const operation = (async () => {
567
+ if (force) tripleCache.delete(account.id)
568
+ const entry = { ...publicAccount(account, readStore()), credit: null, checkin: null, error: null }
569
+ let failure
570
+ try {
571
+ const client = new MadaoClient({ credentials: await tripleOf(account), gateway: deps.settings.gateway })
572
+ const credit = await readCredit(client, { strict: true })
573
+ if (credit) entry.credit = { remain: credit.remain, total: credit.total, plan: credit.plan ?? null, expiring: credit.expiringTotal ?? 0 }
574
+ const checkin = await readCheckin(client, { now: new Date(), state: readCheckinState(), accountId: account.id })
575
+ entry.checkin = { available: checkin.available, claimable: checkin.claimable, claimedToday: checkin.claimedToday, amount: checkin.amount, title: checkin.title, reason: checkin.reason ?? null }
576
+ const identity = parseIdentity(tripleCache.get(account.id)?.securityToken)
577
+ if (!account.accountName && identity.accountName) {
578
+ entry.accountName = identity.accountName
579
+ await rememberAccountName(account.id, identity.accountName)
580
+ }
581
+ } catch (error) {
582
+ failure = error
583
+ entry.error = message(error)
584
+ }
585
+ entry.health = accountHealth({ error: failure, credit: entry.credit })
586
+ entry.lowBalance = isLowBalance(entry.credit, deps.settings)
587
+ const current = readStore().accounts.find((item) => item.id === account.id)
588
+ if (current?.sk === account.sk && deps.healthChecks.get(account.id)?.promise === operation) deps.healthCache.set(account.id, entry)
589
+ return entry
590
+ })()
591
+ deps.healthChecks.set(account.id, { signature, promise: operation })
592
+ try { return await operation } finally {
593
+ if (deps.healthChecks.get(account.id)?.promise === operation) deps.healthChecks.delete(account.id)
594
+ }
595
+ }
596
+ async function handleAccounts(deps) {
597
+ const store = readStore()
598
+ const accounts = []
599
+ for (const account of store.accounts) {
600
+ const cached = deps.healthCache.get(account.id)
601
+ const entry = cached && Date.now() - cached.health.checkedAt < 60000 ? { ...cached, ...publicAccount(account, store) } : await inspectAccount(account, deps)
602
+ accounts.push({ ...entry, lowBalance: isLowBalance(entry.credit, deps.settings) })
603
+ }
604
+ return {
605
+ ok: true, version: STORE_VERSION, activeId: store.activeId, accounts,
606
+ today: todaySummary(accounts.map(({ id, label }) => ({ id, label })), new Date()),
607
+ autoCheckin: deps.settings.autoCheckin === true,
608
+ lowBalanceEnabled: deps.settings.lowBalanceEnabled !== false,
609
+ lowBalanceThreshold: deps.settings.lowBalanceThreshold,
610
+ }
611
+ }
612
+ async function handleAccountCheck(req, deps) {
613
+ const { id } = await readJsonBody(req)
614
+ const account = readStore().accounts.find((entry) => entry.id === id)
615
+ if (!account) throw new HttpError(404, '账号不存在')
616
+ return { ok: true, account: await inspectAccount(account, deps, true) }
617
+ }
618
+
619
+ /**
620
+ * Cached signed triples, keyed by account id.
621
+ *
622
+ * The pool reads credit and check-in for several accounts in one pass; without
623
+ * a cache that is one STS exchange per account per refresh, which both wastes
624
+ * requests and risks the IAM rate limit. Renewal is the provider's job for the
625
+ * active account; this cache only serves the read-only pool view.
626
+ */
627
+ const tripleCache = new Map()
628
+
629
+ /** Resolve a signed triple for one account, reusing it while it is fresh. */
630
+ async function tripleOf(account) {
631
+ const signature = createHash('sha256').update(`${account.ak}:${account.sk}`).digest('hex')
632
+ const cached = tripleCache.get(account.id)
633
+ if (cached && cached.sourceSignature === signature && Date.now() < cached.expiresAt - 300_000) return cached
634
+ const sts = await getSts(account.ak, account.sk)
635
+ const triple = {
636
+ sourceSignature: signature,
637
+ ak: sts.ak,
638
+ sk: sts.sk,
639
+ securityToken: sts.securityToken,
640
+ expiresAt: Date.parse(sts.expiresAt) || Date.now() + 3600_000,
641
+ }
642
+ tripleCache.set(account.id, triple)
643
+ return triple
644
+ }
645
+
646
+ async function handleAccountAdd(req, deps) {
647
+ const body = await readJsonBody(req)
648
+ const result = await addAccount({
649
+ ak: typeof body.ak === 'string' ? body.ak : '',
650
+ sk: typeof body.sk === 'string' ? body.sk : '',
651
+ label: typeof body.label === 'string' ? body.label : undefined,
652
+ })
653
+ deps.healthCache.delete(result.account.id)
654
+ deps.healthChecks.delete(result.account.id)
655
+ tripleCache.delete(result.account.id)
656
+ deps.credentials.invalidate()
657
+ void deps.refresh()
658
+ return { ok: true, added: result.added, id: result.account.id }
659
+ }
660
+
661
+ /**
662
+ * Import accounts from pasted text or an uploaded file's contents.
663
+ *
664
+ * The browser sends the text; parsing lives on the Host so the same rules apply
665
+ * to a CSV dropped in and to one pasted into the box.
666
+ */
667
+ /**
668
+ * Parse a picked file and report what it holds, writing nothing.
669
+ *
670
+ * The confirmation is what needs the user's attention, so the parsed entries are
671
+ * shown before anything is written: an import that silently took a file the user
672
+ * mis-clicked is worse than one that asks. Only display fields come back — the
673
+ * secrets stay on the Host and never enter the browser.
674
+ */
675
+ async function handleAccountPreview(req, deps) {
676
+ const body = await readJsonBody(req)
677
+ const text = typeof body.text === 'string' ? body.text : ''
678
+ const parsed = parseImport(text)
679
+ if (parsed.accounts.length === 0) {
680
+ throw new HttpError(400, '没有从这段内容里认出任何 AK/SK 对。支持华为云 credentials.csv、每行 AK,SK、或本插件导出的 JSON。')
681
+ }
682
+ const store = readStore()
683
+ const known = new Set(store.accounts.map((account) => account.id))
684
+ return {
685
+ ok: true,
686
+ total: parsed.accounts.length,
687
+ skipped: parsed.skipped,
688
+ accounts: parsed.accounts.map((entry, index) => ({
689
+ index,
690
+ label: entry.label ?? null,
691
+ akMasked: maskKey(entry.ak),
692
+ // Whether this entry would update an existing account rather than add one.
693
+ existing: known.has(accountIdOf(entry.ak)),
694
+ })),
695
+ }
696
+ }
697
+
698
+ async function handleAccountImport(req, deps) {
699
+ const body = await readJsonBody(req)
700
+ const parsed = parseImport(typeof body.text === 'string' ? body.text : '')
701
+ if (parsed.accounts.length === 0) {
702
+ throw new HttpError(400, '没有从这段内容里认出任何 AK/SK 对。支持华为云 credentials.csv、每行 AK,SK、或导出过的 JSON。')
703
+ }
704
+ const result = await addAccounts(parsed.accounts)
705
+ deps.invalidateAccounts()
706
+ deps.credentials.invalidate()
707
+ void deps.refresh()
708
+ return {
709
+ ok: true,
710
+ added: result.added,
711
+ updated: result.updated,
712
+ skipped: result.skipped + parsed.skipped,
713
+ total: result.store.accounts.length,
714
+ }
715
+ }
716
+
717
+ async function handleAccountRemove(req, deps) {
718
+ const body = await readJsonBody(req)
719
+ if (typeof body.id !== 'string') throw new HttpError(400, '缺少账号 id')
720
+ await removeAccount(body.id)
721
+ tripleCache.delete(body.id)
722
+ deps.healthCache.delete(body.id)
723
+ deps.healthChecks.delete(body.id)
724
+ deps.credentials.invalidate()
725
+ void deps.refresh()
726
+ return { ok: true }
727
+ }
728
+
729
+ async function handleAccountActivate(req, deps) {
730
+ const body = await readJsonBody(req)
731
+ if (typeof body.id !== 'string') throw new HttpError(400, '缺少账号 id')
732
+ await setActiveAccount(body.id)
733
+ deps.credentials.invalidate()
734
+ void deps.refresh()
735
+ return { ok: true }
736
+ }
737
+
738
+ async function handleAccountRename(req, deps) {
739
+ const body = await readJsonBody(req)
740
+ if (typeof body.id !== 'string') throw new HttpError(400, '缺少账号 id')
741
+ await renameAccount(body.id, typeof body.label === 'string' ? body.label : '')
742
+ return { ok: true }
743
+ }
744
+
745
+ /**
746
+ * Export the store as text the user can paste into another install.
747
+ *
748
+ * Returns the real keys: an export that cannot be re-imported would be useless.
749
+ * The route is loopback-only, like every other route here.
750
+ */
751
+ async function handleAccountExport(deps) {
752
+ return { ok: true, text: exportStore(readStore()) }
753
+ }
754
+
755
+ // ── daily check-in ─────────────────────────────────────────────────────────
756
+
757
+ /**
758
+ * Save the model selection and apply it without a restart.
759
+ *
760
+ * `enabledIds: null` restores "offer everything", which is what a user gets by
761
+ * pressing reset — distinct from an empty array, which would mean "offer
762
+ * nothing" and leave the picker empty with no way back.
763
+ */
764
+ async function handleModelSelection(req, deps) {
765
+ const body = await readJsonBody(req)
766
+ const enabledIds = Array.isArray(body.enabledIds)
767
+ ? body.enabledIds.filter((id) => typeof id === 'string' && id !== '')
768
+ : body.enabledIds === null
769
+ ? null
770
+ : undefined
771
+ if (enabledIds === undefined) throw new HttpError(400, 'enabledIds 必须是字符串数组或 null')
772
+
773
+ const overrides = {}
774
+ if (body.overrides !== null && typeof body.overrides === 'object') {
775
+ for (const [id, value] of Object.entries(body.overrides)) {
776
+ if (value === null || typeof value !== 'object') continue
777
+ const entry = {}
778
+ if (typeof value.images === 'boolean') entry.images = value.images
779
+ if (typeof value.allowOff === 'boolean') entry.allowOff = value.allowOff
780
+ if (typeof value.defaultStrength === 'string' && value.defaultStrength !== '') {
781
+ entry.defaultStrength = value.defaultStrength
782
+ }
783
+ if (Object.keys(entry).length > 0) overrides[id] = entry
784
+ }
785
+ }
786
+
787
+ await applyPreferences(deps, { enabledModelIds: enabledIds, modelOverrides: overrides })
788
+ // Announce the new catalog so the picker reloads without a restart.
789
+ deps.ctx.emit('llm/models-updated', PROVIDER_ID)
790
+ return { ok: true, enabled: deps.catalog.visible().length, total: deps.catalog.models().length }
791
+ }
792
+
793
+ async function handleCheckinStatus(deps) {
794
+ const store = readStore()
795
+ const now = new Date()
796
+ const state = readCheckinState()
797
+ const accounts = []
798
+ for (const account of store.accounts) {
799
+ const entry = { id: account.id, label: account.label ?? defaultLabel(account.ak), state: null, error: null }
800
+ try {
801
+ const client = new MadaoClient({ credentials: await tripleOf(account), gateway: deps.settings.gateway })
802
+ entry.state = await readCheckin(client, { now, state, accountId: account.id })
803
+ } catch (error) {
804
+ entry.error = error?.message ?? String(error)
805
+ }
806
+ accounts.push(entry)
807
+ }
808
+ return {
809
+ ok: true,
810
+ accounts,
811
+ today: todaySummary(accounts, now),
812
+ autoCheckin: deps.settings.autoCheckin === true,
813
+ }
814
+ }
815
+
816
+ /** Claim the daily bonus for one account, on an explicit click. */
817
+ async function handleCheckinClaim(req, deps) {
818
+ const body = await readJsonBody(req)
819
+ const id = typeof body.id === 'string' ? body.id : undefined
820
+ const store = readStore()
821
+ const account = id ? store.accounts.find((entry) => entry.id === id) : activeAccount(store)
822
+ if (!account) throw new HttpError(400, '没有这个账号')
823
+ try {
824
+ const client = new MadaoClient({ credentials: await tripleOf(account), gateway: deps.settings.gateway })
825
+ const result = await claimDaily(client, { accountId: account.id })
826
+ deps.healthCache.delete(account.id)
827
+ deps.healthChecks.delete(account.id)
828
+ return { ok: true, ...result, label: account.label ?? defaultLabel(account.ak) }
829
+ } catch (error) {
830
+ return { ok: false, claimed: false, reason: error?.message ?? String(error) }
831
+ }
832
+ }
833
+
834
+ /**
835
+ * Run auto check-in now.
836
+ *
837
+ * `enabled` reflects the saved switch; turning it on is a separate, explicit
838
+ * action, and this handler only runs the sweep. It never becomes a timer here —
839
+ * the timer is the plugin's, so a page that is closed still checks in.
840
+ */
841
+ async function handleAutoCheckin(req, deps) {
842
+ const body = await readJsonBody(req)
843
+ deps.healthCache.clear()
844
+ deps.healthChecks.clear()
845
+ // `enabled` changes the standing preference. The one-off button sends
846
+ // `now: true` instead, so pressing it never opts a user into daily
847
+ // automation — an action and a preference are different things.
848
+ const oneOff = body.now === true
849
+ if (!oneOff && typeof body.enabled === 'boolean' && body.enabled !== deps.settings.autoCheckin) {
850
+ deps.settings.autoCheckin = body.enabled
851
+ // Remember the choice across restarts without editing the profile patch.
852
+ await persistAutoCheckin(body.enabled)
853
+ }
854
+ if (!oneOff && body.enabled === false) return { ok: true, enabled: false, summary: null }
855
+
856
+ const store = readStore()
857
+ const targets = []
858
+ for (const account of store.accounts) {
859
+ try {
860
+ targets.push({
861
+ id: account.id,
862
+ client: new MadaoClient({ credentials: await tripleOf(account), gateway: deps.settings.gateway }),
863
+ })
864
+ } catch {
865
+ // An account whose key cannot be exchanged is skipped, not fatal.
866
+ }
867
+ }
868
+ const summary = await runAutoCheckin({ targets })
869
+ deps.healthCache.clear()
870
+ deps.healthChecks.clear()
871
+ return { ok: true, enabled: deps.settings.autoCheckin === true, summary }
872
+ }
873
+
874
+ /**
875
+ * Persist a preference beside the account store.
876
+ *
877
+ * One writer for every switch: the preferences file is small and shared, and a
878
+ * second writer would eventually read-modify-write over the first's key.
879
+ */
880
+ /** Persist the auto check-in switch. */
881
+ async function persistAutoCheckin(enabled) {
882
+ await persistPreferences({ autoCheckin: enabled })
883
+ }
884
+
885
+ async function handleTest(deps) {
886
+ const steps = []
887
+ try {
888
+ const { client, resolved } = await deps.client()
889
+ steps.push({ step: '凭证', ok: true, detail: resolved.label })
890
+
891
+ try {
892
+ const key = await client.ensureSessionKey()
893
+ steps.push({
894
+ step: '会话密钥',
895
+ ok: true,
896
+ detail: `keyId ${key.keyId},剩余 ${Math.round((key.expiresAt - Date.now()) / 1000)} 秒`,
897
+ })
898
+ } catch (error) {
899
+ steps.push({ step: '会话密钥', ok: false, detail: message(error) })
900
+ return { ok: false, steps }
901
+ }
902
+
903
+ const refreshResult = await deps.refresh()
904
+ steps.push({
905
+ step: '模型清单',
906
+ ok: refreshResult.source === 'gateway',
907
+ detail:
908
+ refreshResult.source === 'gateway'
909
+ ? `${deps.catalog.models().length} 个模型`
910
+ : (refreshResult.error ?? '退回兜底清单'),
911
+ })
912
+
913
+ const credit = await readCredit(client)
914
+ steps.push({
915
+ step: '积分',
916
+ ok: credit !== null,
917
+ detail: credit ? `剩余 ${credit.remain} / 共 ${credit.total}` : '读不到积分(不影响对话)',
918
+ })
919
+
920
+ const identity = parseIdentity(resolved.key.securityToken)
921
+ if (identity.accountName) {
922
+ steps.push({ step: '账号', ok: true, detail: identity.accountName })
923
+ }
924
+
925
+ return { ok: steps.every((step) => step.ok), steps }
926
+ } catch (error) {
927
+ steps.push({
928
+ step: '凭证',
929
+ ok: false,
930
+ detail: error instanceof CredentialError ? error.message : message(error),
931
+ })
932
+ return { ok: false, steps }
933
+ }
934
+ }
935
+
936
+ async function handleRefresh(deps) {
937
+ const result = await deps.refresh()
938
+ return {
939
+ ok: result.source === 'gateway',
940
+ source: result.source,
941
+ models: deps.catalog.models().length,
942
+ error: result.error ?? null,
943
+ }
944
+ }
945
+
946
+ async function handleBenefits(deps) {
947
+ try {
948
+ const { client } = await deps.client()
949
+ const items = await listBenefits(client)
950
+ return { ok: true, items }
951
+ } catch (error) {
952
+ return { ok: false, error: message(error), items: [] }
953
+ }
954
+ }
955
+
956
+ async function handleClaim(req, deps) {
957
+ const body = await readJsonBody(req)
958
+ const campaignId = Number(body.campaignId)
959
+ if (!Number.isInteger(campaignId)) throw new HttpError(400, 'campaignId 必须是整数')
960
+ try {
961
+ const { client } = await deps.client()
962
+ const result = await claimBenefit(client, campaignId)
963
+ if (!result.ok) return { ok: false, error: result.reason }
964
+ return { ok: true, reply: result.reply }
965
+ } catch (error) {
966
+ return { ok: false, error: message(error) }
967
+ }
968
+ }
969
+
970
+ // ── plumbing ───────────────────────────────────────────────────────────────
971
+
972
+ /** An HTTP failure with an explicit status. */
973
+ class HttpError extends Error {
974
+ constructor(status, messageText) {
975
+ super(messageText)
976
+ this.status = status
977
+ }
978
+ }
979
+
980
+ /**
981
+ * Run one handler and answer in JSON.
982
+ *
983
+ * Every route is loopback-only: the settings surface reads credentials and
984
+ * the account balance, and a hostname resolving to 127.0.0.1 must not reach
985
+ * it from a browser.
986
+ */
987
+ async function handleRoute(req, res, handler) {
988
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1')
989
+ try {
990
+ if (!isLoopback(req)) {
991
+ return json(res, 403, { ok: false, error: '只接受本机请求' })
992
+ }
993
+
994
+ const path = resolveHandlerPath(url.pathname)
995
+ if (path === null) return json(res, 404, { ok: false, error: 'unknown route' })
996
+
997
+ // Mutating routes are POST-only: a read route may answer GET so a link in
998
+ // the page still works, but nothing that changes state answers a GET, or a
999
+ // prefetch or an accidental refresh could clear the saved credentials.
1000
+ const mutating = MUTATING_PATHS.has(path)
1001
+ if (mutating ? req.method === 'POST' : req.method === 'GET' || req.method === 'POST') {
1002
+ const value = await handler(req, url)
1003
+ return json(res, 200, value)
1004
+ }
1005
+ if (mutating) res.setHeader('Allow', 'POST')
1006
+ return json(res, 405, { ok: false, error: 'method not allowed' })
1007
+ } catch (error) {
1008
+ const status = error instanceof HttpError ? error.status : error instanceof InputError ? 400 : 500
1009
+ return json(res, status, { ok: false, error: message(error) })
1010
+ }
1011
+ }
1012
+
1013
+ /** Routes that change state and therefore accept POST only. */
1014
+ const MUTATING_PATHS = new Set([
1015
+ '/preferences/save', '/presets', '/usage/clear', '/accounts/check',
1016
+ '/backup/export', '/backup/preview', '/backup/restore',
1017
+ '/models/select',
1018
+ '/save',
1019
+ '/clear',
1020
+ '/claim',
1021
+ '/accounts/add',
1022
+ '/accounts/import',
1023
+ '/accounts/remove',
1024
+ '/accounts/activate',
1025
+ '/accounts/rename',
1026
+ '/checkin/claim',
1027
+ '/checkin/auto',
1028
+ ])
1029
+
1030
+ /** The exact sub-path of a plugin route, or null when it is not one. */
1031
+ function resolveHandlerPath(pathname) {
1032
+ if (!pathname.startsWith(ROUTE_PREFIX)) return null
1033
+ const rest = pathname.slice(ROUTE_PREFIX.length)
1034
+ return rest === '' ? null : rest
1035
+ }
1036
+
1037
+ /** Whether the request arrived over the loopback interface. */
1038
+ function isLoopback(req) {
1039
+ const address = req.socket?.remoteAddress ?? ''
1040
+ return (
1041
+ address === '127.0.0.1' ||
1042
+ address === '::1' ||
1043
+ address === '::ffff:127.0.0.1' ||
1044
+ address.startsWith('127.')
1045
+ )
1046
+ }
1047
+
1048
+ /** Read and parse a JSON request body. */
1049
+ async function readJsonBody(req) {
1050
+ const chunks = []
1051
+ let size = 0
1052
+ for await (const chunk of req) {
1053
+ size += chunk.length
1054
+ // A credential blob is tiny; anything larger is not this route's input.
1055
+ if (size > ((req.url ?? '').includes('/backup/') ? 1024 * 1024 : 64 * 1024)) throw new HttpError(413, '请求体过大')
1056
+ chunks.push(chunk)
1057
+ }
1058
+ if (chunks.length === 0) return {}
1059
+ let body
1060
+ try {
1061
+ body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
1062
+ } catch {
1063
+ throw new HttpError(400, '请求体不是合法 JSON')
1064
+ }
1065
+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw new HttpError(400, '请求体必须为 JSON 对象')
1066
+ return body
1067
+ }
1068
+
1069
+ /** Answer with JSON. */
1070
+ function json(res, status, value) {
1071
+ const body = JSON.stringify(value)
1072
+ res.writeHead(status, {
1073
+ 'Content-Type': 'application/json; charset=utf-8',
1074
+ 'Cache-Control': 'no-store',
1075
+ })
1076
+ res.end(body)
1077
+ }
1078
+
1079
+ /** Extract a message from any thrown value. */
1080
+ function message(error) {
1081
+ if (error instanceof GatewayError) return error.message
1082
+ return error?.message ?? String(error)
1083
+ }
1084
+
1085
+ /**
1086
+ * A bounded diagnostic logger.
1087
+ *
1088
+ * Writes to the Host log only; the settings page reads state through the
1089
+ * routes, so nothing here is the source of truth.
1090
+ */
1091
+ function createLogger() {
1092
+ const prefix = '[dsh-connect-codearts]'
1093
+ return (line) => {
1094
+ try {
1095
+ console.log(`${prefix} ${line}`)
1096
+ } catch {
1097
+ // A closed stdout must not break the plugin.
1098
+ }
1099
+ }
1100
+ }
1101
+
1102
+ /** Expose a stable id for the client half's lazy factory. */
1103
+ export const meta = {
1104
+ PROVIDER_ID,
1105
+ PROVIDER_NAME,
1106
+ credentialPath: CREDENTIAL_PATH,
1107
+ requestId: () => randomUUID(),
1108
+ }