@sixzjd/dsh-workbuddy-connect 0.3.1 → 0.3.3
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.
- package/README.en.md +1 -1
- package/README.md +2 -0
- package/client.js +274 -22
- package/lib/accounts.js +361 -0
- package/lib/adapter.js +1 -38
- package/lib/atrest.js +48 -2
- package/lib/auth.js +48 -7
- package/lib/cachestats.js +85 -0
- package/lib/index.js +172 -3
- package/lib/shim.js +43 -4
- package/lib/thinking.js +39 -0
- package/lib/upstream.js +46 -7
- package/package.json +1 -1
package/lib/accounts.js
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* More than one account per realm.
|
|
3
|
+
*
|
|
4
|
+
* The plugin used to hold exactly one credential per variant, in one file at the
|
|
5
|
+
* data dir root. That is the common case and stays the common case — but the
|
|
6
|
+
* upstream lets one person have several accounts, and swapping between them meant
|
|
7
|
+
* signing out and back in through a device-authorization flow each time.
|
|
8
|
+
*
|
|
9
|
+
* Layout: one directory per realm, one file per account, one pointer naming the
|
|
10
|
+
* active one.
|
|
11
|
+
*
|
|
12
|
+
* <dataDir>/accounts/cn/<uidHash>.json
|
|
13
|
+
* <dataDir>/accounts/cn/active.json -> { "uidHash": "…" }
|
|
14
|
+
* <dataDir>/accounts/global/…
|
|
15
|
+
*
|
|
16
|
+
* The file name is a hash of the uid rather than the uid itself: a directory
|
|
17
|
+
* listing is cheap to leak (a screenshot, a bug report paste) and a uid is a
|
|
18
|
+
* stable account identifier. The hash is not a secret — it is derived from the
|
|
19
|
+
* uid, which is why the uid is still stored *inside* the file where it is
|
|
20
|
+
* needed.
|
|
21
|
+
*
|
|
22
|
+
* The realm split is a safety property, not tidiness: the two products' tokens
|
|
23
|
+
* are not interchangeable, and a CN token offered to the international gateway
|
|
24
|
+
* fails at request time, far from the point where the wrong account was picked.
|
|
25
|
+
*
|
|
26
|
+
* @module dsh-workbuddy-connect/accounts
|
|
27
|
+
*/
|
|
28
|
+
import { createHash } from 'node:crypto'
|
|
29
|
+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from 'node:fs'
|
|
30
|
+
import { join } from 'node:path'
|
|
31
|
+
import { parseWorkBuddyAuth, readJsonFile, writeJsonAtomic } from './auth.js'
|
|
32
|
+
import { realmOf } from './upstream.js'
|
|
33
|
+
|
|
34
|
+
/** Directory name under the plugin data dir. */
|
|
35
|
+
const ACCOUNTS_DIR_NAME = 'accounts'
|
|
36
|
+
|
|
37
|
+
/** The pointer file naming the active account, per realm. */
|
|
38
|
+
const POINTER_FILENAME = 'active.json'
|
|
39
|
+
|
|
40
|
+
/** Characters a uid hash may use, so a hostile uid cannot escape the directory. */
|
|
41
|
+
const UID_HASH_PATTERN = /^[0-9a-f]{16}$/
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Hash a uid into a file name.
|
|
45
|
+
*
|
|
46
|
+
* Truncated to 16 hex characters (64 bits): this is a file name, not a security
|
|
47
|
+
* boundary, and a collision would need two real accounts sharing a truncated
|
|
48
|
+
* digest to matter. The full uid is preserved inside the file.
|
|
49
|
+
*/
|
|
50
|
+
export function uidHashOf(uid) {
|
|
51
|
+
return createHash('sha256').update(`workbuddy-account:${uid}`).digest('hex').slice(0, 16)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Refuse a uid that yields no usable hash, rather than writing to `undefined`. */
|
|
55
|
+
function requireHash(uid) {
|
|
56
|
+
if (typeof uid !== 'string' || uid === '') throw new Error('workbuddy: account has no uid; cannot store it')
|
|
57
|
+
const hash = uidHashOf(uid)
|
|
58
|
+
if (!UID_HASH_PATTERN.test(hash)) throw new Error('workbuddy: account uid did not produce a usable file name')
|
|
59
|
+
return hash
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* One realm's account list.
|
|
64
|
+
*
|
|
65
|
+
* Stateless apart from its directory: every method reads the disk. That is what
|
|
66
|
+
* lets a switch take effect for the very next request without restarting, and it
|
|
67
|
+
* means a stale in-memory copy can never disagree with what is stored.
|
|
68
|
+
*/
|
|
69
|
+
export class WorkBuddyAccountStore {
|
|
70
|
+
/**
|
|
71
|
+
* @param {object} options
|
|
72
|
+
* @param {'cn'|'global'} options.realm Which product's accounts these are.
|
|
73
|
+
* @param {string} options.dataDir The plugin data directory.
|
|
74
|
+
*/
|
|
75
|
+
constructor(options) {
|
|
76
|
+
this.realm = options.realm
|
|
77
|
+
this.dir = join(options.dataDir, ACCOUNTS_DIR_NAME, options.realm)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
pointerPath() {
|
|
81
|
+
return join(this.dir, POINTER_FILENAME)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Every stored credential file, ignoring the pointer. */
|
|
85
|
+
#credentialFiles() {
|
|
86
|
+
let entries
|
|
87
|
+
try {
|
|
88
|
+
entries = readdirSync(this.dir)
|
|
89
|
+
} catch {
|
|
90
|
+
return []
|
|
91
|
+
}
|
|
92
|
+
return entries
|
|
93
|
+
.filter(name => name.endsWith('.json') && name !== POINTER_FILENAME)
|
|
94
|
+
.map(name => join(this.dir, name))
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
#readCredential(path) {
|
|
98
|
+
try {
|
|
99
|
+
return parseWorkBuddyAuth(readFileSync(path, 'utf8'))
|
|
100
|
+
} catch {
|
|
101
|
+
return undefined
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The active account's uid hash, or undefined when nothing is active. */
|
|
106
|
+
async activeHash() {
|
|
107
|
+
const pointer = readJsonFile(this.pointerPath())
|
|
108
|
+
const hash = pointer?.['uidHash']
|
|
109
|
+
if (typeof hash !== 'string' || !UID_HASH_PATTERN.test(hash)) return undefined
|
|
110
|
+
// A pointer to a file that no longer exists is the same as no pointer: the
|
|
111
|
+
// honest answer is "nothing is active", not a broken credential.
|
|
112
|
+
return existsSync(join(this.dir, `${hash}.json`)) ? hash : undefined
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* The active credential, or undefined.
|
|
117
|
+
*
|
|
118
|
+
* Verified against this realm on the way out. A credential that names another
|
|
119
|
+
* realm is not returned: it would be sent to the wrong gateway.
|
|
120
|
+
*/
|
|
121
|
+
async active() {
|
|
122
|
+
const hash = await this.activeHash()
|
|
123
|
+
if (hash === undefined) return undefined
|
|
124
|
+
const credential = this.#readCredential(join(this.dir, `${hash}.json`))
|
|
125
|
+
if (credential === undefined) return undefined
|
|
126
|
+
if (realmOf(credential) !== this.realm) return undefined
|
|
127
|
+
return credential
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Import the single credential file this plugin used to keep, once.
|
|
132
|
+
*
|
|
133
|
+
* Every existing install has exactly one credential at the data dir root, and
|
|
134
|
+
* an upgrade must not look like a sign-out. The import is additive: the legacy
|
|
135
|
+
* file is left in place, because it is also what an older version of the plugin
|
|
136
|
+
* would read after a downgrade, and deleting the user's only credential to
|
|
137
|
+
* tidy up is not worth that risk.
|
|
138
|
+
*
|
|
139
|
+
* Idempotent: importing the same file twice updates one account.
|
|
140
|
+
*
|
|
141
|
+
* @param {string} legacyPath The single-file credential path.
|
|
142
|
+
* @returns {Promise<boolean>} Whether anything was imported.
|
|
143
|
+
*/
|
|
144
|
+
async importLegacyFile(legacyPath) {
|
|
145
|
+
let text
|
|
146
|
+
try {
|
|
147
|
+
text = readFileSync(legacyPath, 'utf8')
|
|
148
|
+
} catch {
|
|
149
|
+
return false
|
|
150
|
+
}
|
|
151
|
+
const credential = parseWorkBuddyAuth(text)
|
|
152
|
+
if (credential === undefined) return false
|
|
153
|
+
if (realmOf(credential) !== this.realm) return false
|
|
154
|
+
if (typeof credential.uid !== 'string' || credential.uid === '') return false
|
|
155
|
+
const hash = uidHashOf(credential.uid)
|
|
156
|
+
const target = join(this.dir, `${hash}.json`)
|
|
157
|
+
// Never overwrite a newer stored copy with the legacy one: after the first
|
|
158
|
+
// import the account file is the one that gets refreshed, so the legacy file
|
|
159
|
+
// is progressively staler.
|
|
160
|
+
if (!existsSync(target)) {
|
|
161
|
+
writeJsonAtomic(target, credentialDocument(credential))
|
|
162
|
+
}
|
|
163
|
+
// Only claim the active slot if nothing holds it yet, so an upgrade does not
|
|
164
|
+
// silently switch away from an account the user chose afterwards.
|
|
165
|
+
if (await this.activeHash() === undefined) {
|
|
166
|
+
writeJsonAtomic(this.pointerPath(), { version: 1, uidHash: hash })
|
|
167
|
+
}
|
|
168
|
+
return true
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* Store a credential and make it the active one.
|
|
173
|
+
*
|
|
174
|
+
* Saving is "use this account now": the caller has just signed in or imported
|
|
175
|
+
* it, and a save that left some other account active would look like the
|
|
176
|
+
* sign-in had not worked.
|
|
177
|
+
*/
|
|
178
|
+
async save(input) {
|
|
179
|
+
// Accepts either a parsed credential or the document shape that lives on
|
|
180
|
+
// disk. Both arrive in practice: a sign-in produces the former, and importing
|
|
181
|
+
// an existing file (or migrating the single-file layout) produces the latter.
|
|
182
|
+
const credential = normalizeCredential(input)
|
|
183
|
+
if (credential === undefined) throw new Error('workbuddy: refusing to store an unreadable credential')
|
|
184
|
+
const realm = realmOf(credential)
|
|
185
|
+
if (realm !== this.realm) {
|
|
186
|
+
throw new Error(
|
|
187
|
+
`refusing to store a ${realm === 'cn' ? 'WorkBuddy (CN)' : 'WorkBuddy AI'} credential`
|
|
188
|
+
+ ` in the ${this.realm === 'cn' ? 'WorkBuddy (CN)' : 'WorkBuddy AI'} account list`,
|
|
189
|
+
)
|
|
190
|
+
}
|
|
191
|
+
const hash = requireHash(credential.uid)
|
|
192
|
+
writeJsonAtomic(join(this.dir, `${hash}.json`), credentialDocument(credential))
|
|
193
|
+
writeJsonAtomic(this.pointerPath(), { version: 1, uidHash: hash })
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Make an existing account active.
|
|
198
|
+
*
|
|
199
|
+
* Throws when the uid is not stored. Falling back to "no account" would sign
|
|
200
|
+
* the user out, and falling back to a different account would send their
|
|
201
|
+
* requests to somebody else's — both worse than an error the card can show.
|
|
202
|
+
*/
|
|
203
|
+
async activate(handle) {
|
|
204
|
+
const hash = await this.#resolveHandle(handle)
|
|
205
|
+
writeJsonAtomic(this.pointerPath(), { version: 1, uidHash: hash })
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Turn a handle into a stored account's hash.
|
|
210
|
+
*
|
|
211
|
+
* A handle is the uid hash the list handed out, or a full uid when the caller
|
|
212
|
+
* already has one (a sign-in does). Callers that only ever saw the list must
|
|
213
|
+
* use the hash: the list deliberately does not carry the full uid.
|
|
214
|
+
*/
|
|
215
|
+
async #resolveHandle(handle) {
|
|
216
|
+
if (typeof handle !== 'string' || handle === '') {
|
|
217
|
+
throw new Error('workbuddy: an account handle is required')
|
|
218
|
+
}
|
|
219
|
+
const direct = UID_HASH_PATTERN.test(handle) ? handle : undefined
|
|
220
|
+
if (direct !== undefined && existsSync(join(this.dir, `${direct}.json`))) return direct
|
|
221
|
+
const hash = requireHash(handle)
|
|
222
|
+
if (!existsSync(join(this.dir, `${hash}.json`))) {
|
|
223
|
+
throw new Error(`workbuddy: unknown account ${JSON.stringify(handle.slice(0, 8))}; add it first`)
|
|
224
|
+
}
|
|
225
|
+
return hash
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Forget one account.
|
|
230
|
+
*
|
|
231
|
+
* When the removed account was the active one, another is promoted rather
|
|
232
|
+
* than leaving the variant signed out while a usable credential is still on
|
|
233
|
+
* disk. When it was the last one, nothing is promoted and the variant is
|
|
234
|
+
* genuinely signed out.
|
|
235
|
+
*/
|
|
236
|
+
async remove(handle) {
|
|
237
|
+
const hash = await this.#resolveHandle(handle)
|
|
238
|
+
// Read the pointer BEFORE deleting the file. `activeHash()` treats a pointer
|
|
239
|
+
// to a missing file as "nothing active", so asking afterwards would always
|
|
240
|
+
// look like this account was not the active one and the promotion below
|
|
241
|
+
// would never run.
|
|
242
|
+
const wasActive = await this.activeHash() === hash
|
|
243
|
+
const target = join(this.dir, `${hash}.json`)
|
|
244
|
+
if (existsSync(target)) rmSync(target, { force: true })
|
|
245
|
+
if (!wasActive) return
|
|
246
|
+
rmSync(this.pointerPath(), { force: true })
|
|
247
|
+
const remaining = (await this.list()).filter(account => account.hash !== hash)
|
|
248
|
+
// `remaining` is already ordered oldest-first by uid, which is stable and
|
|
249
|
+
// predictable; the point is only that *something* usable becomes active.
|
|
250
|
+
if (remaining.length > 0) await this.activate(remaining[0].hash)
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Forget every account in this realm.
|
|
255
|
+
*
|
|
256
|
+
* Clearing is deliberately a whole-realm operation: the two products' tokens
|
|
257
|
+
* are not interchangeable, so "clear all" in the CN row must not touch the
|
|
258
|
+
* international accounts. The credential store's single-file copy is left to
|
|
259
|
+
* its own logout path — this method owns only the account list.
|
|
260
|
+
*/
|
|
261
|
+
async clear() {
|
|
262
|
+
for (const path of this.#credentialFiles()) {
|
|
263
|
+
try {
|
|
264
|
+
rmSync(path, { force: true })
|
|
265
|
+
} catch {
|
|
266
|
+
// A file that cannot be removed is not worth failing the whole clear.
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
try {
|
|
270
|
+
rmSync(this.pointerPath(), { force: true })
|
|
271
|
+
} catch {
|
|
272
|
+
// As above: idempotent, safe to call when nothing is there.
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* The accounts this realm holds, oldest name first.
|
|
278
|
+
*
|
|
279
|
+
* Deliberately a summary: the page renders this, so it carries no token and no
|
|
280
|
+
* full uid. `expired` is reported rather than filtered — an expired account is
|
|
281
|
+
* precisely the one the user needs to see, so they know to sign in again.
|
|
282
|
+
*/
|
|
283
|
+
async list() {
|
|
284
|
+
const activeHash = await this.activeHash()
|
|
285
|
+
const accounts = []
|
|
286
|
+
for (const path of this.#credentialFiles()) {
|
|
287
|
+
const credential = this.#readCredential(path)
|
|
288
|
+
if (credential === undefined) continue
|
|
289
|
+
if (realmOf(credential) !== this.realm) continue
|
|
290
|
+
if (typeof credential.uid !== 'string' || credential.uid === '') continue
|
|
291
|
+
const hash = uidHashOf(credential.uid)
|
|
292
|
+
accounts.push({
|
|
293
|
+
// NOT the full uid: the handle is the hash, and the short prefix is
|
|
294
|
+
// enough for a human to tell two accounts apart. A screenshot of the
|
|
295
|
+
// card should not be a copy of a stable account identifier.
|
|
296
|
+
uidShort: credential.uid.slice(0, 8),
|
|
297
|
+
hash,
|
|
298
|
+
...credential.nickname === undefined ? {} : { nickname: credential.nickname },
|
|
299
|
+
expiresAtMs: credential.expiresAtMs,
|
|
300
|
+
expired: !(credential.expiresAtMs > Date.now()),
|
|
301
|
+
active: hash === activeHash,
|
|
302
|
+
})
|
|
303
|
+
}
|
|
304
|
+
accounts.sort((a, b) => a.uidShort.localeCompare(b.uidShort))
|
|
305
|
+
return accounts
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Serialize in the cross-tool layout the store already writes.
|
|
311
|
+
*
|
|
312
|
+
* Duplicated from auth.js's private `ownDocument` on purpose: that one is not
|
|
313
|
+
* exported, and widening its export would tempt other modules to depend on the
|
|
314
|
+
* single-file layout this module exists to move past. The format itself must
|
|
315
|
+
* stay identical — the same file is read by other tools.
|
|
316
|
+
*/
|
|
317
|
+
function normalizeCredential(input) {
|
|
318
|
+
if (typeof input !== 'object' || input === null) return undefined
|
|
319
|
+
if (typeof input.accessToken === 'string') return input
|
|
320
|
+
// A document: parse it through the same reader the store uses for its own
|
|
321
|
+
// files, so the two shapes cannot drift.
|
|
322
|
+
return parseWorkBuddyAuth(JSON.stringify(input))
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function credentialDocument(credential) {
|
|
326
|
+
const region = realmOf(credential)
|
|
327
|
+
return {
|
|
328
|
+
version: 1,
|
|
329
|
+
region,
|
|
330
|
+
auth: {
|
|
331
|
+
accessToken: credential.accessToken,
|
|
332
|
+
refreshToken: credential.refreshToken,
|
|
333
|
+
expiresAt: Math.floor(credential.expiresAtMs / 1000),
|
|
334
|
+
...credential.refreshExpiresAtMs === undefined ? {} : { refreshExpiresAt: Math.floor(credential.refreshExpiresAtMs / 1000) },
|
|
335
|
+
domain: credential.domain,
|
|
336
|
+
realm: region,
|
|
337
|
+
},
|
|
338
|
+
account: {
|
|
339
|
+
uid: credential.uid,
|
|
340
|
+
...credential.enterpriseId === undefined ? {} : { enterpriseId: credential.enterpriseId },
|
|
341
|
+
...credential.nickname === undefined ? {} : { nickname: credential.nickname },
|
|
342
|
+
},
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** Create the store for one realm. */
|
|
347
|
+
export function createAccountStore(options) {
|
|
348
|
+
return new WorkBuddyAccountStore(options)
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/** The accounts directory for one realm, for diagnostics. */
|
|
352
|
+
export function accountsDirOf(dataDir, realm) {
|
|
353
|
+
return join(dataDir, ACCOUNTS_DIR_NAME, realm)
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** Create it if absent (mode 0700: it holds credentials). */
|
|
357
|
+
export function ensureAccountsDir(dataDir, realm) {
|
|
358
|
+
const dir = accountsDirOf(dataDir, realm)
|
|
359
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
360
|
+
return dir
|
|
361
|
+
}
|
package/lib/adapter.js
CHANGED
|
@@ -14,6 +14,7 @@ import { openAICompletionsApi } from '@earendil-works/pi-ai/api/openai-completio
|
|
|
14
14
|
import { resolveRetryPolicy } from '@deepseek-ai/dsh-llm'
|
|
15
15
|
import { PiAiAdapter } from '@deepseek-ai/dsh-llm-pi-ai'
|
|
16
16
|
import { normalizeCredits } from './upstream.js'
|
|
17
|
+
import { reasoningFields } from './thinking.js'
|
|
17
18
|
import { WORKBUDDY_MODEL_IDENTITY, modelIdentityKeysOf } from './variants.js'
|
|
18
19
|
|
|
19
20
|
export { WORKBUDDY_MODEL_IDENTITY, modelIdentityKeysOf }
|
|
@@ -116,44 +117,6 @@ function withCatalogDisplay(name, info) {
|
|
|
116
117
|
return suffix === undefined ? name : `${name}${RATE_SEPARATOR}${suffix}`
|
|
117
118
|
}
|
|
118
119
|
|
|
119
|
-
/**
|
|
120
|
-
* Resolve a model's reasoning capability into pi-ai's `thinkingLevelMap`.
|
|
121
|
-
*
|
|
122
|
-
* The upstream's declared set wins outright: when it names a non-empty
|
|
123
|
-
* `supportedEfforts`, exactly those values are offered and nothing else. A
|
|
124
|
-
* row the upstream left undeclared gets no control at all — its selectable set
|
|
125
|
-
* is client-side knowledge the catalog does not carry.
|
|
126
|
-
*
|
|
127
|
-
* `off` is offered only when the upstream declares `canDisableThinking: true`,
|
|
128
|
-
* and it maps to `null` (no `reasoning_effort` on the wire) because the
|
|
129
|
-
* upstream has no `off` spelling to send.
|
|
130
|
-
*/
|
|
131
|
-
export function reasoningFields(info) {
|
|
132
|
-
const reasoning = info.reasoning
|
|
133
|
-
if (reasoning === undefined || reasoning.supports !== true) {
|
|
134
|
-
// Not a reasoning model: pi-ai reads a falsy `reasoning` as "off only".
|
|
135
|
-
return { reasoning: false }
|
|
136
|
-
}
|
|
137
|
-
const declared = reasoning.supportedEfforts
|
|
138
|
-
if (declared === undefined || declared.length === 0) {
|
|
139
|
-
// Undeclared: no thinking control, and no `reasoning_effort` on the wire.
|
|
140
|
-
return { reasoning: false }
|
|
141
|
-
}
|
|
142
|
-
const fallback = typeof reasoning.defaultEffort === 'string' ? reasoning.defaultEffort : undefined
|
|
143
|
-
return {
|
|
144
|
-
reasoning: true,
|
|
145
|
-
thinkingLevelMap: {
|
|
146
|
-
off: fallback ?? null,
|
|
147
|
-
minimal: null,
|
|
148
|
-
low: declared.includes('low') ? 'low' : null,
|
|
149
|
-
medium: declared.includes('medium') ? 'medium' : null,
|
|
150
|
-
high: declared.includes('high') ? 'high' : null,
|
|
151
|
-
xhigh: declared.includes('xhigh') ? 'xhigh' : null,
|
|
152
|
-
max: declared.includes('max') ? 'max' : null,
|
|
153
|
-
},
|
|
154
|
-
}
|
|
155
|
-
}
|
|
156
|
-
|
|
157
120
|
/** Build one pi-ai model descriptor pointing at the loopback shim. */
|
|
158
121
|
function toPiModel(info, baseUrl, modelIdentity) {
|
|
159
122
|
const reasoning = reasoningFields(info)
|
package/lib/atrest.js
CHANGED
|
@@ -336,8 +336,54 @@ export function findDesktopCredentialFile(dir = desktopAuthDir()) {
|
|
|
336
336
|
* cannot be asked for its key. Every failure inside is a reason to fall back
|
|
337
337
|
* to the plugin's own login, never an error the user has to act on.
|
|
338
338
|
*/
|
|
339
|
-
|
|
340
|
-
|
|
339
|
+
/**
|
|
340
|
+
* Every desktop session on disk, newest first, decrypted where possible.
|
|
341
|
+
*
|
|
342
|
+
* The app never deletes a rotated session, so this is also a history of the
|
|
343
|
+
* accounts that have signed in on this machine. Files that cannot be decrypted
|
|
344
|
+
* are skipped rather than reported: a stale file with a key the current app no
|
|
345
|
+
* longer uses is not something the user can act on.
|
|
346
|
+
*/
|
|
347
|
+
export async function readDesktopCredentials(dir = desktopAuthDir()) {
|
|
348
|
+
let entries
|
|
349
|
+
try {
|
|
350
|
+
entries = readdirSync(dir)
|
|
351
|
+
} catch {
|
|
352
|
+
return []
|
|
353
|
+
}
|
|
354
|
+
const files = entries
|
|
355
|
+
.filter(name => name.startsWith('workbuddy-desktop') && name.endsWith('.info'))
|
|
356
|
+
.map(name => join(dir, name))
|
|
357
|
+
.sort((a, b) => {
|
|
358
|
+
try {
|
|
359
|
+
return statSync(b).mtimeMs - statSync(a).mtimeMs
|
|
360
|
+
} catch {
|
|
361
|
+
return 0
|
|
362
|
+
}
|
|
363
|
+
})
|
|
364
|
+
const seen = new Set()
|
|
365
|
+
const out = []
|
|
366
|
+
for (const file of files) {
|
|
367
|
+
const credential = await readDesktopCredential(file)
|
|
368
|
+
if (credential === undefined) continue
|
|
369
|
+
// One entry per account, newest session first: the app rotates a file on
|
|
370
|
+
// every refresh, so the same account appears many times.
|
|
371
|
+
const key = `${credential.uid}|${credential.domain}`
|
|
372
|
+
if (credential.uid === '' || seen.has(key)) continue
|
|
373
|
+
seen.add(key)
|
|
374
|
+
out.push(credential)
|
|
375
|
+
}
|
|
376
|
+
return out
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export async function readDesktopCredential(dirOrFile = desktopAuthDir()) {
|
|
380
|
+
// Accepts a directory (pick the newest session) or one file (read exactly that
|
|
381
|
+
// one). The file form exists for the account switcher: the app keeps every past
|
|
382
|
+
// session on disk, and importing a specific one is how a second account gets
|
|
383
|
+
// added without signing the first one out.
|
|
384
|
+
const file = existsSync(dirOrFile) && statSync(dirOrFile).isFile()
|
|
385
|
+
? dirOrFile
|
|
386
|
+
: findDesktopCredentialFile(dirOrFile)
|
|
341
387
|
if (file === undefined) return undefined
|
|
342
388
|
let document
|
|
343
389
|
try {
|
package/lib/auth.js
CHANGED
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
import { readFileSync, mkdirSync, renameSync, writeFileSync } from 'node:fs'
|
|
24
24
|
import { dirname, join } from 'node:path'
|
|
25
25
|
import { realmOf, regionOf } from './upstream.js'
|
|
26
|
+
import { createAccountStore } from './accounts.js'
|
|
26
27
|
import { workbuddyPluginDataDir } from './paths.js'
|
|
27
28
|
|
|
28
29
|
/** The one provenance a stored credential can have: this plugin's own login. */
|
|
@@ -199,13 +200,36 @@ export class WorkBuddyCredentialStore {
|
|
|
199
200
|
this.variant = options.variant
|
|
200
201
|
this.refresh = options.refresh
|
|
201
202
|
this.refreshMarginMs = options.refreshMarginMs ?? 5 * 60 * 1000
|
|
203
|
+
this.dataDir = options.dataDir ?? workbuddyPluginDataDir()
|
|
202
204
|
this.ownPath = options.ownPath ?? join(
|
|
203
|
-
|
|
205
|
+
this.dataDir,
|
|
204
206
|
options.variant ? options.variant.authFilename : WORKBUDDY_AUTH_FILENAME,
|
|
205
207
|
)
|
|
208
|
+
/**
|
|
209
|
+
* The realm's account list.
|
|
210
|
+
*
|
|
211
|
+
* `ownPath` stays meaningful: it is the single-file location this store used
|
|
212
|
+
* before accounts existed, and it is where a downgrade would look. Imports
|
|
213
|
+
* from it are additive, so the two layouts agree instead of competing.
|
|
214
|
+
*/
|
|
215
|
+
this.accounts = createAccountStore({ realm: options.variant?.region ?? 'cn', dataDir: this.dataDir })
|
|
206
216
|
this.inflight = undefined
|
|
207
217
|
}
|
|
208
218
|
|
|
219
|
+
/**
|
|
220
|
+
* Read the active credential, importing the pre-upgrade file on first use.
|
|
221
|
+
*
|
|
222
|
+
* The import runs at read time rather than in a constructor so it cannot make
|
|
223
|
+
* construction fail: a status read must never be the thing that breaks the
|
|
224
|
+
* card.
|
|
225
|
+
*/
|
|
226
|
+
async #activeWithMigration() {
|
|
227
|
+
const active = await this.accounts.active()
|
|
228
|
+
if (active !== undefined) return active
|
|
229
|
+
if (await this.accounts.importLegacyFile(this.ownPath)) return this.accounts.active()
|
|
230
|
+
return undefined
|
|
231
|
+
}
|
|
232
|
+
|
|
209
233
|
/** The plugin-owned credential path, for diagnostics. */
|
|
210
234
|
ownAuthPath() {
|
|
211
235
|
return this.ownPath
|
|
@@ -246,6 +270,9 @@ export class WorkBuddyCredentialStore {
|
|
|
246
270
|
)
|
|
247
271
|
}
|
|
248
272
|
}
|
|
273
|
+
await this.accounts.save(credential)
|
|
274
|
+
// The single-file copy is kept in step as well: it is what a downgrade
|
|
275
|
+
// reads, and what the "import the desktop session" path already wrote.
|
|
249
276
|
await this.saveOwn(credential)
|
|
250
277
|
}
|
|
251
278
|
|
|
@@ -290,13 +317,27 @@ export class WorkBuddyCredentialStore {
|
|
|
290
317
|
}
|
|
291
318
|
}
|
|
292
319
|
|
|
293
|
-
/**
|
|
320
|
+
/**
|
|
321
|
+
* Sign out completely.
|
|
322
|
+
*
|
|
323
|
+
* This used to remove only the active account. With several saved, the
|
|
324
|
+
* account store's "promote another on removal" behaviour turned "退出登录"
|
|
325
|
+
* into a silent switch: the card showed "signed in" again on its next poll,
|
|
326
|
+
* and requests went out under an account the user had just signed out of.
|
|
327
|
+
* Sign-out means ALL accounts for this edition, plus the downgrade copy.
|
|
328
|
+
*
|
|
329
|
+
* Deleting individual accounts is the separate "删除当前" action.
|
|
330
|
+
*/
|
|
294
331
|
async logout() {
|
|
332
|
+
await this.accounts.clear()
|
|
333
|
+
// The single-file copy kept for downgrades would otherwise be migrated back
|
|
334
|
+
// on the very next read, making "退出登录" / "清除全部" a no-op. Sign-out and
|
|
335
|
+
// clear are the ONLY operations that are allowed to remove it.
|
|
295
336
|
try {
|
|
296
337
|
const { rm } = await import('node:fs/promises')
|
|
297
338
|
await rm(this.ownPath, { force: true })
|
|
298
339
|
} catch {
|
|
299
|
-
// Nothing to remove:
|
|
340
|
+
// Nothing to remove, or a filesystem error: signing out is idempotent.
|
|
300
341
|
}
|
|
301
342
|
}
|
|
302
343
|
|
|
@@ -341,11 +382,11 @@ export class WorkBuddyCredentialStore {
|
|
|
341
382
|
|
|
342
383
|
async readOwn() {
|
|
343
384
|
try {
|
|
344
|
-
return
|
|
385
|
+
return await this.#activeWithMigration()
|
|
345
386
|
} catch {
|
|
346
|
-
// An
|
|
347
|
-
//
|
|
348
|
-
//
|
|
387
|
+
// An unreadable account list means "not signed in". The only recovery
|
|
388
|
+
// either way is to sign in again, and a status read must never be the
|
|
389
|
+
// thing that breaks the card.
|
|
349
390
|
return undefined
|
|
350
391
|
}
|
|
351
392
|
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cache-hit accounting for the model card.
|
|
3
|
+
*
|
|
4
|
+
* The upstream bills a cached prefix at a fraction of a fresh one, so the hit
|
|
5
|
+
* rate is the difference between a cheap conversation and an expensive one.
|
|
6
|
+
* Until now the plugin never read `usage` on the streaming path at all — which
|
|
7
|
+
* is the only path the upstream serves — so the card could say nothing about
|
|
8
|
+
* it, and the only way to see the number was to guess from a bill.
|
|
9
|
+
*
|
|
10
|
+
* Deliberately closed over nothing: these are the two pure transforms the shim
|
|
11
|
+
* and the card need, so they can be tested without a socket or a body.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Pull the `usage` block out of a chunk of forwarded SSE text.
|
|
16
|
+
*
|
|
17
|
+
* Called with text the relay is about to hand to the client, so it must be
|
|
18
|
+
* infallible and must never throw: a usage block it cannot read is worth
|
|
19
|
+
* nothing, while an exception here would break a response that is already
|
|
20
|
+
* streaming. Lines that do not mention `usage` are skipped without parsing,
|
|
21
|
+
* because on a long completion every content delta would otherwise be parsed
|
|
22
|
+
* twice for nothing.
|
|
23
|
+
*
|
|
24
|
+
* @param {string} text Complete SSE lines (event boundaries already honoured).
|
|
25
|
+
* @returns {object|undefined} The last usage block in the text.
|
|
26
|
+
*/
|
|
27
|
+
export function usageFromSseText(text) {
|
|
28
|
+
let usage
|
|
29
|
+
const source = typeof text === 'string' ? text : ''
|
|
30
|
+
for (const line of source.split('\n')) {
|
|
31
|
+
if (!line.startsWith('data:')) continue
|
|
32
|
+
const payload = line.slice(5).trim()
|
|
33
|
+
if (payload === '' || payload === '[DONE]') continue
|
|
34
|
+
// Cheap guard first: the overwhelming majority of events carry a content
|
|
35
|
+
// delta and no usage, and JSON.parse on each of them is pure waste.
|
|
36
|
+
if (!payload.includes('"usage"')) continue
|
|
37
|
+
try {
|
|
38
|
+
const data = JSON.parse(payload)
|
|
39
|
+
if (data?.usage !== undefined && data?.usage !== null && typeof data.usage === 'object') usage = data.usage
|
|
40
|
+
} catch {
|
|
41
|
+
// A block that does not parse is not this function's problem to report.
|
|
42
|
+
continue
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return usage
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** The empty accumulator. */
|
|
49
|
+
export function emptyCacheUsage() {
|
|
50
|
+
return { promptTokens: 0, cachedTokens: 0, turns: 0, lastRate: null, rate: null }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Fold one turn's `usage` into the running cache totals.
|
|
55
|
+
*
|
|
56
|
+
* Cached tokens are clamped to the prompt they belong to: the upstream reports
|
|
57
|
+
* `cached_tokens` separately, and a value larger than `prompt_tokens` would
|
|
58
|
+
* otherwise produce a hit rate above 100% — a number the card must never show,
|
|
59
|
+
* because it would be obviously wrong and would hide the real figure.
|
|
60
|
+
*
|
|
61
|
+
* A turn without a usable `prompt_tokens` is ignored rather than counted as a
|
|
62
|
+
* miss. Some upstream events (and every aborted stream) omit usage entirely,
|
|
63
|
+
* and folding those in as zero-cache turns would pull the average down for
|
|
64
|
+
* reasons that have nothing to do with the cache.
|
|
65
|
+
*
|
|
66
|
+
* @param {object|undefined} previous Accumulator from the prior call.
|
|
67
|
+
* @param {object|undefined} usage The upstream's `usage` block.
|
|
68
|
+
* @returns {object} The next accumulator.
|
|
69
|
+
*/
|
|
70
|
+
export function accumulateCacheUsage(previous, usage) {
|
|
71
|
+
const state = previous ?? emptyCacheUsage()
|
|
72
|
+
const prompt = Number(usage?.prompt_tokens)
|
|
73
|
+
if (!Number.isFinite(prompt) || prompt <= 0) return state
|
|
74
|
+
const reported = Number(usage?.prompt_tokens_details?.cached_tokens)
|
|
75
|
+
const cached = Number.isFinite(reported) ? Math.min(Math.max(reported, 0), prompt) : 0
|
|
76
|
+
const promptTokens = state.promptTokens + prompt
|
|
77
|
+
const cachedTokens = state.cachedTokens + cached
|
|
78
|
+
return {
|
|
79
|
+
promptTokens,
|
|
80
|
+
cachedTokens,
|
|
81
|
+
turns: state.turns + 1,
|
|
82
|
+
lastRate: cached / prompt,
|
|
83
|
+
rate: promptTokens === 0 ? null : cachedTokens / promptTokens,
|
|
84
|
+
}
|
|
85
|
+
}
|