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