dsh-connect-workbuddy 5.15.2 → 5.17.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.
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as parseCreditMultiplier, $t as resolveDshHome, A as isEncryptedCredentialError, At as pickMediaModel, B as WorkBuddyCredentialRejectedError, Bt as deriveAtRestKey, C as WorkBuddyCredentialStore, Ct as IMAGE_TAG_TEXT_TO_IMAGE, D as defaultDesktopAuthDirs, Dt as imageMimeForPath, E as defaultDesktopAuthCandidates, Et as imageDataUrl, F as workbuddyAccountId, Ft as NATIVE_MODALITY_BY_MODEL_ID, G as forceNeutralHead, Gt as isEncryptedFieldWrapper, H as channelGateMemberOf, Ht as fetchAtRestKeyPayload, I as workbuddyOwnAuthPath, It as imageDefaultFor, J as isCredentialRejectedError, Jt as macosNestedAppBundles, K as isContextTooLongBody, Kt as isWorkbuddyBundle, L as CONTEXT_OVERFLOW_MARKER, Lt as nativeModalityOf, M as legacyWorkbuddyOwnAuthPath, Mt as parseQueueAnswer, N as parseWorkBuddyAuth, Nt as queueNoticeText, O as defaultDesktopAuthPath, Ot as isBareBase64Image, P as preferredAccountName, Pt as pruneTempDir, Q as openingEvidenceOfBody, R as CREDENTIAL_REJECTED_CODE, Rt as WORKBUDDY_APP_EXECUTABLE_ENV, S as WORKBUDDY_AUTH_FILE_ENV, St as IMAGE_TAG_IMAGE_TO_IMAGE, T as authFileName, Tt as WorkBuddyImageError, U as classifyUpstreamError, Ut as findWorkbuddyAppExecutable, V as WorkBuddyUpstreamClient, Vt as deriveAtRestKeyId, W as declaredTools, X as knownRegionOf, Xt as readAtRestKey, Y as isFirstMessageGateBody, Yt as openEncryptedField, Z as modelIdOfBody, Zt as workbuddyAppExecutableCandidates, _ as deriveCatalog, _t as WorkBuddyVideoError, a as readHostHeartbeat, at as requestEvidenceOf, b as ENCRYPTED_CREDENTIAL_CODE, bt as resolveVideoParams, c as WORKBUDDY_CONNECT_VERSION, ct as REFUSES_OFF_MODEL_IDS, dt as offDefaultFor, en as withFileLock, et as parseReasoning, f as piAiRuntimeInfo, ft as offRefused, g as applyContextBudgets, gt as VIDEO_TAG_TEXT_TO_VIDEO, h as WorkBuddyCatalog, ht as VIDEO_TAG_IMAGE_TO_VIDEO, i as processStartTimeMs, it as regionOf, j as isVaultAccountId, jt as sniffImageMime, k as hasEncryptedCredentialFields, kt as parseImageDataUrl, l as createFileRosterSeenStore, lt as defaultOffModelIds, m as FALLBACK_WORKBUDDY_MODELS_GLOBAL, mt as withEffectiveOff, n as clearHostHeartbeat, nt as perturbChannelFingerprints, o as workbuddyHostHeartbeatPath, ot as rewriteSessionTitleModel, p as FALLBACK_WORKBUDDY_MODELS, pt as recordRefusal, q as isConversationIdGateBody, qt as macosBundleExecutable, r as isHeartbeatProcessAlive, rt as prepareChatBody, s as writeHostHeartbeat, st as attachBusyLevels, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tn as writeFileAtomic, tt as parseUpstreamModel, ut as lastRefusalFor, v as fallbackModelsFor, vt as parseSupportedSecondsRange, w as WorkBuddyEncryptedCredentialError, wt as MAX_INPUT_IMAGE_BYTES, x as WORKBUDDY_AUTH_FILENAME, xt as DEFAULT_IMAGE_SIZE, y as withoutRouters, yt as pickVideoModel, z as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, zt as clearAtRestKeyCache } from "./host-heartbeat-Dj8K0mMq.js";
1
+ import { $ as WorkBuddyCredentialRejectedError, A as WORKBUDDY_AUTH_FILENAME, At as VIDEO_TAG_TEXT_TO_VIDEO, B as isEncryptedCredentialError, Bt as imageDataUrl, C as FALLBACK_WORKBUDDY_MODELS_GLOBAL, Cn as writeFileAtomic, Ct as defaultOffModelIds, D as fallbackModelsFor, Dt as recordRefusal, E as deriveCatalog, Et as offRefused, F as authFileName, Ft as DEFAULT_IMAGE_SIZE, G as workbuddyAccountId, Gt as sniffImageMime, H as legacyWorkbuddyOwnAuthPath, Ht as isBareBase64Image, I as defaultDesktopAuthCandidates, It as IMAGE_TAG_IMAGE_TO_IMAGE, J as APP_VERSION, Jt as pruneTempDir, K as workbuddyOwnAuthPath, Kt as parseQueueAnswer, L as defaultDesktopAuthDirs, Lt as IMAGE_TAG_TEXT_TO_IMAGE, Mt as parseSupportedSecondsRange, N as WorkBuddyCredentialStore, Nt as pickVideoModel, O as withoutRouters, Ot as withEffectiveOff, P as WorkBuddyEncryptedCredentialError, Pt as resolveVideoParams, Q as WORKBUDDY_FALLBACK_SYSTEM_PROMPT, R as defaultDesktopAuthPath, Rt as MAX_INPUT_IMAGE_BYTES, S as FALLBACK_WORKBUDDY_MODELS, Sn as withFileLock, St as REFUSES_OFF_MODEL_IDS, T as applyContextBudgets, Tt as offDefaultFor, U as parseWorkBuddyAuth, Ut as parseImageDataUrl, V as isVaultAccountId, Vt as imageMimeForPath, W as preferredAccountName, Wt as pickMediaModel, X as CREDENTIAL_REJECTED_CODE, Xt as imageDefaultFor, Y as CONTEXT_OVERFLOW_MARKER, Yt as NATIVE_MODALITY_BY_MODEL_ID, Zt as nativeModalityOf, _ as isDeviceMode, _n as openEncryptedField, _t as prepareChatBody, a as readHostHeartbeat, at as forceNeutralHead, b as saveDeviceSdkSettings, bt as rewriteSessionTitleModel, c as WORKBUDDY_CONNECT_VERSION, cn as deriveAtRestKey, ct as isCredentialRejectedError, dn as findWorkbuddyAppExecutable, dt as modelIdOfBody, et as WorkBuddyUpstreamClient, f as piAiRuntimeInfo, ft as openingEvidenceOfBody, g as describeDerivedDevices, gn as macosNestedAppBundles, gt as perturbChannelFingerprints, h as createDeviceProfileLookup, hn as macosBundleExecutable, ht as parseUpstreamModel, i as processStartTimeMs, j as WORKBUDDY_AUTH_FILE_ENV, jt as WorkBuddyVideoError, k as ENCRYPTED_CREDENTIAL_CODE, kt as VIDEO_TAG_IMAGE_TO_VIDEO, l as createFileRosterSeenStore, ln as deriveAtRestKeyId, lt as isFirstMessageGateBody, m as createTuringSdk, mn as isWorkbuddyBundle, mt as parseReasoning, n as clearHostHeartbeat, nt as classifyUpstreamError, o as workbuddyHostHeartbeatPath, on as WORKBUDDY_APP_EXECUTABLE_ENV, ot as isContextTooLongBody, p as createDeviceSdkPort, pn as isEncryptedFieldWrapper, pt as parseCreditMultiplier, qt as queueNoticeText, r as isHeartbeatProcessAlive, rn as isDeviceId, rt as declaredTools, s as writeHostHeartbeat, sn as clearAtRestKeyCache, st as isConversationIdGateBody, t as WORKBUDDY_HOST_HEARTBEAT_FILENAME, tt as channelGateMemberOf, un as fetchAtRestKeyPayload, ut as knownRegionOf, v as readDeviceSettings, vn as readAtRestKey, vt as regionOf, w as WorkBuddyCatalog, wt as lastRefusalFor, x as setDeviceMode, xn as resolveDshHome, xt as attachBusyLevels, y as saveDeviceProfile, yn as workbuddyAppExecutableCandidates, yt as requestEvidenceOf, z as hasEncryptedCredentialFields, zt as WorkBuddyImageError } from "./host-heartbeat-09tOJATV.js";
2
2
  import z from "@deepseek-ai/schemastery";
3
3
  import { appendFile, mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
4
4
  import { randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
@@ -6,11 +6,11 @@ import { homedir, tmpdir } from "node:os";
6
6
  import { isAbsolute, join, resolve, sep } from "node:path";
7
7
  import { spawn } from "node:child_process";
8
8
  import { existsSync, mkdtempSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
10
  import { createAssistantMessageEventStream, createProvider, isContextOverflow } from "@earendil-works/pi-ai";
10
11
  import { openAICompletionsApi } from "@earendil-works/pi-ai/api/openai-completions.lazy";
11
12
  import { ReasoningEffortId, createUserMessage, resolveRetryPolicy } from "@deepseek-ai/dsh-llm";
12
13
  import { PiAiAdapter } from "@deepseek-ai/dsh-llm-pi-ai";
13
- import { fileURLToPath, pathToFileURL } from "node:url";
14
14
  import { createServer } from "node:http";
15
15
  import { Readable } from "node:stream";
16
16
  import { isIP } from "node:net";
@@ -373,6 +373,32 @@ const WORKBUDDY_POOL_PATH = "/plugins/dsh-connect-workbuddy/pool";
373
373
  const WORKBUDDY_OAUTH_PATH = "/plugins/dsh-connect-workbuddy/oauth";
374
374
  /** Query parameter selecting which pool batch action a request means. */
375
375
  const WORKBUDDY_POOL_ACTION_PARAM = "action";
376
+ /**
377
+ * 设备头设置(「虚拟值 / 真实值」+ 每账号的覆盖参数)。
378
+ *
379
+ * 一条路由两种方法,因为读和写描述的是同一份文档:
380
+ * - `GET` → `{ mode, accounts }`,卡片渲染切换项与每行的齿轮状态;
381
+ * - `POST` → 立即生效(不像账号池那样有草稿):`{ kind: 'mode', mode }` 或
382
+ * `{ kind: 'account', accountId, machineId?, sessionId? }`。
383
+ *
384
+ * POST + loopback-only:写的是"这台机器对外声称自己是谁",和凭据写入同级。
385
+ * 之所以不挂在账号池的 `/pool` 下面:那份草稿是"点保存才生效"的偏好,而这里的
386
+ * 两个动作都是即时生效,混在一条路由里会让"保存"按钮的语义变得说不清。
387
+ */
388
+ const WORKBUDDY_DEVICE_PROFILE_PATH = "/plugins/dsh-connect-workbuddy/device-profile";
389
+ /**
390
+ * 真实设备参数(本机安装的桌面端 Turing Shield SDK)的状态与取值。
391
+ *
392
+ * - `GET` → `{ tier, sdk, token }`,`token` 只有掩码与长度。
393
+ * - `POST ?action=refresh` → 强制重取一次,再返回同一形状。
394
+ * - `POST ?action=reveal` → `{ token }`,完整值,**只在用户显式点击时**。
395
+ *
396
+ * 为什么把"完整值"单独做成一个动作:这是一枚能代表这台机器的凭据,卡片是
397
+ * 一个会被截图、被贴进 issue 的界面。默认只给掩码,复制/查看各要一次显式动作。
398
+ */
399
+ const WORKBUDDY_DEVICE_SDK_PATH = "/plugins/dsh-connect-workbuddy/device-sdk";
400
+ /** Query parameter selecting it. */
401
+ const WORKBUDDY_DEVICE_SDK_ACTION_PARAM = "action";
376
402
  /** Read the OAuth action off a request URL; unknown/absent means undefined. */
377
403
  function oauthActionOf(url) {
378
404
  const at = url.indexOf("?");
@@ -11229,6 +11255,154 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
11229
11255
  }
11230
11256
  }
11231
11257
  });
11258
+ /**
11259
+ * 设备头设置:档位切换 + 每账号的虚拟参数。
11260
+ *
11261
+ * GET 与 POST 描述的是同一份文档,所以一条路由两种方法。POST 的两种 `kind`
11262
+ * 都是**即时生效**——这里没有草稿,因为齿轮改的是"这台机器对外声称自己是谁",
11263
+ * 一个需要点保存才生效的设备身份,会让"我改完到底发出去的是什么"变成猜测。
11264
+ */
11265
+ const disposeDeviceProfile = ctx.webServer.register({
11266
+ kind: "exact",
11267
+ path: WORKBUDDY_DEVICE_PROFILE_PATH,
11268
+ handler: async (req, res) => {
11269
+ if (!requireLoopback(req, res)) return;
11270
+ const port = deps.deviceSettings;
11271
+ if (port === void 0) return json(res, 503, {
11272
+ reason: "device-settings-unavailable",
11273
+ error: "device settings unavailable"
11274
+ });
11275
+ if (req.method === "GET") {
11276
+ try {
11277
+ json(res, 200, await port.read());
11278
+ } catch (error) {
11279
+ json(res, 500, {
11280
+ reason: "device-settings-failed",
11281
+ error: safeMessage(error)
11282
+ });
11283
+ }
11284
+ return;
11285
+ }
11286
+ if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
11287
+ let body;
11288
+ try {
11289
+ body = await readJsonBody(req);
11290
+ } catch (error) {
11291
+ return json(res, 400, { error: safeMessage(error) });
11292
+ }
11293
+ if (body["kind"] === "mode") {
11294
+ if (!isDeviceMode(body["mode"])) return json(res, 400, { error: "mode must be virtual or real" });
11295
+ try {
11296
+ json(res, 200, await port.setMode(body["mode"]));
11297
+ } catch (error) {
11298
+ json(res, 500, {
11299
+ reason: "device-settings-failed",
11300
+ error: safeMessage(error)
11301
+ });
11302
+ }
11303
+ return;
11304
+ }
11305
+ if (body["kind"] === "account") {
11306
+ const accountId = typeof body["accountId"] === "string" ? body["accountId"] : "";
11307
+ if (!isVaultAccountId(accountId)) return json(res, 400, { error: "accountId is not a well-formed account id" });
11308
+ const values = {};
11309
+ for (const key of ["machineId", "sessionId"]) {
11310
+ const raw = body[key];
11311
+ if (raw === void 0) continue;
11312
+ if (typeof raw !== "string") return json(res, 400, { error: `${key} must be a string` });
11313
+ if (raw !== "" && !isDeviceId(raw)) return json(res, 400, { error: `${key} must be 36 lowercase hex characters` });
11314
+ values[key] = raw;
11315
+ }
11316
+ try {
11317
+ json(res, 200, await port.saveAccount(accountId, values));
11318
+ } catch (error) {
11319
+ json(res, 500, {
11320
+ reason: "device-settings-failed",
11321
+ error: safeMessage(error)
11322
+ });
11323
+ }
11324
+ return;
11325
+ }
11326
+ /**
11327
+ * `kind: 'sdk'` — 手填 SDK 目录与回退开关(作者意见 #1 / #2)。
11328
+ *
11329
+ * 两项都**不做值校验**,只做类型校验:目录填错时的正确反馈是 `probe` 答
11330
+ * `missing`/`error` 并带上那个路径(用户立刻看见"我填的这个不存在"),而
11331
+ * 不是这里 400——后者只会让输入框看起来没保存。路径的合法性由文件系统回答,
11332
+ * 不由字符串正则回答。
11333
+ */
11334
+ if (body["kind"] === "sdk") {
11335
+ const values = {};
11336
+ if (body["sdkDir"] !== void 0) {
11337
+ if (typeof body["sdkDir"] !== "string") return json(res, 400, { error: "sdkDir must be a string" });
11338
+ values.sdkDir = body["sdkDir"];
11339
+ }
11340
+ if (body["sdkFallbackToVirtual"] !== void 0) {
11341
+ if (typeof body["sdkFallbackToVirtual"] !== "boolean") return json(res, 400, { error: "sdkFallbackToVirtual must be a boolean" });
11342
+ values.sdkFallbackToVirtual = body["sdkFallbackToVirtual"];
11343
+ }
11344
+ try {
11345
+ json(res, 200, await port.saveSdk(values));
11346
+ } catch (error) {
11347
+ json(res, 500, {
11348
+ reason: "device-settings-failed",
11349
+ error: safeMessage(error)
11350
+ });
11351
+ }
11352
+ return;
11353
+ }
11354
+ json(res, 400, { error: "kind must be 'mode', 'account' or 'sdk'" });
11355
+ }
11356
+ });
11357
+ /**
11358
+ * 真实设备参数(本机安装的桌面端 SDK)。
11359
+ *
11360
+ * 三个动作的权限不一样:读状态是 GET,强制重取与取完整值是 POST。把完整值
11361
+ * 放在 POST 后面不是形式主义——它会进浏览器历史、会被 proxy 记日志、会被截图,
11362
+ * 而 `GET` 是三者里最容易被动触发的(预取、刷新、插件间的探测)。
11363
+ */
11364
+ const disposeDeviceSdk = ctx.webServer.register({
11365
+ kind: "exact",
11366
+ path: WORKBUDDY_DEVICE_SDK_PATH,
11367
+ handler: async (req, res) => {
11368
+ if (!requireLoopback(req, res)) return;
11369
+ const port = deps.deviceSdk;
11370
+ if (port === void 0) return json(res, 503, {
11371
+ reason: "device-sdk-unavailable",
11372
+ error: "device sdk unavailable"
11373
+ });
11374
+ if (req.method === "GET") {
11375
+ try {
11376
+ json(res, 200, await port.read());
11377
+ } catch (error) {
11378
+ json(res, 500, {
11379
+ reason: "device-sdk-failed",
11380
+ error: safeMessage(error)
11381
+ });
11382
+ }
11383
+ return;
11384
+ }
11385
+ if (req.method !== "POST") return json(res, 405, { error: "method not allowed" });
11386
+ const action = new URL(req.url ?? "/", "http://127.0.0.1").searchParams.get(WORKBUDDY_DEVICE_SDK_ACTION_PARAM);
11387
+ try {
11388
+ if (action === "reveal") {
11389
+ const token = await port.reveal();
11390
+ if (token === void 0) return json(res, 409, {
11391
+ reason: "device-sdk-no-token",
11392
+ error: "no device token is available"
11393
+ });
11394
+ return json(res, 200, { token });
11395
+ }
11396
+ if (action === "refresh") return json(res, 200, await port.refresh());
11397
+ } catch (error) {
11398
+ return json(res, 500, {
11399
+ reason: "device-sdk-failed",
11400
+ error: safeMessage(error)
11401
+ });
11402
+ }
11403
+ json(res, 400, { error: "action must be 'refresh' or 'reveal'" });
11404
+ }
11405
+ });
11232
11406
  return () => {
11233
11407
  disposeBenefitClaim();
11234
11408
  disposeRefresh();
@@ -11244,6 +11418,8 @@ function registerWorkBuddyStatusRoute(ctx, deps) {
11244
11418
  disposeTransfer();
11245
11419
  disposeDiagWrite();
11246
11420
  disposeCliLive();
11421
+ disposeDeviceProfile();
11422
+ disposeDeviceSdk();
11247
11423
  };
11248
11424
  }, "dsh-connect-workbuddy: Web status route");
11249
11425
  }
@@ -11504,7 +11680,12 @@ const Config = z.object({
11504
11680
  z.const("failure"),
11505
11681
  z.const("always")
11506
11682
  ]).default("failure").description("When to perturb scanned messages with invisible characters: \"off\" only rescues after a channel-gate refusal, \"failure\" (default) learns from a successful rescue and starts later requests perturbed, \"always\" starts every request with the dense rescue for a gateway whose plain attempt is guaranteed to fail.")),
11507
- usageIdentity: asVolatile(z.boolean().default(false).description("Make the upstream's usage page record these calls like the official client's: add the X-IDE-* identity headers (which fill the 使用端 column) and send the conversation ids as 32-hex UUIDv7. Off by default — it is a display alignment measured by a reporter, not by this plugin, and the chat channel identity (User-Agent) and request body never change.")),
11683
+ usageIdentity: asVolatile(z.boolean().default(false).description("Send the chat conversation ids in the official client's 32-hex UUIDv7 shape and add a mirroring X-Request-ID. Off by default — it is a display alignment measured by a reporter, not by this plugin, and the chat channel identity (User-Agent) and request body never change.")),
11684
+ wireProfile: asVolatile(z.union([z.const("conservative"), z.const("balanced")]).default("balanced").description("Outbound identity profile. \"balanced\" (default) makes every request claim the same client (WorkBuddy product/IDE/agent headers, X-CodeBuddy-Request, Accept-Language, X-Root-Request-ID, and a per-account X-Machine-ID/X-Session-ID pair) and gives the billing routes a User-Agent plus Origin/Referer. \"conservative\" restores the 5.16.0 bytes exactly, including X-Product: SaaS.")),
11685
+ deviceToken: asVolatile(z.object({
11686
+ file: z.string().default(""),
11687
+ ttlMs: z.number().step(1).min(1e3).default(3e5)
11688
+ }).default({}).description("Optional X-Device-Token supplied by a file, re-read every ttlMs (default 5 min; the token itself expires in about 10). Accepts a bare token or an {\"token\":…} JSON envelope, so pointing it at workbuddy2openapi's .turing_token_cache.json works as-is. Empty file = off. Only used by wireProfile \"balanced\"; a token that cannot be read is skipped with a warning, never invented.")),
11508
11689
  keepPromptLast: asVolatile(z.boolean().default(false).description("Move the harness-injected runtime context above the real prompt, so the WorkBuddy usage page records what you actually typed instead of the injected block. Message count and text are preserved; the one edit is the recorded prompt's own leading <acp> marker. Off by default because it changes the message order the upstream counts.")),
11509
11690
  extraInjectedPrefixes: asVolatile(z.array(z.string()).default([]).description("Extra literal prefixes (issue #133) treated like the harness-injected context markers when keepPromptLast is on — for blocks a companion plugin injects that the built-in list does not recognize. Each entry matches the start of a trailing user message; read only while keepPromptLast is enabled. Sampled when the plugin mounts: reload the plugin (or restart the host) after changing it.")),
11510
11691
  dropForeignThinking: asVolatile(z.boolean().default(false).description("Drop foreign thinking blocks that pi-ai would publish as prose (issue #147). CROSS-PROVIDER turns are dropped automatically: after a provider switch the other provider's unsigned thinking blocks can never be replayed, and pi-ai would flatten them into assistant prose that the gateway refuses with 11128 (issue #163's measured scene). This switch only widens the repair to a model switch inside one of this bundle's own routes. On, those blocks are removed from the request; text and tool calls are untouched. Off by default for the same-route leg because it changes bytes the upstream counts.")),
@@ -11652,9 +11833,51 @@ async function legacyAttributionRegion(value, accountsFor) {
11652
11833
  * upstream never leaves a provider empty.
11653
11834
  */
11654
11835
  function apply(ctx, config) {
11836
+ /**
11837
+ * 每账号的设备覆盖值(设置里齿轮改的那份)。
11838
+ *
11839
+ * 读盘缓存在 `device-profile.ts` 里是**模块级**的,所以这里、路由、以及客户端
11840
+ * 看到的永远是同一份;`saveDeviceProfile` 写完后会立即失效它,改完下一条请求
11841
+ * 就生效,不需要重启。
11842
+ */
11843
+ const deviceProfiles = createDeviceProfileLookup();
11844
+ /**
11845
+ * 真实设备参数的取链(P3)。
11846
+ *
11847
+ * **启动即预热**:`startAutoRefresh()` 立刻取一次,此后在 10 分钟 TTL 到期前自动
11848
+ * 换新。此前只有请求路径会调 `current()`,于是空闲进程的「SDK」分区永远停在
11849
+ * "已加载、没取过"——那与"SDK 坏了"在界面上长得一样,而这正是用户反馈的现象。
11850
+ *
11851
+ * 代价是一次子进程 + 一次取数,之后每 10 分钟一次;`stopAutoRefresh()` 挂在
11852
+ * `ctx.effect` 的清理上,插件卸载时定时器随之消失。
11853
+ *
11854
+ * `dirSource` 让卡片上填的目录**下一次观察就生效**(作者意见 #1):句柄活到
11855
+ * 卸载,而设置随时会变,所以目录每次 `probe` 现问一次。`deviceProfiles` 读盘有
11856
+ * 5 秒缓存,保存会立即失效它。
11857
+ */
11858
+ const turing = createTuringSdk({
11859
+ productVersion: APP_VERSION,
11860
+ dirSource: () => deviceProfiles.sdkDir()
11861
+ });
11862
+ turing.startAutoRefresh();
11863
+ ctx.effect(() => () => {
11864
+ turing.stopAutoRefresh();
11865
+ });
11655
11866
  const client = new WorkBuddyUpstreamClient((message) => {
11656
11867
  ctx.logger.warn(`dsh-connect-workbuddy: ${message}`);
11657
- }, { usageIdentity: unwrapVolatile(config.usageIdentity) === true });
11868
+ }, {
11869
+ usageIdentity: unwrapVolatile(config.usageIdentity) === true,
11870
+ ...unwrapVolatile(config.wireProfile) === void 0 ? {} : { profile: unwrapVolatile(config.wireProfile) }
11871
+ }, (() => {
11872
+ const token = unwrapVolatile(config.deviceToken);
11873
+ const configured = typeof token?.file === "string" ? token.file.trim() : "";
11874
+ return {
11875
+ deviceTokenFile: configured !== "" ? configured : (process.env["WORKBUDDY_DEVICE_TOKEN_FILE"] ?? "").trim(),
11876
+ ...typeof token?.ttlMs === "number" ? { deviceTokenTtlMs: token.ttlMs } : {},
11877
+ deviceProfiles,
11878
+ realDevice: turing.tokens
11879
+ };
11880
+ })());
11658
11881
  /**
11659
11882
  * How long a check-in reading is reused before asking the upstream again.
11660
11883
  *
@@ -12309,595 +12532,671 @@ function apply(ctx, config) {
12309
12532
  cliDirectoryOf = void 0;
12310
12533
  });
12311
12534
  });
12312
- ctx.inject(["webServer"], (webCtx) => registerWorkBuddyStatusRoute(webCtx, {
12313
- store: (region) => stacks[region].store,
12314
- client,
12315
- accountUsable: accountUsabilityProbe,
12535
+ ctx.inject(["webServer"], (webCtx) => {
12316
12536
  /**
12317
- * The CLI route's live turns, for the composer readout.
12537
+ * 池子里每个账号的 uid,用来算"留空时会发出什么"。
12318
12538
  *
12319
- * Read through `cliRuntime` rather than captured once: the runtime is rebuilt
12320
- * whenever `cliBridge` settings change, and the board belongs to the runtime.
12321
- * A captured board would keep answering for a runtime nothing drives any
12322
- * more. Switched off means `undefined`, which the route reports as an empty
12323
- * document.
12539
+ * 按 accountId 去重:同一个账号可能同时出现在两个区域的凭据目录里(用户
12540
+ * 两边都登录过),而它的设备身份只该有一个。`credentialFor` 每账号一次
12541
+ * 文件读,只在这条路由被打开/保存时发生,不在请求热路径上。
12324
12542
  */
12325
- cliLive: () => cliRuntime?.live.snapshot() ?? {
12326
- turns: [],
12327
- serverTime: Date.now()
12328
- },
12329
- /**
12330
- * Why each of the region's accounts cannot serve right now, for the composer
12331
- * panel's table.
12332
- *
12333
- * Runs the SAME `exclusionOf` the pool ranks by, against every account the
12334
- * region knows — not only pool members. Deriving it any other way (a second
12335
- * expiry comparison, or `probe.outcome` read raw) would let the panel call an
12336
- * account rate-limited while the pool has already moved past its cooldown.
12337
- */
12338
- accountExclusions: async (region) => {
12339
- const probes = await readPoolProbes(region);
12340
- const nowMs = Date.now();
12341
- const out = {};
12342
- for (const [accountId, probe] of Object.entries(probes)) {
12343
- const excludedBy = exclusionOf(probe, nowMs);
12344
- if (excludedBy !== void 0) out[accountId] = excludedBy;
12345
- }
12346
- return out;
12347
- },
12348
- displayModels: (region) => displayModels(current(), region),
12349
- /**
12350
- * The LIVE load levels, read beside the saved roster the card lists.
12351
- *
12352
- * The card's model list is the SAVED `lastCatalog`, which carries no load
12353
- * level (load is not persisted — `src/busy.ts`), so the badge has to come
12354
- * from the live roster instead.
12355
- */
12356
- busyLevels: (region) => liveBusyLevels(region),
12357
- enabledModelIds: (region) => regionStateOf(current(), region).enabledModelIds ?? [],
12358
- imageModelIds: (region) => [...effectiveImageIds(regionStateOf(current(), region), displayModels(current(), region))],
12359
- offModelIds: (region) => savedOffModelIds(regionStateOf(current(), region), displayModels(current(), region)),
12360
- contextBudgets: (region) => regionStateOf(current(), region).contextBudgets ?? {},
12361
- defaultThinkingEfforts: (region) => regionStateOf(current(), region).defaultThinkingEfforts ?? {},
12362
- discoverModels,
12363
- /**
12364
- * This region's first-sighting readout, the data behind the composer pill's
12365
- * "· N 新模型" segment.
12366
- *
12367
- * READ-ONLY here: only the reconciler's `note` writes first-sighting
12368
- * history, so no amount of polling by the pill or the card can change who
12369
- * counts as new — the one property that keeps the marker honest.
12370
- */
12371
- rosterSeen: (region) => stacks[region].rosterSeen.readout(),
12372
- mediaModels: readMediaModels,
12373
- regionEnabled: (region) => regionEnabled(current(), region),
12374
- /**
12375
- * The region's committed sidebar-credit flag, read from the same config the
12376
- * card writes. Exposed on the Host's answer because the browser settings
12377
- * mirror goes stale for this namespace on the affected 0.1.7 deployments,
12378
- * which made the switch look unable to turn the line off ("关闭不了").
12379
- */
12380
- showCreditsInMainUi: (region) => regionStateOf(current(), region).showCreditsInMainUi !== false,
12381
- /**
12382
- * Whether the model may call the image tool here. Read from the committed
12383
- * value like the flag above, and deliberately `=== true`: an absent setting
12384
- * is NOT consent to let the model spend.
12385
- */
12386
- imageToolEnabled: (region) => regionStateOf(current(), region).imageToolEnabled === true,
12387
- /** Whether the model may call the video tool here. Same opt-IN read as above. */
12388
- videoToolEnabled: (region) => regionStateOf(current(), region).videoToolEnabled === true,
12389
- /**
12390
- * The video model pinned per tag in this region, for the card's per-mode
12391
- * picker. Read from the committed value like the switches above: the picker
12392
- * must render what the TOOL will actually use, not what the browser mirror
12393
- * happens to hold.
12394
- */
12395
- preferredVideoModels: (region) => regionStateOf(current(), region).preferredVideoModels ?? {},
12396
- /**
12397
- * Whether the optional CodeBuddy CLI route is mounted (`codebuddy_ask` tool
12398
- * + `/codebuddy` command).
12399
- *
12400
- * GLOBAL, so it takes no region. `=== true` like `imageToolEnabled`, not
12401
- * `!== false`: switching this on lets a child process edit files and spend
12402
- * CodeBuddy quota, so an absent value must read as OFF rather than as
12403
- * consent. `cliBridge` is a volatile field, hence the unwrap.
12404
- */
12405
- cliBridgeEnabled: () => unwrapVolatile(current().cliBridge)?.enabled === true,
12406
- /**
12407
- * The model / reasoning effort the optional CodeBuddy CLI route runs on.
12408
- *
12409
- * `cliBridge` is volatile, hence the unwrap; absent keys read as `''` —
12410
- * "the CLI's own default" — because an empty pin is a COMMITTED value the
12411
- * card's pickers can render, not a missing one.
12412
- */
12413
- cliBridgeModel: () => unwrapVolatile(current().cliBridge)?.model ?? "",
12414
- cliBridgeEffort: () => unwrapVolatile(current().cliBridge)?.effort ?? "",
12415
- cliBridgeRegionOrder: () => unwrapVolatile(current().cliBridge)?.regionOrder ?? "",
12416
- /**
12417
- * Whether the request path drops foreign thinking blocks (issue #147), read
12418
- * live so the card's switch reflects the value the NEXT request will use
12419
- * rather than the one captured at mount.
12420
- */
12421
- dropForeignThinking: () => unwrapVolatile(current().dropForeignThinking) === true,
12422
- /**
12423
- * What the last request had to drop, so the card can explain a turn that
12424
- * arrived looking like working notes instead of leaving the user to conclude
12425
- * the model broke. `undefined` until a request actually removes something —
12426
- * an empty report would render as a permanent warning.
12427
- */
12428
- latestForeignThinking: () => latestForeignThinking,
12429
- /**
12430
- * WHERE the readout sits, resolved here rather than read from the browser
12431
- * settings mirror, for the same measured reason as the flag above: on the
12432
- * affected 0.1.7 deployments that mirror never picks up this plugin's
12433
- * writes, and a control reading it would keep showing the old seat.
12434
- */
12435
- creditPosition: (region) => creditPositionOf(current(), region),
12436
- /**
12437
- * One minimal request per named model, through the region's own credential.
12438
- *
12439
- * Resolved here rather than in the route so the browser half never touches a
12440
- * token: the route passes only model ids and receives only outcomes.
12441
- *
12442
- * `quotaRefreshAtMs` is the region's nearest monthly refresh point, read from
12443
- * the SAME credit answer the card displays. It is the only cooldown this
12444
- * service ever states — an exhausted monthly resource that resets at a known
12445
- * time — so it is what makes "when can I use this again" answerable for an
12446
- * out-of-credit result. Every other limited outcome has no time anywhere, and
12447
- * the probe reports exactly that instead of inventing one.
12448
- */
12449
- async probeModels(region, modelIds, options) {
12450
- let credential;
12451
- try {
12452
- credential = await stacks[region].store.resolve();
12453
- } catch (error) {
12454
- return modelIds.map((modelId) => ({
12455
- modelId,
12456
- outcome: "credential-rejected",
12457
- message: error instanceof Error ? error.message.slice(0, 300) : String(error).slice(0, 300)
12458
- }));
12543
+ const deviceAccounts = async () => {
12544
+ const entries = [];
12545
+ const seen = /* @__PURE__ */ new Set();
12546
+ for (const region of REGION_KEYS) for (const account of await stacks[region].store.accounts()) {
12547
+ if (seen.has(account.id)) continue;
12548
+ const credential = await stacks[region].store.credentialFor(account.id);
12549
+ if (credential === void 0 || credential.uid === "") continue;
12550
+ seen.add(account.id);
12551
+ entries.push({
12552
+ accountId: account.id,
12553
+ uid: credential.uid
12554
+ });
12459
12555
  }
12460
- const quotaRefreshAtMs = await quotaRefreshOf(region, credential);
12461
- const results = [];
12462
- for (const modelId of modelIds) results.push(await probeModel({
12463
- client,
12464
- credential,
12465
- modelId,
12466
- nowMs: Date.now(),
12467
- ...quotaRefreshAtMs === void 0 ? {} : { quotaRefreshAtMs },
12468
- ...options?.signal === void 0 ? {} : { signal: options.signal }
12469
- }));
12470
- return results;
12471
- },
12556
+ return entries;
12557
+ };
12472
12558
  /**
12473
- * Output-speed measurement (issue #92), region-scoped like every other
12474
- * spending path.
12559
+ * 给设置补上派生值。读、切档、保存三条路都走它,三个响应因此永远同形。
12475
12560
  *
12476
- * Deliberately NOT routed through the probe's failover machinery: a speed
12477
- * number describes the MODEL, and having the pool silently serve the run
12478
- * from a different account would attach one account's rate limit (6004) to
12479
- * another's measurement. The selected credential runs all three samples, so
12480
- * "it failed" means this account could not measure it, which is the honest
12481
- * answer.
12561
+ * 派生值算不出来(本机没有设备盐)时整块缺席,而不是回一个空对象:缺席是
12562
+ * "这次没算",空对象是"算过,一个都没有",弹窗对这两种情况要说不同的话。
12482
12563
  */
12483
- async measureTps(region, modelIds, options) {
12484
- let credential;
12564
+ const withDerived = async (settings) => {
12485
12565
  try {
12486
- credential = await stacks[region].store.resolve();
12487
- } catch (error) {
12488
- const message = error instanceof Error ? error.message.slice(0, 300) : String(error).slice(0, 300);
12489
- return modelIds.map((modelId) => ({
12490
- modelId,
12491
- outcome: "credential-rejected",
12492
- samples: 0,
12493
- message
12494
- }));
12495
- }
12496
- const results = [];
12497
- for (const modelId of modelIds) {
12498
- const sample = await measureTps({
12499
- client,
12500
- credential,
12501
- modelId,
12502
- ...options?.signal === void 0 ? {} : { signal: options.signal }
12503
- });
12504
- results.push({
12505
- modelId: sample.modelId,
12506
- outcome: sample.tokensPerSecond === void 0 ? "failed" : "ok",
12507
- ...sample.tokensPerSecond === void 0 ? {} : { tokensPerSecond: sample.tokensPerSecond },
12508
- ...sample.timeToFirstTokenMs === void 0 ? {} : { timeToFirstTokenMs: sample.timeToFirstTokenMs },
12509
- ...sample.outputTokens === void 0 ? {} : { outputTokens: sample.outputTokens },
12510
- samples: sample.samples,
12511
- ...sample.reason === void 0 ? {} : { reason: sample.reason },
12512
- ...sample.credit === void 0 ? {} : { credit: sample.credit }
12513
- });
12566
+ const derived = await describeDerivedDevices(await deviceAccounts());
12567
+ return derived === void 0 ? settings : {
12568
+ ...settings,
12569
+ derived
12570
+ };
12571
+ } catch {
12572
+ return settings;
12514
12573
  }
12515
- return results;
12516
- },
12517
- regionUsable(region, usable) {
12518
- if (stacks[region].catalog.setRegionUsable(usable)) invalidateCatalog();
12519
- },
12520
- /**
12521
- * The account pool, resolved per region.
12522
- *
12523
- * Region-scoped throughout: the CN and international pools are separate
12524
- * stacks of accounts, so one region's pool can never rank or bill the
12525
- * other's accounts.
12526
- *
12527
- * The pool decides who serves a FAILED request (see `failoverAccountFor`),
12528
- * and it does so without writing `config.accounts[region]`: a retry borrows
12529
- * another member's credential for that one request, leaving the record of
12530
- * what the user picked — and the account the next request starts from —
12531
- * untouched.
12532
- */
12533
- pool: {
12534
- preferences: (region) => poolPreferencesOf(current(), region),
12535
- members: (region) => poolMembersOf(region),
12574
+ };
12575
+ return registerWorkBuddyStatusRoute(webCtx, {
12576
+ store: (region) => stacks[region].store,
12577
+ client,
12578
+ accountUsable: accountUsabilityProbe,
12536
12579
  /**
12537
- * The first-paint member list (issue #77): local state only.
12580
+ * The CLI route's live turns, for the composer readout.
12538
12581
  *
12539
- * This is `localPoolMembers`, i.e. the SAME list the request path already
12540
- * consults — saved members, their last credit snapshot (if it is still
12541
- * fresh), and their last probe result. No upstream call, so the card's
12542
- * account table can paint before any billing endpoint answers; live
12543
- * figures arrive with the full document a moment later.
12544
- *
12545
- * A member whose credit snapshot has expired simply carries no `credits`,
12546
- * which the card renders as "—" rather than as zero.
12582
+ * Read through `cliRuntime` rather than captured once: the runtime is rebuilt
12583
+ * whenever `cliBridge` settings change, and the board belongs to the runtime.
12584
+ * A captured board would keep answering for a runtime nothing drives any
12585
+ * more. Switched off means `undefined`, which the route reports as an empty
12586
+ * document.
12547
12587
  */
12548
- localMembers: (region) => localPoolMembers(region),
12588
+ cliLive: () => cliRuntime?.live.snapshot() ?? {
12589
+ turns: [],
12590
+ serverTime: Date.now()
12591
+ },
12549
12592
  /**
12550
- * The checked accounts that resolve to a local sign-in.
12593
+ * 设备头设置(「虚拟值 / 真实值」+ 每账号覆盖参数)。
12551
12594
  *
12552
- * A local scan only — no upstream calls — so the route's empty-pool guard
12553
- * can use it on every batch. {@link poolMembersOf} is the expensive one
12554
- * (it fetches credits per account) and is not suitable there.
12595
+ * uid 由 Host 自己解:卡片只认识 accountId,而构头时需要 uid——让浏览器把
12596
+ * uid 传上来,等于把账号在网关侧的身份交给前端,没有必要。
12597
+ *
12598
+ * 每次响应都带一份 `derived`:**留空时真正会发出去的那一对 id**。弹窗把它
12599
+ * 显示在空输入框下面,于是"自动派生"不再是句承诺,而是一个能核对的值。
12600
+ * 派生用 uid(与 `deviceHeaders()` 同一份输入),所以界面上的值等于线上的值。
12555
12601
  */
12556
- effectiveMemberAccountIds: async (region) => {
12557
- const saved = poolPreferencesOf(current(), region).memberAccountIds;
12558
- if (saved.length === 0) return [];
12559
- const accounts = await stacks[region].store.accounts();
12560
- return effectiveMembersOf(saved, new Set(accounts.map((account) => account.id)));
12602
+ deviceSettings: {
12603
+ read: async () => withDerived(await readDeviceSettings()),
12604
+ setMode: async (mode) => withDerived(await setDeviceMode(mode)),
12605
+ saveAccount: async (accountId, values) => {
12606
+ for (const region of REGION_KEYS) {
12607
+ const credential = await stacks[region].store.credentialFor(accountId);
12608
+ if (credential !== void 0) return withDerived(await saveDeviceProfile(accountId, {
12609
+ ...values,
12610
+ uid: credential.uid
12611
+ }));
12612
+ }
12613
+ return withDerived(await saveDeviceProfile(accountId, values));
12614
+ },
12615
+ saveSdk: (values) => saveDeviceSdkSettings(values)
12561
12616
  },
12562
12617
  /**
12563
- * Last measured display name per saved member id (issue #60).
12618
+ * 真实设备参数(本机安装的桌面端 SDK)的状态与取值。
12564
12619
  *
12565
- * Answers the one question the card cannot answer itself: a saved member
12566
- * whose sign-in is gone has no row in the roster, so the name the pool
12567
- * once saw is the only thing that can identify it. Read from the runtime
12568
- * probe store — no upstream call, and no credential touched.
12620
+ * `mode` 现读而不是缓存:切档与面板是同一屏的两件事,中间隔一次 5 秒缓存就会
12621
+ * 出现"已经切到真实值、面板还说虚拟值"的一屏。
12622
+ */
12623
+ deviceSdk: createDeviceSdkPort({
12624
+ sdk: turing,
12625
+ mode: async () => (await readDeviceSettings()).mode
12626
+ }),
12627
+ /**
12628
+ * Why each of the region's accounts cannot serve right now, for the composer
12629
+ * panel's table.
12569
12630
  *
12570
- * Best-effort, and deliberately NOT filtered to ghosts here: the route
12571
- * knows which ids are unlisted (it built the roster) and names only
12572
- * those, so this stays a plain lookup with one meaning.
12631
+ * Runs the SAME `exclusionOf` the pool ranks by, against every account the
12632
+ * region knows — not only pool members. Deriving it any other way (a second
12633
+ * expiry comparison, or `probe.outcome` read raw) would let the panel call an
12634
+ * account rate-limited while the pool has already moved past its cooldown.
12573
12635
  */
12574
- memberNames: async (region) => {
12636
+ accountExclusions: async (region) => {
12575
12637
  const probes = await readPoolProbes(region);
12576
- const names = {};
12638
+ const nowMs = Date.now();
12639
+ const out = {};
12577
12640
  for (const [accountId, probe] of Object.entries(probes)) {
12578
- if (probe.accountName === void 0 || probe.accountName === "") continue;
12579
- names[accountId] = probe.accountName;
12641
+ const excludedBy = exclusionOf(probe, nowMs);
12642
+ if (excludedBy !== void 0) out[accountId] = excludedBy;
12580
12643
  }
12581
- return names;
12644
+ return out;
12582
12645
  },
12646
+ displayModels: (region) => displayModels(current(), region),
12583
12647
  /**
12584
- * Local sign-ins the pool does NOT cover.
12648
+ * The LIVE load levels, read beside the saved roster the card lists.
12585
12649
  *
12586
- * Sent so the card can offer them to check in. Membership is an explicit
12587
- * opt-in, and a user cannot opt in to an account the card never shows.
12650
+ * The card's model list is the SAVED `lastCatalog`, which carries no load
12651
+ * level (load is not persisted — `src/busy.ts`), so the badge has to come
12652
+ * from the live roster instead.
12588
12653
  */
12589
- async otherAccounts(region) {
12590
- const wanted = new Set(poolPreferencesOf(current(), region).memberAccountIds);
12591
- return (await stacks[region].store.accounts()).filter((account) => !wanted.has(account.id)).map((account) => ({
12592
- id: account.id,
12593
- accountName: account.accountName,
12594
- ...account.enterprise === true ? { enterprise: true } : {}
12595
- }));
12596
- },
12654
+ busyLevels: (region) => liveBusyLevels(region),
12655
+ enabledModelIds: (region) => regionStateOf(current(), region).enabledModelIds ?? [],
12656
+ imageModelIds: (region) => [...effectiveImageIds(regionStateOf(current(), region), displayModels(current(), region))],
12657
+ offModelIds: (region) => savedOffModelIds(regionStateOf(current(), region), displayModels(current(), region)),
12658
+ contextBudgets: (region) => regionStateOf(current(), region).contextBudgets ?? {},
12659
+ defaultThinkingEfforts: (region) => regionStateOf(current(), region).defaultThinkingEfforts ?? {},
12660
+ discoverModels,
12597
12661
  /**
12598
- * Today's check-in state per account, for the pool table.
12662
+ * This region's first-sighting readout, the data behind the composer pill's
12663
+ * "· N 新模型" segment.
12599
12664
  *
12600
- * Read per account through `credentialFor` (never `resolve`), so asking
12601
- * about an account cannot change which one is billing. A per-account
12602
- * failure is simply omitted, which the card renders as unknown.
12665
+ * READ-ONLY here: only the reconciler's `note` writes first-sighting
12666
+ * history, so no amount of polling by the pill or the card can change who
12667
+ * counts as new — the one property that keeps the marker honest.
12603
12668
  */
12604
- async checkedInToday(region) {
12605
- if (!poolPreferencesOf(current(), region).enabled) return {};
12606
- const store = stacks[region].store;
12607
- const accounts = await store.accounts();
12608
- const now = Date.now();
12609
- const entries = await Promise.all(accounts.map(async (account) => {
12610
- const cached = checkinStateCache[region]?.[account.id];
12611
- if (cached !== void 0 && now - cached.atMs < CHECKIN_CACHE_MS) return [account.id, cached.checkedIn];
12612
- const credential = await store.credentialFor(account.id).catch(() => void 0);
12613
- if (credential === void 0) return void 0;
12614
- const status = await client.fetchCheckinStatus(credential).catch(() => void 0);
12615
- if (status === void 0) return void 0;
12616
- checkinStateCache[region] = {
12617
- ...checkinStateCache[region],
12618
- [account.id]: {
12619
- checkedIn: status.todayCheckedIn,
12620
- atMs: now
12621
- }
12622
- };
12623
- return [account.id, status.todayCheckedIn];
12624
- }));
12625
- return Object.fromEntries(entries.filter((entry) => entry !== void 0));
12626
- },
12669
+ rosterSeen: (region) => stacks[region].rosterSeen.readout(),
12670
+ mediaModels: readMediaModels,
12671
+ regionEnabled: (region) => regionEnabled(current(), region),
12627
12672
  /**
12628
- * Today's check-in state from the cells already measured this process.
12629
- *
12630
- * The first-paint counterpart (issue #77) of `checkedInToday`: it reads
12631
- * `checkinStateCache` and nothing else, so painting the table never waits
12632
- * on one request per account. An unmeasured account is absent, which the
12633
- * card already renders as unknown rather than as "not checked in".
12673
+ * The region's committed sidebar-credit flag, read from the same config the
12674
+ * card writes. Exposed on the Host's answer because the browser settings
12675
+ * mirror goes stale for this namespace on the affected 0.1.7 deployments,
12676
+ * which made the switch look unable to turn the line off ("关闭不了").
12634
12677
  */
12635
- cachedCheckedInToday(region) {
12636
- if (!poolPreferencesOf(current(), region).enabled) return {};
12637
- const now = Date.now();
12638
- const state = checkinStateCache[region] ?? {};
12639
- const cached = {};
12640
- for (const [accountId, entry] of Object.entries(state)) {
12641
- if (now - entry.atMs >= CHECKIN_CACHE_MS) continue;
12642
- cached[accountId] = entry.checkedIn;
12643
- }
12644
- return cached;
12645
- },
12678
+ showCreditsInMainUi: (region) => regionStateOf(current(), region).showCreditsInMainUi !== false,
12646
12679
  /**
12647
- * Claimable promotional benefits per account (issue #79).
12648
- *
12649
- * Only campaigns the account can STILL claim are returned — a claimed or
12650
- * lapsed one is absent, which is what the issue asked for. Absent means
12651
- * the card shows no benefit line at all.
12652
- *
12653
- * Two status reads per account, so it is cached for `BENEFIT_CACHE_MS` and
12654
- * skipped entirely when the pool is off (same reasoning as
12655
- * `checkedInToday`: no table, no request).
12680
+ * Whether the model may call the image tool here. Read from the committed
12681
+ * value like the flag above, and deliberately `=== true`: an absent setting
12682
+ * is NOT consent to let the model spend.
12656
12683
  */
12657
- async benefits(region) {
12658
- if (!poolPreferencesOf(current(), region).enabled) return {};
12659
- const store = stacks[region].store;
12660
- const accounts = await store.accounts();
12661
- const now = Date.now();
12662
- const entries = await Promise.all(accounts.map(async (account) => {
12663
- const cached = benefitStateCache[region]?.[account.id];
12664
- if (cached !== void 0 && now - cached.atMs < 18e5) return [account.id, cached.views];
12665
- const credential = await store.credentialFor(account.id).catch(() => void 0);
12666
- if (credential === void 0) return void 0;
12667
- if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") return [account.id, []];
12668
- const read = await client.fetchBenefits(credential).catch(() => void 0);
12669
- if (read === void 0) return void 0;
12670
- const views = claimableBenefits(read, now);
12671
- benefitStateCache[region] = {
12672
- ...benefitStateCache[region],
12673
- [account.id]: {
12674
- views,
12675
- atMs: now
12676
- }
12677
- };
12678
- return [account.id, views];
12679
- }));
12680
- return Object.fromEntries(entries.filter((entry) => entry !== void 0));
12681
- },
12684
+ imageToolEnabled: (region) => regionStateOf(current(), region).imageToolEnabled === true,
12685
+ /** Whether the model may call the video tool here. Same opt-IN read as above. */
12686
+ videoToolEnabled: (region) => regionStateOf(current(), region).videoToolEnabled === true,
12682
12687
  /**
12683
- * Claimable benefits from the readings already taken this process.
12684
- *
12685
- * The first-paint counterpart of `benefits`, mirroring
12686
- * `cachedCheckedInToday`: no request, so painting never blocks on two
12687
- * calls per account. An unmeasured account is absent, not empty.
12688
+ * The video model pinned per tag in this region, for the card's per-mode
12689
+ * picker. Read from the committed value like the switches above: the picker
12690
+ * must render what the TOOL will actually use, not what the browser mirror
12691
+ * happens to hold.
12688
12692
  */
12689
- cachedBenefits(region) {
12690
- if (!poolPreferencesOf(current(), region).enabled) return {};
12691
- const now = Date.now();
12692
- const state = benefitStateCache[region] ?? {};
12693
- const cached = {};
12694
- for (const [accountId, entry] of Object.entries(state)) {
12695
- if (now - entry.atMs >= 18e5) continue;
12696
- cached[accountId] = entry.views;
12697
- }
12698
- return cached;
12699
- },
12693
+ preferredVideoModels: (region) => regionStateOf(current(), region).preferredVideoModels ?? {},
12700
12694
  /**
12701
- * Drop one account's cached benefit reading (issue #79).
12695
+ * Whether the optional CodeBuddy CLI route is mounted (`codebuddy_ask` tool
12696
+ * + `/codebuddy` command).
12702
12697
  *
12703
- * The claim route writes upstream itself, so this cache is the ONLY thing
12704
- * that can keep answering "claimable" after a successful claim — and it was
12705
- * never invalidated: the credits went up, the 领取 pill stayed for up to 30
12706
- * minutes, and the claim looked like it had silently failed. That is the
12707
- * exact symptom the user reported. `checkin` already deletes its entries
12708
- * after a batch; this is the same rule for the claim.
12698
+ * GLOBAL, so it takes no region. `=== true` like `imageToolEnabled`, not
12699
+ * `!== false`: switching this on lets a child process edit files and spend
12700
+ * CodeBuddy quota, so an absent value must read as OFF rather than as
12701
+ * consent. `cliBridge` is a volatile field, hence the unwrap.
12702
+ */
12703
+ cliBridgeEnabled: () => unwrapVolatile(current().cliBridge)?.enabled === true,
12704
+ /**
12705
+ * The model / reasoning effort the optional CodeBuddy CLI route runs on.
12709
12706
  *
12710
- * Deleting (rather than overwriting with the post-claim read) keeps the
12711
- * ownership where it belongs: the route already made the authoritative
12712
- * re-read, and the next `benefits()` refills this from live data.
12707
+ * `cliBridge` is volatile, hence the unwrap; absent keys read as `''` —
12708
+ * "the CLI's own default" — because an empty pin is a COMMITTED value the
12709
+ * card's pickers can render, not a missing one.
12713
12710
  */
12714
- invalidateBenefit(region, accountId) {
12715
- const cached = benefitStateCache[region];
12716
- if (cached !== void 0) delete cached[accountId];
12717
- },
12718
- async currentAccountId(region) {
12719
- await applyPoolSelection(region).catch(() => void 0);
12720
- const credential = await stacks[region].store.current().catch(() => void 0);
12721
- if (credential === void 0) return void 0;
12722
- if (await servingAccountIsExcluded(region).catch(() => false)) return void 0;
12723
- return workbuddyAccountId(credential);
12724
- },
12711
+ cliBridgeModel: () => unwrapVolatile(current().cliBridge)?.model ?? "",
12712
+ cliBridgeEffort: () => unwrapVolatile(current().cliBridge)?.effort ?? "",
12713
+ cliBridgeRegionOrder: () => unwrapVolatile(current().cliBridge)?.regionOrder ?? "",
12725
12714
  /**
12726
- * Only the CN app rewards a daily check-in; the international region has
12727
- * no equivalent here, so its card must not offer the action.
12715
+ * Whether the request path drops foreign thinking blocks (issue #147), read
12716
+ * live so the card's switch reflects the value the NEXT request will use
12717
+ * rather than the one captured at mount.
12728
12718
  */
12729
- checkinSupported: (region) => region === "cn",
12730
- checkin: async (region) => {
12731
- const rows = await checkinAllAccounts(await poolTargets(region), poolRunnerDeps(region));
12732
- for (const row of rows) {
12733
- if (row.status === "failed") continue;
12734
- const cached = checkinStateCache[region];
12735
- if (cached !== void 0) delete cached[row.accountId];
12736
- }
12737
- return rows;
12738
- },
12739
- test: async (region, modelId, onRow) => {
12740
- const rows = await testAllAccounts(await poolTargets(region), modelId, poolRunnerDeps(region), onRow);
12741
- await writePoolProbes(region, probeUpdatesOf(rows));
12742
- return rows;
12743
- },
12744
- catalog: (region) => displayModels(current(), region),
12719
+ dropForeignThinking: () => unwrapVolatile(current().dropForeignThinking) === true,
12745
12720
  /**
12746
- * Test ONE account against the region's target model.
12721
+ * What the last request had to drop, so the card can explain a turn that
12722
+ * arrived looking like working notes instead of leaving the user to conclude
12723
+ * the model broke. `undefined` until a request actually removes something —
12724
+ * an empty report would render as a permanent warning.
12725
+ */
12726
+ latestForeignThinking: () => latestForeignThinking,
12727
+ /**
12728
+ * WHERE the readout sits, resolved here rather than read from the browser
12729
+ * settings mirror, for the same measured reason as the flag above: on the
12730
+ * affected 0.1.7 deployments that mirror never picks up this plugin's
12731
+ * writes, and a control reading it would keep showing the old seat.
12732
+ */
12733
+ creditPosition: (region) => creditPositionOf(current(), region),
12734
+ /**
12735
+ * One minimal request per named model, through the region's own credential.
12747
12736
  *
12748
- * The per-row button's Host half. Reuses the batch's probe dependency
12749
- * (same client, same probe size, same quota-refresh input) so a row
12750
- * result and a batch result are the SAME measurement — only the
12751
- * persistence is scoped to one id instead of every member.
12737
+ * Resolved here rather than in the route so the browser half never touches a
12738
+ * token: the route passes only model ids and receives only outcomes.
12752
12739
  *
12753
- * Returns undefined when the region cannot name a target model (the
12754
- * same refusal the batch route reports as 409) — the card says so
12755
- * rather than pretending a test ran.
12740
+ * `quotaRefreshAtMs` is the region's nearest monthly refresh point, read from
12741
+ * the SAME credit answer the card displays. It is the only cooldown this
12742
+ * service ever states — an exhausted monthly resource that resets at a known
12743
+ * time — so it is what makes "when can I use this again" answerable for an
12744
+ * out-of-credit result. Every other limited outcome has no time anywhere, and
12745
+ * the probe reports exactly that instead of inventing one.
12756
12746
  */
12757
- testOne: async (region, accountId) => {
12758
- const target = regionTargetModel(region);
12759
- if (target === void 0) return void 0;
12760
- const store = stacks[region].store;
12761
- const credential = await store.credentialFor(accountId).catch(() => void 0);
12762
- if (credential === void 0) return {
12763
- accountId,
12764
- accountName: "",
12765
- result: {
12766
- modelId: target,
12747
+ async probeModels(region, modelIds, options) {
12748
+ let credential;
12749
+ try {
12750
+ credential = await stacks[region].store.resolve();
12751
+ } catch (error) {
12752
+ return modelIds.map((modelId) => ({
12753
+ modelId,
12767
12754
  outcome: "credential-rejected",
12768
- status: 0,
12769
- message: "no stored credential for this account"
12770
- }
12771
- };
12772
- const accountName = (await store.accounts().catch(() => [])).find((account) => account.id === accountId)?.accountName ?? "";
12773
- const result = await poolRunnerDeps(region).probe(credential, target);
12774
- await writePoolProbes(region, probeUpdatesOf([{
12775
- accountId,
12776
- accountName,
12777
- result
12778
- }]));
12779
- return {
12780
- accountId,
12781
- accountName,
12782
- result
12783
- };
12755
+ message: error instanceof Error ? error.message.slice(0, 300) : String(error).slice(0, 300)
12756
+ }));
12757
+ }
12758
+ const quotaRefreshAtMs = await quotaRefreshOf(region, credential);
12759
+ const results = [];
12760
+ for (const modelId of modelIds) results.push(await probeModel({
12761
+ client,
12762
+ credential,
12763
+ modelId,
12764
+ nowMs: Date.now(),
12765
+ ...quotaRefreshAtMs === void 0 ? {} : { quotaRefreshAtMs },
12766
+ ...options?.signal === void 0 ? {} : { signal: options.signal }
12767
+ }));
12768
+ return results;
12784
12769
  },
12785
12770
  /**
12786
- * Forget ONE account's plugin-stored credential (the vault entry; the
12787
- * desktop app's files are never touched). The card rescans afterwards,
12788
- * so the row disappears the moment the write lands.
12789
- *
12790
- * AND DROP THE REGION'S PERSISTED PIN, when this was the pinned account
12791
- * (issue #155's second report). `removeAccount` forgets the selection in
12792
- * memory only, so the next `applySelection` — a restart, or any settings
12793
- * save — re-reads the dead id out of `accounts.<region>`, re-pins it, and
12794
- * the tab returns to「已保存的账号在本机已不存在」with the card's advice
12795
- * pointing at a list that state does not render. The clear is decided from
12796
- * the settings document rather than from the store, and is scoped to the
12797
- * one region that pinned this account: an unrelated removal must not move
12798
- * anybody off the account they chose.
12771
+ * Output-speed measurement (issue #92), region-scoped like every other
12772
+ * spending path.
12799
12773
  *
12800
- * FAIL-SOFT, like the field repair above: the credential is already gone by
12801
- * the time this runs, so a settings write that cannot land must not be
12802
- * reported as a failed removal — that would tell the user the account is
12803
- * still there when it is not.
12774
+ * Deliberately NOT routed through the probe's failover machinery: a speed
12775
+ * number describes the MODEL, and having the pool silently serve the run
12776
+ * from a different account would attach one account's rate limit (6004) to
12777
+ * another's measurement. The selected credential runs all three samples, so
12778
+ * "it failed" means this account could not measure it, which is the honest
12779
+ * answer.
12804
12780
  */
12805
- removeOne: async (region, accountId) => {
12806
- const removed = await stacks[region].store.removeAccount(accountId);
12781
+ async measureTps(region, modelIds, options) {
12782
+ let credential;
12807
12783
  try {
12808
- await clearRegionAccountSelection(hostSettings(), settingsNs, region, accountId, unwrapVolatile(current().accountId), legacyAccountRegion);
12784
+ credential = await stacks[region].store.resolve();
12809
12785
  } catch (error) {
12810
- ctx.logger.warn("dsh-connect-workbuddy: the account was removed, but the region could not be un-pinned from settings; the selection may reappear as orphaned after a restart", error);
12786
+ const message = error instanceof Error ? error.message.slice(0, 300) : String(error).slice(0, 300);
12787
+ return modelIds.map((modelId) => ({
12788
+ modelId,
12789
+ outcome: "credential-rejected",
12790
+ samples: 0,
12791
+ message
12792
+ }));
12811
12793
  }
12812
- return removed;
12813
- }
12814
- },
12815
- /**
12816
- * OAuth QR sign-in for this card. The session lives in `src/oauth.ts`
12817
- * (in-process, keyed by loginId); the Host's only extra duty is
12818
- * persisting the finished credential into the region's vault — the same
12819
- * store the request path reads, so the account is selectable the moment
12820
- * the poll answers.
12821
- */
12822
- oauth: {
12823
- async start(region) {
12824
- return oauthStart(region);
12794
+ const results = [];
12795
+ for (const modelId of modelIds) {
12796
+ const sample = await measureTps({
12797
+ client,
12798
+ credential,
12799
+ modelId,
12800
+ ...options?.signal === void 0 ? {} : { signal: options.signal }
12801
+ });
12802
+ results.push({
12803
+ modelId: sample.modelId,
12804
+ outcome: sample.tokensPerSecond === void 0 ? "failed" : "ok",
12805
+ ...sample.tokensPerSecond === void 0 ? {} : { tokensPerSecond: sample.tokensPerSecond },
12806
+ ...sample.timeToFirstTokenMs === void 0 ? {} : { timeToFirstTokenMs: sample.timeToFirstTokenMs },
12807
+ ...sample.outputTokens === void 0 ? {} : { outputTokens: sample.outputTokens },
12808
+ samples: sample.samples,
12809
+ ...sample.reason === void 0 ? {} : { reason: sample.reason },
12810
+ ...sample.credit === void 0 ? {} : { credit: sample.credit }
12811
+ });
12812
+ }
12813
+ return results;
12825
12814
  },
12826
- async poll(region, loginId) {
12827
- const answer = await oauthPoll(loginId, region);
12828
- if (!answer.done) return answer;
12829
- if ("error" in answer) return answer;
12830
- const store = stacks[region].store;
12831
- const accountId = await store.addOAuthAccount({
12832
- accessToken: answer.account.accessToken,
12833
- refreshToken: answer.account.refreshToken,
12834
- expiresAtMs: answer.account.expiresAtMs,
12835
- ...answer.account.refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs: answer.account.refreshExpiresAtMs },
12836
- domain: answer.account.domain,
12837
- uid: answer.account.uid,
12838
- ...answer.account.nickname === void 0 ? {} : { nickname: answer.account.nickname },
12839
- ...answer.account.uin === void 0 ? {} : { uin: answer.account.uin },
12840
- ...answer.account.enterpriseId === void 0 ? {} : { enterpriseId: answer.account.enterpriseId }
12841
- }).catch((error) => {
12842
- throw new Error("the account was signed in but could not be saved: " + (error instanceof Error ? error.message : String(error)));
12843
- });
12844
- return {
12845
- done: true,
12846
- accountId,
12847
- accountName: (await store.accounts().catch(() => [])).find((account) => account.id === accountId)?.accountName ?? answer.account.nickname ?? ""
12848
- };
12849
- }
12850
- },
12851
- /**
12852
- * Batch credential export / import, in the transfer file format the
12853
- * sibling credential managers share. The Host owns every byte of the
12854
- * vault; the route only ferries parsed answers.
12855
- */
12856
- transfer: {
12857
- async exportAccounts(region, accountIds) {
12858
- const store = stacks[region].store;
12859
- const accounts = await store.accounts().catch(() => []);
12860
- const wanted = new Set(accountIds);
12861
- const records = [];
12862
- for (const account of accounts) {
12863
- if (!wanted.has(account.id)) continue;
12864
- const credential = await store.credentialFor(account.id).catch(() => void 0);
12865
- if (credential === void 0) continue;
12866
- records.push(transferRecordOf(credential, {
12867
- auth: {
12868
- accessToken: credential.accessToken,
12869
- refreshToken: credential.refreshToken,
12870
- expiresAt: credential.expiresAtMs > 0 ? Math.floor(credential.expiresAtMs / 1e3) : 0,
12871
- ...credential.refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAt: Math.floor(credential.refreshExpiresAtMs / 1e3) },
12872
- ...credential.lastRefreshAtMs === void 0 ? {} : { lastRefreshTime: Math.floor(credential.lastRefreshAtMs / 1e3) },
12873
- domain: credential.domain
12874
- },
12875
- account: {
12876
- uid: credential.uid,
12877
- ...credential.enterpriseId === void 0 ? {} : { enterpriseId: credential.enterpriseId },
12878
- ...credential.nickname === void 0 ? {} : { nickname: credential.nickname },
12879
- ...credential.uin === void 0 ? {} : { uin: credential.uin }
12880
- }
12815
+ regionUsable(region, usable) {
12816
+ if (stacks[region].catalog.setRegionUsable(usable)) invalidateCatalog();
12817
+ },
12818
+ /**
12819
+ * The account pool, resolved per region.
12820
+ *
12821
+ * Region-scoped throughout: the CN and international pools are separate
12822
+ * stacks of accounts, so one region's pool can never rank or bill the
12823
+ * other's accounts.
12824
+ *
12825
+ * The pool decides who serves a FAILED request (see `failoverAccountFor`),
12826
+ * and it does so without writing `config.accounts[region]`: a retry borrows
12827
+ * another member's credential for that one request, leaving the record of
12828
+ * what the user picked — and the account the next request starts from —
12829
+ * untouched.
12830
+ */
12831
+ pool: {
12832
+ preferences: (region) => poolPreferencesOf(current(), region),
12833
+ members: (region) => poolMembersOf(region),
12834
+ /**
12835
+ * The first-paint member list (issue #77): local state only.
12836
+ *
12837
+ * This is `localPoolMembers`, i.e. the SAME list the request path already
12838
+ * consults — saved members, their last credit snapshot (if it is still
12839
+ * fresh), and their last probe result. No upstream call, so the card's
12840
+ * account table can paint before any billing endpoint answers; live
12841
+ * figures arrive with the full document a moment later.
12842
+ *
12843
+ * A member whose credit snapshot has expired simply carries no `credits`,
12844
+ * which the card renders as "—" rather than as zero.
12845
+ */
12846
+ localMembers: (region) => localPoolMembers(region),
12847
+ /**
12848
+ * The checked accounts that resolve to a local sign-in.
12849
+ *
12850
+ * A local scan only — no upstream calls — so the route's empty-pool guard
12851
+ * can use it on every batch. {@link poolMembersOf} is the expensive one
12852
+ * (it fetches credits per account) and is not suitable there.
12853
+ */
12854
+ effectiveMemberAccountIds: async (region) => {
12855
+ const saved = poolPreferencesOf(current(), region).memberAccountIds;
12856
+ if (saved.length === 0) return [];
12857
+ const accounts = await stacks[region].store.accounts();
12858
+ return effectiveMembersOf(saved, new Set(accounts.map((account) => account.id)));
12859
+ },
12860
+ /**
12861
+ * Last measured display name per saved member id (issue #60).
12862
+ *
12863
+ * Answers the one question the card cannot answer itself: a saved member
12864
+ * whose sign-in is gone has no row in the roster, so the name the pool
12865
+ * once saw is the only thing that can identify it. Read from the runtime
12866
+ * probe store — no upstream call, and no credential touched.
12867
+ *
12868
+ * Best-effort, and deliberately NOT filtered to ghosts here: the route
12869
+ * knows which ids are unlisted (it built the roster) and names only
12870
+ * those, so this stays a plain lookup with one meaning.
12871
+ */
12872
+ memberNames: async (region) => {
12873
+ const probes = await readPoolProbes(region);
12874
+ const names = {};
12875
+ for (const [accountId, probe] of Object.entries(probes)) {
12876
+ if (probe.accountName === void 0 || probe.accountName === "") continue;
12877
+ names[accountId] = probe.accountName;
12878
+ }
12879
+ return names;
12880
+ },
12881
+ /**
12882
+ * Local sign-ins the pool does NOT cover.
12883
+ *
12884
+ * Sent so the card can offer them to check in. Membership is an explicit
12885
+ * opt-in, and a user cannot opt in to an account the card never shows.
12886
+ */
12887
+ async otherAccounts(region) {
12888
+ const wanted = new Set(poolPreferencesOf(current(), region).memberAccountIds);
12889
+ return (await stacks[region].store.accounts()).filter((account) => !wanted.has(account.id)).map((account) => ({
12890
+ id: account.id,
12891
+ accountName: account.accountName,
12892
+ ...account.enterprise === true ? { enterprise: true } : {}
12893
+ }));
12894
+ },
12895
+ /**
12896
+ * Today's check-in state per account, for the pool table.
12897
+ *
12898
+ * Read per account through `credentialFor` (never `resolve`), so asking
12899
+ * about an account cannot change which one is billing. A per-account
12900
+ * failure is simply omitted, which the card renders as unknown.
12901
+ */
12902
+ async checkedInToday(region) {
12903
+ if (!poolPreferencesOf(current(), region).enabled) return {};
12904
+ const store = stacks[region].store;
12905
+ const accounts = await store.accounts();
12906
+ const now = Date.now();
12907
+ const entries = await Promise.all(accounts.map(async (account) => {
12908
+ const cached = checkinStateCache[region]?.[account.id];
12909
+ if (cached !== void 0 && now - cached.atMs < CHECKIN_CACHE_MS) return [account.id, cached.checkedIn];
12910
+ const credential = await store.credentialFor(account.id).catch(() => void 0);
12911
+ if (credential === void 0) return void 0;
12912
+ const status = await client.fetchCheckinStatus(credential).catch(() => void 0);
12913
+ if (status === void 0) return void 0;
12914
+ checkinStateCache[region] = {
12915
+ ...checkinStateCache[region],
12916
+ [account.id]: {
12917
+ checkedIn: status.todayCheckedIn,
12918
+ atMs: now
12919
+ }
12920
+ };
12921
+ return [account.id, status.todayCheckedIn];
12922
+ }));
12923
+ return Object.fromEntries(entries.filter((entry) => entry !== void 0));
12924
+ },
12925
+ /**
12926
+ * Today's check-in state from the cells already measured this process.
12927
+ *
12928
+ * The first-paint counterpart (issue #77) of `checkedInToday`: it reads
12929
+ * `checkinStateCache` and nothing else, so painting the table never waits
12930
+ * on one request per account. An unmeasured account is absent, which the
12931
+ * card already renders as unknown rather than as "not checked in".
12932
+ */
12933
+ cachedCheckedInToday(region) {
12934
+ if (!poolPreferencesOf(current(), region).enabled) return {};
12935
+ const now = Date.now();
12936
+ const state = checkinStateCache[region] ?? {};
12937
+ const cached = {};
12938
+ for (const [accountId, entry] of Object.entries(state)) {
12939
+ if (now - entry.atMs >= CHECKIN_CACHE_MS) continue;
12940
+ cached[accountId] = entry.checkedIn;
12941
+ }
12942
+ return cached;
12943
+ },
12944
+ /**
12945
+ * Claimable promotional benefits per account (issue #79).
12946
+ *
12947
+ * Only campaigns the account can STILL claim are returned — a claimed or
12948
+ * lapsed one is absent, which is what the issue asked for. Absent means
12949
+ * the card shows no benefit line at all.
12950
+ *
12951
+ * Two status reads per account, so it is cached for `BENEFIT_CACHE_MS` and
12952
+ * skipped entirely when the pool is off (same reasoning as
12953
+ * `checkedInToday`: no table, no request).
12954
+ */
12955
+ async benefits(region) {
12956
+ if (!poolPreferencesOf(current(), region).enabled) return {};
12957
+ const store = stacks[region].store;
12958
+ const accounts = await store.accounts();
12959
+ const now = Date.now();
12960
+ const entries = await Promise.all(accounts.map(async (account) => {
12961
+ const cached = benefitStateCache[region]?.[account.id];
12962
+ if (cached !== void 0 && now - cached.atMs < 18e5) return [account.id, cached.views];
12963
+ const credential = await store.credentialFor(account.id).catch(() => void 0);
12964
+ if (credential === void 0) return void 0;
12965
+ if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") return [account.id, []];
12966
+ const read = await client.fetchBenefits(credential).catch(() => void 0);
12967
+ if (read === void 0) return void 0;
12968
+ const views = claimableBenefits(read, now);
12969
+ benefitStateCache[region] = {
12970
+ ...benefitStateCache[region],
12971
+ [account.id]: {
12972
+ views,
12973
+ atMs: now
12974
+ }
12975
+ };
12976
+ return [account.id, views];
12881
12977
  }));
12978
+ return Object.fromEntries(entries.filter((entry) => entry !== void 0));
12979
+ },
12980
+ /**
12981
+ * Claimable benefits from the readings already taken this process.
12982
+ *
12983
+ * The first-paint counterpart of `benefits`, mirroring
12984
+ * `cachedCheckedInToday`: no request, so painting never blocks on two
12985
+ * calls per account. An unmeasured account is absent, not empty.
12986
+ */
12987
+ cachedBenefits(region) {
12988
+ if (!poolPreferencesOf(current(), region).enabled) return {};
12989
+ const now = Date.now();
12990
+ const state = benefitStateCache[region] ?? {};
12991
+ const cached = {};
12992
+ for (const [accountId, entry] of Object.entries(state)) {
12993
+ if (now - entry.atMs >= 18e5) continue;
12994
+ cached[accountId] = entry.views;
12995
+ }
12996
+ return cached;
12997
+ },
12998
+ /**
12999
+ * Drop one account's cached benefit reading (issue #79).
13000
+ *
13001
+ * The claim route writes upstream itself, so this cache is the ONLY thing
13002
+ * that can keep answering "claimable" after a successful claim — and it was
13003
+ * never invalidated: the credits went up, the 领取 pill stayed for up to 30
13004
+ * minutes, and the claim looked like it had silently failed. That is the
13005
+ * exact symptom the user reported. `checkin` already deletes its entries
13006
+ * after a batch; this is the same rule for the claim.
13007
+ *
13008
+ * Deleting (rather than overwriting with the post-claim read) keeps the
13009
+ * ownership where it belongs: the route already made the authoritative
13010
+ * re-read, and the next `benefits()` refills this from live data.
13011
+ */
13012
+ invalidateBenefit(region, accountId) {
13013
+ const cached = benefitStateCache[region];
13014
+ if (cached !== void 0) delete cached[accountId];
13015
+ },
13016
+ async currentAccountId(region) {
13017
+ await applyPoolSelection(region).catch(() => void 0);
13018
+ const credential = await stacks[region].store.current().catch(() => void 0);
13019
+ if (credential === void 0) return void 0;
13020
+ if (await servingAccountIsExcluded(region).catch(() => false)) return void 0;
13021
+ return workbuddyAccountId(credential);
13022
+ },
13023
+ /**
13024
+ * Only the CN app rewards a daily check-in; the international region has
13025
+ * no equivalent here, so its card must not offer the action.
13026
+ */
13027
+ checkinSupported: (region) => region === "cn",
13028
+ checkin: async (region) => {
13029
+ const rows = await checkinAllAccounts(await poolTargets(region), poolRunnerDeps(region));
13030
+ for (const row of rows) {
13031
+ if (row.status === "failed") continue;
13032
+ const cached = checkinStateCache[region];
13033
+ if (cached !== void 0) delete cached[row.accountId];
13034
+ }
13035
+ return rows;
13036
+ },
13037
+ test: async (region, modelId, onRow) => {
13038
+ const rows = await testAllAccounts(await poolTargets(region), modelId, poolRunnerDeps(region), onRow);
13039
+ await writePoolProbes(region, probeUpdatesOf(rows));
13040
+ return rows;
13041
+ },
13042
+ catalog: (region) => displayModels(current(), region),
13043
+ /**
13044
+ * Test ONE account against the region's target model.
13045
+ *
13046
+ * The per-row button's Host half. Reuses the batch's probe dependency
13047
+ * (same client, same probe size, same quota-refresh input) so a row
13048
+ * result and a batch result are the SAME measurement — only the
13049
+ * persistence is scoped to one id instead of every member.
13050
+ *
13051
+ * Returns undefined when the region cannot name a target model (the
13052
+ * same refusal the batch route reports as 409) — the card says so
13053
+ * rather than pretending a test ran.
13054
+ */
13055
+ testOne: async (region, accountId) => {
13056
+ const target = regionTargetModel(region);
13057
+ if (target === void 0) return void 0;
13058
+ const store = stacks[region].store;
13059
+ const credential = await store.credentialFor(accountId).catch(() => void 0);
13060
+ if (credential === void 0) return {
13061
+ accountId,
13062
+ accountName: "",
13063
+ result: {
13064
+ modelId: target,
13065
+ outcome: "credential-rejected",
13066
+ status: 0,
13067
+ message: "no stored credential for this account"
13068
+ }
13069
+ };
13070
+ const accountName = (await store.accounts().catch(() => [])).find((account) => account.id === accountId)?.accountName ?? "";
13071
+ const result = await poolRunnerDeps(region).probe(credential, target);
13072
+ await writePoolProbes(region, probeUpdatesOf([{
13073
+ accountId,
13074
+ accountName,
13075
+ result
13076
+ }]));
13077
+ return {
13078
+ accountId,
13079
+ accountName,
13080
+ result
13081
+ };
13082
+ },
13083
+ /**
13084
+ * Forget ONE account's plugin-stored credential (the vault entry; the
13085
+ * desktop app's files are never touched). The card rescans afterwards,
13086
+ * so the row disappears the moment the write lands.
13087
+ *
13088
+ * AND DROP THE REGION'S PERSISTED PIN, when this was the pinned account
13089
+ * (issue #155's second report). `removeAccount` forgets the selection in
13090
+ * memory only, so the next `applySelection` — a restart, or any settings
13091
+ * save — re-reads the dead id out of `accounts.<region>`, re-pins it, and
13092
+ * the tab returns to「已保存的账号在本机已不存在」with the card's advice
13093
+ * pointing at a list that state does not render. The clear is decided from
13094
+ * the settings document rather than from the store, and is scoped to the
13095
+ * one region that pinned this account: an unrelated removal must not move
13096
+ * anybody off the account they chose.
13097
+ *
13098
+ * FAIL-SOFT, like the field repair above: the credential is already gone by
13099
+ * the time this runs, so a settings write that cannot land must not be
13100
+ * reported as a failed removal — that would tell the user the account is
13101
+ * still there when it is not.
13102
+ */
13103
+ removeOne: async (region, accountId) => {
13104
+ const removed = await stacks[region].store.removeAccount(accountId);
13105
+ try {
13106
+ await clearRegionAccountSelection(hostSettings(), settingsNs, region, accountId, unwrapVolatile(current().accountId), legacyAccountRegion);
13107
+ } catch (error) {
13108
+ ctx.logger.warn("dsh-connect-workbuddy: the account was removed, but the region could not be un-pinned from settings; the selection may reappear as orphaned after a restart", error);
13109
+ }
13110
+ return removed;
12882
13111
  }
12883
- return { accounts: records };
12884
13112
  },
12885
- async previewImport(region, text) {
12886
- return previewTransferFile(text);
13113
+ /**
13114
+ * OAuth QR sign-in for this card. The session lives in `src/oauth.ts`
13115
+ * (in-process, keyed by loginId); the Host's only extra duty is
13116
+ * persisting the finished credential into the region's vault — the same
13117
+ * store the request path reads, so the account is selectable the moment
13118
+ * the poll answers.
13119
+ */
13120
+ oauth: {
13121
+ async start(region) {
13122
+ return oauthStart(region);
13123
+ },
13124
+ async poll(region, loginId) {
13125
+ const answer = await oauthPoll(loginId, region);
13126
+ if (!answer.done) return answer;
13127
+ if ("error" in answer) return answer;
13128
+ const store = stacks[region].store;
13129
+ const accountId = await store.addOAuthAccount({
13130
+ accessToken: answer.account.accessToken,
13131
+ refreshToken: answer.account.refreshToken,
13132
+ expiresAtMs: answer.account.expiresAtMs,
13133
+ ...answer.account.refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAtMs: answer.account.refreshExpiresAtMs },
13134
+ domain: answer.account.domain,
13135
+ uid: answer.account.uid,
13136
+ ...answer.account.nickname === void 0 ? {} : { nickname: answer.account.nickname },
13137
+ ...answer.account.uin === void 0 ? {} : { uin: answer.account.uin },
13138
+ ...answer.account.enterpriseId === void 0 ? {} : { enterpriseId: answer.account.enterpriseId }
13139
+ }).catch((error) => {
13140
+ throw new Error("the account was signed in but could not be saved: " + (error instanceof Error ? error.message : String(error)));
13141
+ });
13142
+ return {
13143
+ done: true,
13144
+ accountId,
13145
+ accountName: (await store.accounts().catch(() => [])).find((account) => account.id === accountId)?.accountName ?? answer.account.nickname ?? ""
13146
+ };
13147
+ }
12887
13148
  },
12888
- async importAccounts(region, text, indexes) {
12889
- const { changes, imported, skipped } = mergeTransferRecords(parseTransferFile(text), indexes, region, (domain) => knownRegionOf(domain));
12890
- const store = stacks[region].store;
12891
- for (const [id, credential] of changes) await store.addOAuthAccount(credential).catch((error) => {
12892
- throw new Error("imported account " + id + " could not be stored: " + (error instanceof Error ? error.message : String(error)));
12893
- });
12894
- return {
12895
- imported,
12896
- skipped
12897
- };
13149
+ /**
13150
+ * Batch credential export / import, in the transfer file format the
13151
+ * sibling credential managers share. The Host owns every byte of the
13152
+ * vault; the route only ferries parsed answers.
13153
+ */
13154
+ transfer: {
13155
+ async exportAccounts(region, accountIds) {
13156
+ const store = stacks[region].store;
13157
+ const accounts = await store.accounts().catch(() => []);
13158
+ const wanted = new Set(accountIds);
13159
+ const records = [];
13160
+ for (const account of accounts) {
13161
+ if (!wanted.has(account.id)) continue;
13162
+ const credential = await store.credentialFor(account.id).catch(() => void 0);
13163
+ if (credential === void 0) continue;
13164
+ records.push(transferRecordOf(credential, {
13165
+ auth: {
13166
+ accessToken: credential.accessToken,
13167
+ refreshToken: credential.refreshToken,
13168
+ expiresAt: credential.expiresAtMs > 0 ? Math.floor(credential.expiresAtMs / 1e3) : 0,
13169
+ ...credential.refreshExpiresAtMs === void 0 ? {} : { refreshExpiresAt: Math.floor(credential.refreshExpiresAtMs / 1e3) },
13170
+ ...credential.lastRefreshAtMs === void 0 ? {} : { lastRefreshTime: Math.floor(credential.lastRefreshAtMs / 1e3) },
13171
+ domain: credential.domain
13172
+ },
13173
+ account: {
13174
+ uid: credential.uid,
13175
+ ...credential.enterpriseId === void 0 ? {} : { enterpriseId: credential.enterpriseId },
13176
+ ...credential.nickname === void 0 ? {} : { nickname: credential.nickname },
13177
+ ...credential.uin === void 0 ? {} : { uin: credential.uin }
13178
+ }
13179
+ }));
13180
+ }
13181
+ return { accounts: records };
13182
+ },
13183
+ async previewImport(region, text) {
13184
+ return previewTransferFile(text);
13185
+ },
13186
+ async importAccounts(region, text, indexes) {
13187
+ const { changes, imported, skipped } = mergeTransferRecords(parseTransferFile(text), indexes, region, (domain) => knownRegionOf(domain));
13188
+ const store = stacks[region].store;
13189
+ for (const [id, credential] of changes) await store.addOAuthAccount(credential).catch((error) => {
13190
+ throw new Error("imported account " + id + " could not be stored: " + (error instanceof Error ? error.message : String(error)));
13191
+ });
13192
+ return {
13193
+ imported,
13194
+ skipped
13195
+ };
13196
+ }
12898
13197
  }
12899
- }
12900
- }));
13198
+ });
13199
+ });
12901
13200
  /**
12902
13201
  * The region's nearest monthly quota refresh, or undefined when unknown.
12903
13202
  *