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/backup.js ADDED
@@ -0,0 +1,89 @@
1
+ /** Versioned portable configuration; credential-bearing files are always authenticated encryption. */
2
+ import { randomBytes, scrypt, createCipheriv, createDecipheriv, createHash } from 'node:crypto'
3
+ import { promisify } from 'node:util'
4
+ import { InputError, validatePreferences } from './preferences.js'
5
+ const derive = promisify(scrypt)
6
+ const FORMAT = 'dsh-connect-codearts-backup'
7
+ const ENCRYPTED = 'dsh-connect-codearts-encrypted'
8
+ const MAX_BYTES = 512 * 1024
9
+ const invalid = (message = '备份格式或版本不受支持') => { throw new InputError(message) }
10
+ function passwordCheck(password) {
11
+ if (typeof password !== 'string' || password.length < 8 || password.length > 256) invalid('备份密码需为 8 到 256 个字符')
12
+ }
13
+ function validatePayload(value) {
14
+ if (!value || value.format !== FORMAT || value.version !== 1 || !value.preferences) invalid()
15
+ const preferences = validatePreferences(value.preferences)
16
+ const result = { format: FORMAT, version: 1, preferences }
17
+ if ('accounts' in value) {
18
+ if (!Array.isArray(value.accounts) || value.accounts.length > 100) invalid('备份最多包含 100 个账号')
19
+ const knownKeys = new Set()
20
+ result.accounts = value.accounts.map((account) => {
21
+ if (!account || typeof account.ak !== 'string' || typeof account.sk !== 'string' || !account.ak.trim() || !account.sk.trim() || account.ak.length > 512 || account.sk.length > 512 || (account.label !== undefined && (typeof account.label !== 'string' || account.label.length > 100))) invalid('备份包含不合法的账号')
22
+ const ak = account.ak.trim()
23
+ if (knownKeys.has(ak)) invalid('备份包含重复账号')
24
+ knownKeys.add(ak)
25
+ return { ak, sk: account.sk.trim(), ...(account.label ? { label: account.label } : {}) }
26
+ })
27
+ }
28
+ if (value.activeAccountId !== undefined) {
29
+ if (typeof value.activeAccountId !== 'string' || !result.accounts?.some((entry) => createHash('sha256').update(entry.ak).digest('hex').slice(0, 16) === value.activeAccountId)) invalid('备份的当前账号不合法')
30
+ result.activeAccountId = value.activeAccountId
31
+ }
32
+ return result
33
+ }
34
+ export async function encodeBackup({ preferences, accounts, activeAccountId, includeCredentials = false, password = '' }) {
35
+ const payload = { format: FORMAT, version: 1, createdAt: new Date().toISOString(), preferences: validatePreferences(preferences) }
36
+ if (includeCredentials) {
37
+ payload.accounts = accounts ?? []
38
+ if (activeAccountId) payload.activeAccountId = activeAccountId
39
+ }
40
+ validatePayload(payload)
41
+ const data = Buffer.from(JSON.stringify(payload))
42
+ if (data.length > MAX_BYTES) invalid('备份内容过大')
43
+ if (!includeCredentials && !password) return payload
44
+ passwordCheck(password)
45
+ const salt = randomBytes(16), iv = randomBytes(12)
46
+ const key = await derive(password, salt, 32, { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 })
47
+ try {
48
+ const cipher = createCipheriv('aes-256-gcm', key, iv)
49
+ cipher.setAAD(Buffer.from(`${ENCRYPTED}:1`))
50
+ const sealed = Buffer.concat([cipher.update(data), cipher.final()])
51
+ return { format: ENCRYPTED, version: 1, cipher: 'aes-256-gcm', kdf: 'scrypt', salt: salt.toString('base64'), iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), data: sealed.toString('base64') }
52
+ } finally { key.fill(0) }
53
+ }
54
+ export async function decodeBackup(text, password = '') {
55
+ if (typeof text !== 'string' || Buffer.byteLength(text) > MAX_BYTES * 1.5) invalid('备份文件过大或内容不正确')
56
+ let raw
57
+ try { raw = JSON.parse(text) } catch { invalid('备份不是合法 JSON') }
58
+ if (raw?.format === FORMAT) {
59
+ if ('accounts' in raw || 'activeAccountId' in raw) invalid('含凭证的备份必须为加密文件')
60
+ return validatePayload(raw)
61
+ }
62
+ if (raw?.format !== ENCRYPTED || raw.version !== 1 || raw.cipher !== 'aes-256-gcm' || raw.kdf !== 'scrypt') invalid()
63
+ passwordCheck(password)
64
+ const bytes = (field, size) => {
65
+ const encoded = raw[field]
66
+ if (typeof encoded !== 'string' || !/^[A-Za-z0-9+/]*={0,2}$/.test(encoded) || encoded.length % 4 !== 0) invalid()
67
+ const value = Buffer.from(encoded, 'base64')
68
+ if ((size && value.length !== size) || (!size && value.length > MAX_BYTES)) invalid()
69
+ return value
70
+ }
71
+ const salt = bytes('salt', 16), iv = bytes('iv', 12), tag = bytes('tag', 16), data = bytes('data')
72
+ const key = await derive(password, salt, 32, { N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 })
73
+ let payload
74
+ try {
75
+ const decipher = createDecipheriv('aes-256-gcm', key, iv)
76
+ decipher.setAAD(Buffer.from(`${ENCRYPTED}:1`))
77
+ decipher.setAuthTag(tag)
78
+ payload = JSON.parse(Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8'))
79
+ } catch { invalid('密码错误,或备份文件已损坏') } finally { key.fill(0) }
80
+ return validatePayload(payload)
81
+ }
82
+ export function backupSummary(payload, currentSettings, knownAccounts = []) {
83
+ const known = new Set(knownAccounts.map((entry) => entry.ak))
84
+ return {
85
+ preferences: payload.preferences,
86
+ changes: Object.keys(payload.preferences).filter((key) => JSON.stringify(currentSettings[key]) !== JSON.stringify(payload.preferences[key])),
87
+ accounts: { total: payload.accounts?.length ?? 0, added: payload.accounts?.filter((entry) => !known.has(entry.ak)).length ?? 0, updated: payload.accounts?.filter((entry) => known.has(entry.ak)).length ?? 0 },
88
+ }
89
+ }
package/src/catalog.js ADDED
@@ -0,0 +1,269 @@
1
+ /**
2
+ * The live model catalog.
3
+ *
4
+ * The adapter, the settings page, and the diagnostics view all read the same
5
+ * catalog, so it is one object with one refresh path. A refresh that fails
6
+ * keeps the previous live catalog in service rather than replacing it with
7
+ * the static fallback table, which would silently downgrade a working
8
+ * session to models with no thinking metadata.
9
+ */
10
+
11
+ import { readFileSync, writeFileSync, mkdirSync } from 'node:fs'
12
+ import { dirname } from 'node:path'
13
+ import { discoverModels, FALLBACK_MODELS } from './models.js'
14
+
15
+ export class Catalog {
16
+ /**
17
+ * @param {object} [options] catalog options.
18
+ * @param {(line: string) => void} [options.log] diagnostic sink.
19
+ */
20
+ constructor(options = {}) {
21
+ this.log = options.log ?? (() => {})
22
+ /** @type {import('./models.js').ModelInfo[]} */
23
+ this.current = FALLBACK_MODELS
24
+ /** Where the current catalog came from. */
25
+ this.source = 'fallback'
26
+ /** The last discovery failure, kept for the diagnostics view. */
27
+ this.lastError = undefined
28
+ /** Epoch ms of the last successful refresh. */
29
+ this.refreshedAt = undefined
30
+ this.pending = null
31
+ /** Saved selection; null means "offer everything". */
32
+ this.enabledIds = null
33
+ /** Per-model capability overrides. */
34
+ this.overrides = {}
35
+ /** @type {Set<() => void>} */
36
+ this.listeners = new Set()
37
+ }
38
+
39
+ /**
40
+ * Load the last catalog persisted on disk, if any.
41
+ *
42
+ * A restart otherwise begins on the static fallback table and shows a stale
43
+ * model list (or none) until the first refresh lands. Persisting the last good
44
+ * catalog means the picker is correct the moment the plugin loads, and the
45
+ * refresh only confirms it.
46
+ *
47
+ * @param {string} path file to read.
48
+ * @returns {boolean} whether a usable catalog was loaded.
49
+ */
50
+ loadPersisted(path) {
51
+ try {
52
+ const saved = JSON.parse(readFileSync(path, 'utf8'))
53
+ const models = Array.isArray(saved?.models) ? saved.models : []
54
+ // Only accept a shape the rest of the plugin can actually use: a partial
55
+ // file must not replace a working catalog with something unreadable.
56
+ if (models.length === 0) return false
57
+ if (!models.every((model) => typeof model?.id === 'string' && model.id !== '')) return false
58
+ this.current = models
59
+ this.source = 'cache'
60
+ this.refreshedAt = typeof saved.refreshedAt === 'number' ? saved.refreshedAt : undefined
61
+ this.#notify()
62
+ return true
63
+ } catch {
64
+ return false
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Persist the current catalog.
70
+ *
71
+ * Best-effort: a read-only profile must not break a working session, so a
72
+ * failure here is logged and dropped rather than thrown.
73
+ *
74
+ * @param {string} path file to write.
75
+ */
76
+ persist(path) {
77
+ if (this.source === 'fallback') return
78
+ try {
79
+ mkdirSync(dirname(path), { recursive: true })
80
+ writeFileSync(
81
+ path,
82
+ `${JSON.stringify({ version: 1, source: this.source, refreshedAt: this.refreshedAt, models: this.current }, null, 2)}\n`,
83
+ { encoding: 'utf8', mode: 0o600 },
84
+ )
85
+ } catch (error) {
86
+ this.log(`模型清单落盘失败(不影响使用):${error?.message ?? error}`)
87
+ }
88
+ }
89
+
90
+ /** The catalog the rest of the plugin reads. */
91
+ models() {
92
+ return this.current
93
+ }
94
+
95
+ /**
96
+ * Apply the user's selection and capability overrides.
97
+ *
98
+ * `enabledIds` null means "everything" — a user who never opened the card must
99
+ * see the whole catalog, not an empty picker. A non-null list is authoritative:
100
+ * it keeps models the upstream withdrew (the user is still running them) and
101
+ * withholds ones the upstream added (so a new upstream model appears only once
102
+ * the user ticks it).
103
+ *
104
+ * @param {object} selection the saved selection.
105
+ * @param {string[]|null} [selection.enabledIds] ids to offer, or null for all.
106
+ * @param {Record<string, {images?: boolean, allowOff?: boolean, defaultStrength?: string}>} [selection.overrides] per-model overrides.
107
+ */
108
+ configure(selection) {
109
+ this.enabledIds = selection?.enabledIds ?? null
110
+ this.overrides = selection?.overrides ?? {}
111
+ this.#notify()
112
+ }
113
+
114
+ /** The models the rest of the plugin may offer, after the selection. */
115
+ visible() {
116
+ const models = this.current
117
+ if (this.enabledIds === null) return models
118
+ const wanted = new Set(this.enabledIds)
119
+ return models.filter((model) => wanted.has(model.id))
120
+ }
121
+
122
+ /** Whether a model is enabled under the current selection. */
123
+ isEnabled(id) {
124
+ return this.enabledIds === null || this.enabledIds.includes(id)
125
+ }
126
+
127
+ /** One model after capability overrides: images and whether "off" is offered. */
128
+ effective(model) {
129
+ if (!model) return model
130
+ const override = this.overrides?.[model.id]
131
+ if (!override) return model
132
+ return {
133
+ ...model,
134
+ supportsImages: typeof override.images === 'boolean' ? override.images : model.supportsImages,
135
+ allowOff: typeof override.allowOff === 'boolean' ? override.allowOff : model.allowOff,
136
+ // Only honour a level the model actually offers: a stale or hand-edited
137
+ // preference must not become a request the upstream will reject.
138
+ defaultStrength:
139
+ typeof override.defaultStrength === 'string' &&
140
+ (model.strengths ?? []).includes(override.defaultStrength)
141
+ ? override.defaultStrength
142
+ : model.defaultStrength,
143
+ }
144
+ }
145
+
146
+ /** Look up one model by id. */
147
+ find(id) {
148
+ return this.current.find((model) => model.id === id)
149
+ }
150
+
151
+ /**
152
+ * Resolve whatever a caller named into the gateway's model id.
153
+ *
154
+ * The selector displays `name · ratio` (for example `GLM-5.2 · 0.7x`), and a
155
+ * surface can hand that display string back as the model. The gateway does
156
+ * NOT recognise it: it answers HTTP 200 with an empty body and no error,
157
+ * which the Host can only report as "returned a completed response with no
158
+ * content". Verified against the live gateway.
159
+ *
160
+ * Falls back through id → display string → name → id/name with the ` · ratio`
161
+ * tail stripped, and finally returns the input unchanged so a genuinely
162
+ * unknown id still reaches the gateway rather than being silently dropped.
163
+ *
164
+ * @param {string} value the model as named by a caller.
165
+ * @returns {string} the id to put on the wire.
166
+ */
167
+ resolveId(value) {
168
+ const raw = String(value ?? '').trim()
169
+ if (raw === '') return raw
170
+ const low = raw.toLowerCase()
171
+ const display = (model) => (model.ratio ? `${model.name} · ${model.ratio}` : model.name)
172
+
173
+ const byId = this.current.find((model) => model.id.toLowerCase() === low)
174
+ if (byId) return byId.id
175
+
176
+ const byDisplay = this.current.find(
177
+ (model) => display(model) === raw || display(model).toLowerCase() === low,
178
+ )
179
+ if (byDisplay) return byDisplay.id
180
+
181
+ const byName = this.current.find((model) => model.name.toLowerCase() === low)
182
+ if (byName) return byName.id
183
+
184
+ const stripped = raw.split('·')[0].trim().toLowerCase()
185
+ if (stripped !== '' && stripped !== low) {
186
+ const byStrippedId = this.current.find((model) => model.id.toLowerCase() === stripped)
187
+ if (byStrippedId) return byStrippedId.id
188
+ const byStrippedName = this.current.find((model) => model.name.toLowerCase() === stripped)
189
+ if (byStrippedName) return byStrippedName.id
190
+ }
191
+
192
+ // Unknown: pass it through so the gateway's own answer reaches the user.
193
+ return raw
194
+ }
195
+
196
+ /**
197
+ * Re-read the catalog from the gateway.
198
+ *
199
+ * Concurrent callers share one refresh: the settings page and the adapter
200
+ * can ask at the same time without doubling the requests.
201
+ *
202
+ * @param {import('./gateway.js').MadaoClient} client an authenticated client.
203
+ * @returns {Promise<{changed: boolean, source: string, error?: string}>} the outcome.
204
+ */
205
+ async refresh(client) {
206
+ if (this.pending) return this.pending
207
+ this.pending = this.#refresh(client).finally(() => {
208
+ this.pending = null
209
+ })
210
+ return this.pending
211
+ }
212
+
213
+ async #refresh(client) {
214
+ const before = this.current
215
+ const result = await discoverModels(client)
216
+
217
+ if (result.error) {
218
+ this.lastError = result.error
219
+ this.log(`模型清单刷新失败:${result.error}`)
220
+ } else {
221
+ this.lastError = undefined
222
+ }
223
+
224
+ // A fallback result never replaces a live catalog: the static table is a
225
+ // first-start courtesy, not a downgrade path.
226
+ if (result.source === 'gateway') {
227
+ this.current = result.models
228
+ this.source = 'gateway'
229
+ this.refreshedAt = Date.now()
230
+ } else if (this.source !== 'gateway') {
231
+ this.current = result.models
232
+ this.source = 'fallback'
233
+ }
234
+
235
+ const changed = !sameCatalog(before, this.current)
236
+ if (changed) this.#notify()
237
+ return { changed, source: this.source, error: this.lastError }
238
+ }
239
+
240
+ /** Subscribe to catalog changes; returns the disposer. */
241
+ onChange(listener) {
242
+ this.listeners.add(listener)
243
+ return () => this.listeners.delete(listener)
244
+ }
245
+
246
+ #notify() {
247
+ for (const listener of this.listeners) {
248
+ try {
249
+ listener()
250
+ } catch (error) {
251
+ this.log(`目录变更监听器抛错:${error?.message ?? error}`)
252
+ }
253
+ }
254
+ }
255
+ }
256
+
257
+ /** Cheap structural comparison: ids, names, and the capabilities that matter. */
258
+ function sameCatalog(a, b) {
259
+ if (a.length !== b.length) return false
260
+ for (let i = 0; i < a.length; i++) {
261
+ const left = a[i]
262
+ const right = b[i]
263
+ if (left.id !== right.id || left.name !== right.name) return false
264
+ if (left.ratio !== right.ratio || left.context !== right.context) return false
265
+ if (left.supportsImages !== right.supportsImages) return false
266
+ if (left.strengths.length !== right.strengths.length) return false
267
+ }
268
+ return true
269
+ }
package/src/checkin.js ADDED
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Daily check-in.
3
+ *
4
+ * The gateway runs its daily bonus as a campaign in the same welfare list the
5
+ * settings page already reads: `campaignId: 34`, titled 「每日签到领100积分」,
6
+ * `triggerMode: MANUAL_CLAIM`. Claiming is a real, irreversible write
7
+ * (`POST /v1/ops/claim`) that spends the day's one entitlement, so everything
8
+ * here is built around never doing it twice and never doing it unasked.
9
+ *
10
+ * Auto check-in is therefore opt-in, off by default, and guarded three ways:
11
+ *
12
+ * 1. it re-reads campaign state immediately before claiming, so an account
13
+ * already claimed today by any client is skipped, not retried;
14
+ * 2. it records the local date of the last attempt per account, so a refresh
15
+ * loop cannot re-claim within one day even if the upstream answer is
16
+ * ambiguous;
17
+ * 3. it never claims when the campaign does not report itself claimable.
18
+ *
19
+ * The record lives beside the account store so a restart does not forget it.
20
+ */
21
+
22
+ import { existsSync, readFileSync } from 'node:fs'
23
+ import { mkdir, rename, writeFile } from 'node:fs/promises'
24
+ import { join } from 'node:path'
25
+ import { CONFIG_DIR } from './paths.js'
26
+ import { claimBenefit, listBenefits } from './account.js'
27
+
28
+ /** File holding the per-account check-in record. */
29
+ export const CHECKIN_STATE_PATH = join(CONFIG_DIR, 'checkin-state.json')
30
+
31
+ /** The daily-bonus campaign, by name rather than only id: the id is stable but the title is what makes a mismatch obvious. */
32
+ export const DAILY_CAMPAIGN_HINT = '签到'
33
+
34
+ /**
35
+ * @typedef {object} CheckinState
36
+ * @property {Record<string, {day: string, at: number, claimed: boolean, amount?: number, error?: string}>} accounts
37
+ */
38
+
39
+ /** The local calendar day key, `YYYY-MM-DD`, in the user's own zone. */
40
+ export function todayKey(now = new Date()) {
41
+ const p = (n) => String(n).padStart(2, '0')
42
+ return `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}`
43
+ }
44
+
45
+ /** Read the record; a missing or corrupt file is an empty record. */
46
+ export function readCheckinState() {
47
+ if (!existsSync(CHECKIN_STATE_PATH)) return { accounts: {} }
48
+ try {
49
+ const parsed = JSON.parse(readFileSync(CHECKIN_STATE_PATH, 'utf8'))
50
+ if (parsed && typeof parsed === 'object' && typeof parsed.accounts === 'object') {
51
+ return { accounts: parsed.accounts }
52
+ }
53
+ } catch {
54
+ // Fall through: an unreadable record means "no attempts recorded", and the
55
+ // re-read before claiming still prevents a double claim.
56
+ }
57
+ return { accounts: {} }
58
+ }
59
+
60
+ /** Write the record atomically. */
61
+ async function writeCheckinState(state) {
62
+ await mkdir(CONFIG_DIR, { recursive: true })
63
+ const temp = `${CHECKIN_STATE_PATH}.tmp`
64
+ await writeFile(temp, `${JSON.stringify(state, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
65
+ await rename(temp, CHECKIN_STATE_PATH)
66
+ }
67
+
68
+ /** Whether this account already attempted a claim today. */
69
+ export function attemptedToday(state, accountId, now = new Date()) {
70
+ const entry = state.accounts[accountId]
71
+ return entry !== undefined && entry.day === todayKey(now)
72
+ }
73
+
74
+ /**
75
+ * The daily campaign in a benefit list.
76
+ *
77
+ * Chosen by its `USER_LOGIN` type plus the 签到 hint, because several login
78
+ * campaigns can be active at once (there is a second one running right now).
79
+ * @param {Array<object>} items benefits from the gateway.
80
+ * @returns {object|undefined} the daily campaign.
81
+ */
82
+ export function dailyCampaignOf(items) {
83
+ const list = Array.isArray(items) ? items : []
84
+ // Prefer the exact, long-standing campaign; fall back to a title match.
85
+ return (
86
+ list.find((item) => item.campaignId === 34) ??
87
+ list.find((item) => typeof item.title === 'string' && item.title.includes(DAILY_CAMPAIGN_HINT))
88
+ )
89
+ }
90
+
91
+ /**
92
+ * Read one account's daily check-in state without claiming anything.
93
+ *
94
+ * @param {import('./gateway.js').MadaoClient} client an authenticated client.
95
+ * @param {object} [options] read options.
96
+ * @param {Date} [options.now] clock, for tests.
97
+ * @param {CheckinState} [options.state] the record to consult.
98
+ * @param {string} [options.accountId] whose record to consult.
99
+ * @returns {Promise<{available: boolean, claimable: boolean, status: string|null, amount: number, title: string|null, claimedToday: boolean, reason?: string}>} the state.
100
+ */
101
+ export async function readCheckin(client, options = {}) {
102
+ const now = options.now ?? new Date()
103
+ const state = options.state ?? readCheckinState()
104
+ const attempt = options.accountId ? state.accounts[options.accountId] : undefined
105
+
106
+ let items
107
+ try {
108
+ items = await listBenefits(client)
109
+ } catch (error) {
110
+ return {
111
+ available: false,
112
+ claimable: false,
113
+ status: null,
114
+ amount: 0,
115
+ title: null,
116
+ claimedToday: false,
117
+ reason: `读取福利列表失败:${error?.message ?? error}`,
118
+ }
119
+ }
120
+
121
+ const campaign = dailyCampaignOf(items)
122
+ if (!campaign) {
123
+ return {
124
+ available: false,
125
+ claimable: false,
126
+ status: null,
127
+ amount: 0,
128
+ title: null,
129
+ claimedToday: false,
130
+ reason: '上游的福利列表里没有每日签到活动',
131
+ }
132
+ }
133
+
134
+ // The upstream status is authoritative about today; the local record only
135
+ // covers the window between a successful claim and the upstream catching up.
136
+ const locallyClaimed =
137
+ attempt !== undefined && attempt.day === todayKey(now) && attempt.claimed === true
138
+ const claimable = campaign.claimable === true && !locallyClaimed
139
+
140
+ return {
141
+ available: true,
142
+ claimable,
143
+ status: campaign.status ?? null,
144
+ amount: campaign.pendingAmount || campaign.amount || 0,
145
+ title: campaign.title ?? null,
146
+ claimedToday: locallyClaimed || campaign.claimable !== true,
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Claim the daily bonus for one account, once.
152
+ *
153
+ * @param {import('./gateway.js').MadaoClient} client an authenticated client.
154
+ * @param {object} options claim options.
155
+ * @param {string} options.accountId whose record to update.
156
+ * @param {Date} [options.now] clock, for tests.
157
+ * @param {boolean} [options.force] claim even when the local record says it was attempted today (never used by auto mode).
158
+ * @returns {Promise<{claimed: boolean, amount?: number, reason?: string}>} the outcome.
159
+ */
160
+ export async function claimDaily(client, options) {
161
+ const now = options.now ?? new Date()
162
+ const state = readCheckinState()
163
+
164
+ if (!options.force && attemptedToday(state, options.accountId, now)) {
165
+ const entry = state.accounts[options.accountId]
166
+ return {
167
+ claimed: false,
168
+ reason: entry?.claimed
169
+ ? '今天已经签过了(本地记录)'
170
+ : `今天已经尝试过(${entry?.error ?? '上次未成功'}),不重复领取`,
171
+ }
172
+ }
173
+
174
+ const before = await readCheckin(client, { now, state, accountId: options.accountId })
175
+ if (!before.available) return { claimed: false, reason: before.reason }
176
+ if (!before.claimable) {
177
+ await recordAttempt(state, options.accountId, now, false, undefined, '上游显示今天不可领取')
178
+ return { claimed: false, reason: '上游显示今天已经领过或当前不可领取' }
179
+ }
180
+
181
+ const items = await listBenefits(client)
182
+ const campaign = dailyCampaignOf(items)
183
+ if (!campaign) return { claimed: false, reason: '上游的福利列表里没有每日签到活动' }
184
+
185
+ const result = await claimBenefit(client, campaign.campaignId)
186
+ if (!result.ok) {
187
+ await recordAttempt(state, options.accountId, now, false, undefined, result.reason)
188
+ return { claimed: false, reason: result.reason }
189
+ }
190
+
191
+ await recordAttempt(state, options.accountId, now, true, before.amount)
192
+ return { claimed: true, amount: before.amount }
193
+ }
194
+
195
+ /** Record one attempt for one account, replacing that account's entry. */
196
+ async function recordAttempt(state, accountId, now, claimed, amount, error) {
197
+ state.accounts[accountId] = {
198
+ day: todayKey(now),
199
+ at: now.getTime(),
200
+ claimed,
201
+ ...(amount === undefined ? {} : { amount }),
202
+ ...(error === undefined ? {} : { error }),
203
+ }
204
+ await writeCheckinState(state)
205
+ }
206
+
207
+ /**
208
+ * Run auto check-in across the accounts that should be checked.
209
+ *
210
+ * Sequential on purpose: the gateway counts concurrent sessions with a small
211
+ * ceiling, and a burst of parallel claims on one account is the fastest way to
212
+ * hit it. One account failing never stops the rest.
213
+ *
214
+ * @param {object} options run options.
215
+ * @param {Array<{id: string, client: import('./gateway.js').MadaoClient}>} options.targets accounts to check, in order.
216
+ * @param {Date} [options.now] clock, for tests.
217
+ * @returns {Promise<{attempted: number, claimed: number, skipped: number, failures: Array<{id: string, reason: string}>}>} the summary.
218
+ */
219
+ export async function runAutoCheckin({ targets, now = new Date() }) {
220
+ const summary = { attempted: 0, claimed: 0, skipped: 0, failures: [] }
221
+ const state = readCheckinState()
222
+
223
+ for (const target of targets ?? []) {
224
+ if (attemptedToday(state, target.id, now)) {
225
+ summary.skipped += 1
226
+ continue
227
+ }
228
+ summary.attempted += 1
229
+ try {
230
+ const result = await claimDaily(target.client, {
231
+ accountId: target.id,
232
+ now,
233
+ force: false,
234
+ })
235
+ if (result.claimed) summary.claimed += 1
236
+ else if (result.reason) summary.failures.push({ id: target.id, reason: result.reason })
237
+ state.accounts[target.id] = readCheckinState().accounts[target.id] ?? state.accounts[target.id]
238
+ } catch (error) {
239
+ summary.failures.push({ id: target.id, reason: error?.message ?? String(error) })
240
+ }
241
+ }
242
+
243
+ return summary
244
+ }
245
+
246
+ /**
247
+ * What auto check-in has done today, for the settings page.
248
+ * @param {Array<{id: string, label: string}>} accounts the pool, in display order.
249
+ * @param {Date} [now] clock, for tests.
250
+ * @returns {{total: number, done: number, pending: number, lastError?: string}} today's progress.
251
+ */
252
+ export function todaySummary(accounts, now = new Date()) {
253
+ const state = readCheckinState()
254
+ const today = todayKey(now)
255
+ let done = 0
256
+ let lastError
257
+ for (const account of accounts ?? []) {
258
+ const entry = state.accounts[account.id]
259
+ if (entry !== undefined && entry.day === today) {
260
+ if (entry.claimed) done += 1
261
+ else if (entry.error !== undefined) lastError ??= `${account.label}:${entry.error}`
262
+ }
263
+ }
264
+ const total = (accounts ?? []).length
265
+ return {
266
+ total,
267
+ done,
268
+ pending: Math.max(0, total - done),
269
+ ...(lastError === undefined ? {} : { lastError }),
270
+ }
271
+ }