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
@@ -0,0 +1,435 @@
1
+ /**
2
+ * Credential resolution and the STS cache.
3
+ *
4
+ * The gateway needs three values — AK, SK, and a security token. What a user
5
+ * actually has falls into one of three cases:
6
+ *
7
+ * A. a permanent AK/SK pair -> exchanged for STS at runtime, renewed
8
+ * B. an already-exchanged triple -> used directly, refreshed when it expires
9
+ * C. nothing configured -> borrowed from the CodeArts client's
10
+ * local sign-in state
11
+ *
12
+ * Sources are tried in that order, and each candidate is *verified* before
13
+ * it is adopted: a file that still exists but whose key was disabled would
14
+ * otherwise leave the user stuck on a source that can never work.
15
+ */
16
+
17
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
18
+ import { readFileSync, existsSync } from 'node:fs'
19
+ import { homedir } from 'node:os'
20
+ import { join } from 'node:path'
21
+ import { getSts, StsError } from './sts.js'
22
+ import { activeAccount, defaultLabel, readStore } from './accounts.js'
23
+ import {
24
+ CONFIG_DIR,
25
+ CREDENTIAL_PATH,
26
+ ENV_AK,
27
+ ENV_SK,
28
+ ENV_TOKEN,
29
+ LEGACY_CREDENTIAL_PATH,
30
+ } from './paths.js'
31
+
32
+ // Re-exported so callers that imported these from here keep working.
33
+ export { CONFIG_DIR, CREDENTIAL_PATH, ENV_AK, ENV_SK, ENV_TOKEN, LEGACY_CREDENTIAL_PATH }
34
+
35
+ /** A user-facing credential failure with actionable text. */
36
+ export class CredentialError extends Error {
37
+ constructor(message) {
38
+ super(message)
39
+ this.name = 'CredentialError'
40
+ }
41
+ }
42
+
43
+ /**
44
+ * @typedef {object} StoredKey
45
+ * @property {string} ak access key id.
46
+ * @property {string} sk secret access key.
47
+ * @property {string} [securityToken] a pre-exchanged token, when the source supplies one.
48
+ * @property {string|number} [expiresAt] token expiry.
49
+ * @property {string} [account] account name, when known.
50
+ */
51
+
52
+ /**
53
+ * @typedef {object} CredentialCandidate
54
+ * @property {StoredKey} key the credential values.
55
+ * @property {'env'|'file'|'legacy-file'|'codearts'|'config'} source which source produced it.
56
+ * @property {string} label human-readable description for the settings page.
57
+ */
58
+
59
+ /**
60
+ * Read the plugin's saved credentials, tolerating every field spelling.
61
+ * @param {string} [path] file to read.
62
+ * @returns {StoredKey|null} the parsed key, or null when absent.
63
+ */
64
+ export function readSavedCredentials(path = CREDENTIAL_PATH) {
65
+ for (const candidate of [path, LEGACY_CREDENTIAL_PATH]) {
66
+ if (!existsSync(candidate)) continue
67
+ try {
68
+ const parsed = JSON.parse(readFileSync(candidate, 'utf8'))
69
+ const key = normaliseKey(parsed)
70
+ if (key) return key
71
+ } catch {
72
+ // A corrupt file is reported by the settings page, not fatal at load
73
+ // time: another source may still work.
74
+ }
75
+ }
76
+ return null
77
+ }
78
+
79
+ /** Accept the field spellings a user may paste from the Huawei console. */
80
+ function normaliseKey(parsed) {
81
+ if (parsed === null || typeof parsed !== 'object') return null
82
+ const ak = parsed.ak ?? parsed.accessKeyId ?? parsed.access_key_id ?? parsed['Access Key Id']
83
+ const sk = parsed.sk ?? parsed.secretAccessKey ?? parsed.secret_access_key ?? parsed['Secret Access Key']
84
+ if (!ak || !sk) return null
85
+ const securityToken = parsed.securityToken ?? parsed.security_token ?? parsed.token
86
+ return {
87
+ ak: String(ak).trim(),
88
+ sk: String(sk).trim(),
89
+ ...(securityToken ? { securityToken: String(securityToken) } : {}),
90
+ ...(parsed.expiresAt ? { expiresAt: parsed.expiresAt } : {}),
91
+ ...(parsed.account ? { account: String(parsed.account) } : {}),
92
+ }
93
+ }
94
+
95
+ /** Which sources exist, most durable first. */
96
+ export function listCandidates() {
97
+ /** @type {CredentialCandidate[]} */
98
+ const candidates = []
99
+
100
+ const envAk = process.env[ENV_AK]?.trim()
101
+ const envSk = process.env[ENV_SK]?.trim()
102
+ if (envAk && envSk) {
103
+ const token = process.env[ENV_TOKEN]?.trim()
104
+ candidates.push({
105
+ key: { ak: envAk, sk: envSk, ...(token ? { securityToken: token } : {}) },
106
+ source: 'env',
107
+ label: `环境变量 ${ENV_AK} / ${ENV_SK}`,
108
+ })
109
+ }
110
+
111
+ // The account store: the active account is the one requests use. Naming it
112
+ // in the label is what lets a user see which of several accounts is live.
113
+ const store = readStore()
114
+ const active = activeAccount(store)
115
+ if (active) {
116
+ candidates.push({
117
+ key: { ak: active.ak, sk: active.sk, ...(active.accountName ? { account: active.accountName } : {}) },
118
+ source: 'file',
119
+ label: `账号「${active.label ?? defaultLabel(active.ak)}」(${CREDENTIAL_PATH})`,
120
+ accountId: active.id,
121
+ })
122
+ }
123
+
124
+ const borrowed = readCodeArtsSignIn()
125
+ if (borrowed) {
126
+ candidates.push({
127
+ key: borrowed.key,
128
+ source: 'codearts',
129
+ label: `码道客户端登录态(${borrowed.where})`,
130
+ })
131
+ }
132
+
133
+ return candidates
134
+ }
135
+
136
+ /**
137
+ * Read the signed-in credential the CodeArts client keeps on this machine.
138
+ *
139
+ * The VS Code-derived client stores its global state in a SQLite database
140
+ * (`state.vscdb`). Reading SQLite properly would need a native module the Host
141
+ * does not carry — but the credential blob sits inside that file as plain JSON
142
+ * text, so this reads the file as a string and pulls the fields out of the one
143
+ * region that matters.
144
+ *
145
+ * The anchor is what makes that safe. The file is mostly binary, and brace
146
+ * matching from an arbitrary `{` walks into unrelated data; the known marker
147
+ * `"id":"huawei-cloud-authentication"` says "the sign-in JSON starts just after
148
+ * here", so a short window past it is enough.
149
+ *
150
+ * Adopted from dsh-connect-madao (MIT, Copyright (c) 2026 XLNC-L): the anchor
151
+ * approach, the field spellings, and the min-remaining guard are that project's.
152
+ *
153
+ * @param {number} [minRemainingMs] treat a token that expires sooner as absent.
154
+ * @returns {{key: StoredKey, where: string, expiresAtMs: number|null}|null} the borrowed credential.
155
+ */
156
+ export function readCodeArtsSignIn(minRemainingMs = 5 * 60 * 1000) {
157
+ for (const path of candidateStateFiles()) {
158
+ if (!existsSync(path)) continue
159
+ let raw
160
+ try {
161
+ // Large file, but read whole: the anchor's offset is not predictable and a
162
+ // chunked scan would have to stitch JSON across chunk boundaries.
163
+ raw = readFileSync(path, 'utf8')
164
+ } catch {
165
+ continue
166
+ }
167
+ const found = parseSignInBlob(raw, path)
168
+ if (!found) continue
169
+ // Found but nearly dead: skip rather than adopt a credential that will fail
170
+ // on the first request. The next candidate may still work.
171
+ if (found.expiresAtMs !== null && found.expiresAtMs - Date.now() < minRemainingMs) continue
172
+ return found
173
+ }
174
+ return null
175
+ }
176
+
177
+ /** The known sign-in marker inside the client's state database. */
178
+ const SIGN_IN_ANCHOR = '"id":"huawei-cloud-authentication"'
179
+
180
+ /**
181
+ * Pull the credential out of the region that follows the anchor.
182
+ * @param {string} raw the whole state database as text.
183
+ * @param {string} where the file it came from, for the settings page.
184
+ * @returns {{key: StoredKey, where: string, expiresAtMs: number|null}|null} the credential.
185
+ */
186
+ function parseSignInBlob(raw, where) {
187
+ const at = raw.indexOf(SIGN_IN_ANCHOR)
188
+ if (at < 0) return null
189
+ // Fixed window rather than brace matching: the surrounding bytes are SQLite
190
+ // pages, and a brace walk from here can wander into an unrelated object.
191
+ const segment = raw.slice(at, at + 8192)
192
+ const grab = (key) => {
193
+ const match = new RegExp(`"${key}"\\s*:\\s*"([^"]*)"`).exec(segment)
194
+ return match?.[1] || undefined
195
+ }
196
+ const ak = grab('accessKey')
197
+ const sk = grab('secretKey')
198
+ const securityToken = grab('securityToken')
199
+ if (!ak || !sk || !securityToken) return null
200
+ const expires = grab('expiresAt')
201
+ const expiresAtMs = expires ? Date.parse(expires) : NaN
202
+ const account = /"account"\s*:\s*\{[^}]*"label"\s*:\s*"([^"]+)"/.exec(segment)?.[1]
203
+ return {
204
+ key: {
205
+ ak,
206
+ sk,
207
+ securityToken,
208
+ ...(Number.isFinite(expiresAtMs) ? { expiresAt: expiresAtMs } : {}),
209
+ ...(account ? { account } : {}),
210
+ },
211
+ where,
212
+ expiresAtMs: Number.isFinite(expiresAtMs) ? expiresAtMs : null,
213
+ }
214
+ }
215
+
216
+ /** The locations the CodeArts client has used for its state database. */
217
+ function candidateStateFiles() {
218
+ const home = homedir()
219
+ const appData = process.env.APPDATA ?? join(home, 'AppData', 'Roaming')
220
+ const roots = [
221
+ appData,
222
+ join(home, '.config'),
223
+ join(home, 'Library', 'Application Support'),
224
+ join(home, 'AppData', 'Roaming'),
225
+ ]
226
+ const names = ['codearts-agent', 'CodeArts Agent', 'codearts']
227
+ const files = []
228
+ for (const root of roots) {
229
+ for (const name of names) {
230
+ files.push(join(root, name, 'User', 'globalStorage', 'state.vscdb'))
231
+ }
232
+ }
233
+ return [...new Set(files)]
234
+ }
235
+
236
+ /**
237
+ * Save a permanent AK/SK pair so it survives a restart.
238
+ * @param {string} ak access key id.
239
+ * @param {string} sk secret access key.
240
+ * @returns {Promise<StoredKey>} the saved key.
241
+ */
242
+ export async function saveCredentials(ak, sk) {
243
+ const trimmedAk = (ak ?? '').trim()
244
+ const trimmedSk = (sk ?? '').trim()
245
+ if (!trimmedAk || !trimmedSk) {
246
+ throw new CredentialError('Access Key ID 和 Secret Access Key 都要填。')
247
+ }
248
+
249
+ await mkdir(CONFIG_DIR, { recursive: true })
250
+ const key = { ak: trimmedAk, sk: trimmedSk }
251
+ // Write-then-rename so an interrupted save cannot leave a half file that
252
+ // the next start would read as credentials.
253
+ const temp = `${CREDENTIAL_PATH}.tmp`
254
+ await writeFile(temp, `${JSON.stringify(key, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
255
+ await rename(temp, CREDENTIAL_PATH)
256
+ return key
257
+ }
258
+
259
+ /**
260
+ * Remove the saved credentials.
261
+ * @returns {Promise<void>} resolves when the file is gone.
262
+ */
263
+ export async function clearCredentials() {
264
+ const { rm } = await import('node:fs/promises')
265
+ await rm(CREDENTIAL_PATH, { force: true })
266
+ }
267
+
268
+ /** Mask a key for display: enough to recognise, not enough to reuse. */
269
+ export function maskKey(value) {
270
+ if (!value) return ''
271
+ const text = String(value)
272
+ if (text.length <= 8) return `${text.slice(0, 2)}****`
273
+ return `${text.slice(0, 4)}…${text.slice(-4)}`
274
+ }
275
+
276
+ /**
277
+ * A credential provider that resolves a usable triple and renews it before
278
+ * expiry, so a long session never signs with a dead token.
279
+ */
280
+ export class CredentialProvider {
281
+ /**
282
+ * @param {object} [options] provider options.
283
+ * @param {number} [options.renewMarginMs] renew this early; 10 minutes default.
284
+ */
285
+ constructor(options = {}) {
286
+ this.renewMarginMs = options.renewMarginMs ?? 600_000
287
+ this.cached = null
288
+ this.resolvedFrom = null
289
+ this.pending = null
290
+ this.renewTimer = null
291
+ this.lastError = null
292
+ }
293
+
294
+ /**
295
+ * Resolve a credential triple, using a cached one while it is fresh.
296
+ * Concurrent callers share one resolution.
297
+ * @returns {Promise<{key: StoredKey, source: string, label: string}>} the credential.
298
+ */
299
+ async resolve() {
300
+ if (this.cached && this.#isFresh()) return this.cached
301
+ if (this.pending) return this.pending
302
+ this.pending = this.#resolveUncached().finally(() => {
303
+ this.pending = null
304
+ })
305
+ return this.pending
306
+ }
307
+
308
+ /** Whether the cached triple is still usable with margin. */
309
+ #isFresh() {
310
+ if (!this.cached) return false
311
+ if (this.cached.expiresAtMs === undefined) return true
312
+ return Date.now() < this.cached.expiresAtMs - this.renewMarginMs
313
+ }
314
+
315
+ /** Try each source in order, adopting the first that verifies. */
316
+ async #resolveUncached() {
317
+ const candidates = listCandidates()
318
+ if (candidates.length === 0) {
319
+ throw new CredentialError(
320
+ '未找到码道凭证。任选其一:\n' +
321
+ ` A) 环境变量 ${ENV_AK} / ${ENV_SK}\n` +
322
+ ` B) 在「设置 → 码道」填写永久 AK/SK(写入 ${CREDENTIAL_PATH})\n` +
323
+ ' C) 打开一次码道客户端并确认已登录 —— 插件会自动借用它的登录态\n' +
324
+ 'ak/sk 是华为云 IAM 访问密钥(控制台 → 我的凭证 → 访问密钥);STS 临时令牌由插件自动换取。',
325
+ )
326
+ }
327
+
328
+ const failures = []
329
+ for (const candidate of candidates) {
330
+ try {
331
+ const resolved = await this.#verify(candidate)
332
+ this.cached = resolved
333
+ this.resolvedFrom = candidate
334
+ this.lastError = null
335
+ this.#scheduleRenewal()
336
+ return resolved
337
+ } catch (error) {
338
+ failures.push(`${candidate.label} → ${error?.message ?? error}`)
339
+ }
340
+ }
341
+
342
+ this.lastError = `所有凭证来源都不可用:\n${failures.map((line) => ` ${line}`).join('\n')}`
343
+ throw new CredentialError(this.lastError)
344
+ }
345
+
346
+ /** Exchange (or accept) one candidate's credentials. */
347
+ async #verify(candidate) {
348
+ const key = candidate.key
349
+
350
+ // A pre-exchanged triple is used as-is; nothing to verify offline.
351
+ if (key.securityToken) {
352
+ return {
353
+ key,
354
+ source: candidate.source,
355
+ label: candidate.label,
356
+ expiresAtMs: toEpochMs(key.expiresAt) ?? undefined,
357
+ }
358
+ }
359
+
360
+ // A permanent pair is exchanged now, which both verifies it and yields
361
+ // the token every later request signs with.
362
+ const sts = await getSts(key.ak, key.sk)
363
+ return {
364
+ key: { ak: sts.ak, sk: sts.sk, securityToken: sts.securityToken, account: key.account },
365
+ source: candidate.source,
366
+ label: candidate.label,
367
+ expiresAtMs: toEpochMs(sts.expiresAt) ?? Date.now() + 3600_000,
368
+ }
369
+ }
370
+
371
+ /** Renew the cached triple before it expires. */
372
+ #scheduleRenewal() {
373
+ if (this.renewTimer) {
374
+ clearTimeout(this.renewTimer)
375
+ this.renewTimer = null
376
+ }
377
+ if (!this.cached?.expiresAtMs) return
378
+ const delay = Math.max(60_000, this.cached.expiresAtMs - Date.now() - this.renewMarginMs)
379
+ // `unref` keeps a pending renewal from holding the Host process open.
380
+ this.renewTimer = setTimeout(() => {
381
+ this.cached = null
382
+ void this.resolve().catch(() => {
383
+ // A failed renewal is retried on the next request instead of
384
+ // surfacing here, where nothing could act on it.
385
+ })
386
+ }, delay)
387
+ this.renewTimer.unref?.()
388
+ }
389
+
390
+ /** Drop the cached credential, forcing the next call to re-resolve. */
391
+ invalidate() {
392
+ this.cached = null
393
+ if (this.renewTimer) {
394
+ clearTimeout(this.renewTimer)
395
+ this.renewTimer = null
396
+ }
397
+ }
398
+
399
+ /** Stop the renewal timer; call when the plugin unloads. */
400
+ dispose() {
401
+ if (this.renewTimer) {
402
+ clearTimeout(this.renewTimer)
403
+ this.renewTimer = null
404
+ }
405
+ this.cached = null
406
+ }
407
+
408
+ /** The last resolution failure, for the settings page. */
409
+ get errorText() {
410
+ return this.lastError
411
+ }
412
+
413
+ /** The store id of the account now serving, when it came from the store. */
414
+ get accountId() {
415
+ return this.resolvedFrom?.accountId
416
+ }
417
+
418
+ /** Which source produced the current credential. */
419
+ get source() {
420
+ return this.resolvedFrom?.source
421
+ }
422
+
423
+ /** A description of the current source, for the settings page. */
424
+ get sourceLabel() {
425
+ return this.resolvedFrom?.label
426
+ }
427
+ }
428
+
429
+ /** Accept an ISO-8601 string or a number as epoch milliseconds. */
430
+ function toEpochMs(value) {
431
+ if (value === undefined || value === null || value === '') return null
432
+ if (typeof value === 'number') return value < 1e12 ? value * 1000 : value
433
+ const parsed = Date.parse(String(value))
434
+ return Number.isNaN(parsed) ? null : parsed
435
+ }
@@ -0,0 +1,79 @@
1
+ /** Feature routes kept separate from protocol/credential handling. */
2
+ import { randomUUID } from 'node:crypto'
3
+ import { InputError, persistPreferences, portablePreferences, validatePreferences, validateSelection } from './preferences.js'
4
+ import { encodeBackup, decodeBackup, backupSummary } from './backup.js'
5
+ import { readStore, addAccounts, setActiveAccount } from './accounts.js'
6
+
7
+ export async function applyPreferences(deps, patch) {
8
+ const validated = validatePreferences(patch)
9
+ await persistPreferences(validated)
10
+ Object.assign(deps.settings, validated)
11
+ if ('refreshIntervalMs' in validated) deps.rescheduleCatalog?.()
12
+ deps.catalog.configure({ enabledIds: deps.settings.enabledModelIds, overrides: deps.settings.modelOverrides })
13
+ deps.ctx.emit('llm/models-updated', 'codearts')
14
+ return { ok: true, preferences: portablePreferences(deps.settings) }
15
+ }
16
+ export function registerFeatureRoutes(route, deps, readBody) {
17
+ let mutation = Promise.resolve()
18
+ const serial = (fn) => {
19
+ const result = mutation.then(fn)
20
+ mutation = result.catch(() => {})
21
+ return result
22
+ }
23
+ route('/preferences', () => ({ ok: true, preferences: portablePreferences(deps.settings) }))
24
+ route('/preferences/save', async (req) => {
25
+ const body = await readBody(req)
26
+ return serial(() => applyPreferences(deps, body))
27
+ })
28
+ route('/usage', () => deps.usage.list())
29
+ route('/usage/clear', async () => { await deps.usage.clear(); return deps.usage.list() })
30
+ route('/presets', async (req) => {
31
+ const body = await readBody(req)
32
+ return serial(async () => {
33
+ let presets = [...deps.settings.modelPresets]
34
+ if (body.action === 'delete') {
35
+ if (typeof body.id !== 'string' || !presets.some((entry) => entry.id === body.id)) throw new InputError('预设不存在')
36
+ presets = presets.filter((entry) => entry.id !== body.id)
37
+ } else if (body.action === 'save') {
38
+ const selection = validateSelection(body)
39
+ const preset = { id: body.id || randomUUID(), name: body.name, ...selection }
40
+ const index = presets.findIndex((entry) => entry.id === preset.id)
41
+ if (index < 0) presets.push(preset)
42
+ else presets[index] = preset
43
+ } else throw new InputError('未知预设操作')
44
+ await applyPreferences(deps, { modelPresets: presets })
45
+ return { ok: true, presets: deps.settings.modelPresets }
46
+ })
47
+ })
48
+ route('/backup/export', async (req) => {
49
+ const body = await readBody(req)
50
+ const store = body.includeCredentials === true ? readStore() : null
51
+ const backup = await encodeBackup({
52
+ preferences: portablePreferences(deps.settings),
53
+ activeAccountId: store?.activeId,
54
+ accounts: body.includeCredentials === true ? store.accounts.map(({ ak, sk, label }) => ({ ak, sk, ...(label ? { label } : {}) })) : undefined,
55
+ includeCredentials: body.includeCredentials === true,
56
+ password: body.password,
57
+ })
58
+ return { ok: true, backup }
59
+ })
60
+ route('/backup/preview', async (req) => {
61
+ const body = await readBody(req)
62
+ const payload = await decodeBackup(body.text, body.password)
63
+ return { ok: true, ...backupSummary(payload, portablePreferences(deps.settings), readStore().accounts) }
64
+ })
65
+ route('/backup/restore', async (req) => {
66
+ const body = await readBody(req)
67
+ const payload = await decodeBackup(body.text, body.password)
68
+ return serial(async () => {
69
+ const preserveActive = Boolean(readStore().activeId)
70
+ const result = payload.accounts?.length ? await addAccounts(payload.accounts) : { added: 0, updated: 0 }
71
+ if (!preserveActive && payload.activeAccountId) await setActiveAccount(payload.activeAccountId)
72
+ await applyPreferences(deps, payload.preferences)
73
+ deps.invalidateAccounts?.()
74
+ deps.credentials.invalidate()
75
+ void deps.refresh()
76
+ return { ok: true, added: result.added, updated: result.updated, preferences: portablePreferences(deps.settings) }
77
+ })
78
+ })
79
+ }