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.
@@ -1,8 +1,8 @@
1
1
  import { lstat, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
2
2
  import { createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
3
3
  import { homedir, tmpdir } from "node:os";
4
- import { dirname, join, resolve, win32 } from "node:path";
5
- import { execFile, execFileSync } from "node:child_process";
4
+ import { dirname, join, posix, resolve, win32 } from "node:path";
5
+ import { execFile, execFileSync, spawn } from "node:child_process";
6
6
  import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
7
7
  import { fileURLToPath } from "node:url";
8
8
  //#region src/host-peers.ts
@@ -962,6 +962,599 @@ function clearAtRestKeyCache() {
962
962
  cachedAppExecutable = void 0;
963
963
  }
964
964
  //#endregion
965
+ //#region src/windows-acl.ts
966
+ /**
967
+ * Windows ACL hardening for the plugin's credential vault (issue #183).
968
+ *
969
+ * THE REPORT. `<dsh home>/workbuddy-vault/<region>/<accountId>.json` holds the
970
+ * decrypted WorkBuddy `accessToken` / `refreshToken` as plaintext JSON, and the
971
+ * writer asked for `mode: 0o600`. On POSIX that is the whole story. On Windows
972
+ * `mode` is accepted and effectively ignored: a file's permissions come from the
973
+ * DACL it inherits from its parent directory, and nothing in `fs.writeFile` or
974
+ * `fs.rename` consults the mode argument there. The reporter measured the
975
+ * result with `Get-Acl`: the vault files came out readable by
976
+ * `<machine>\CodexSandboxUsers` — the account DSH's own sandbox runs as — so any
977
+ * sandboxed process, sibling plugin or script on that machine could read a
978
+ * usable JWT straight off disk.
979
+ *
980
+ * WHY HARDEN THE DIRECTORY, NOT JUST THE FILE. Two reasons, both measured:
981
+ *
982
+ * 1. The writer commits with an atomic replace (`writeFileAtomic`): a fresh
983
+ * `<name>.<hex>.tmp` inode is created and renamed over the target. A
984
+ * per-file ACL applied AFTER the rename leaves a window in which the new
985
+ * inode carries whatever it inherited, and a crash mid-sequence leaves a
986
+ * file that was never hardened. Children of a hardened directory inherit
987
+ * the hardened ACEs at creation, so the replacement is born correct.
988
+ * 2. Windows RE-PROPAGATES inheritable ACEs down an existing tree, so
989
+ * hardening the directory also repairs the files already sitting in it.
990
+ * Verified on a real Windows 11 host: a file carrying
991
+ * `Everyone: FullControl` inherited from `~/.dsh` came out with exactly the
992
+ * three intended ACEs after only the directory was hardened.
993
+ *
994
+ * WHY NOT `icacls /T`. Measured on the same host: `/T` combined with an
995
+ * `(OI)(CI)` grant spec blanks the DACL of the FILES it walks — they end up with
996
+ * zero ACEs, which reads as "nobody may read this" and would break the plugin's
997
+ * own reads. The two-pass form (directories with `(OI)(CI)`, then files with a
998
+ * plain `(F)` grant) produces the correct result, so `/T` is deliberately not
999
+ * used anywhere here.
1000
+ *
1001
+ * WHY WINDOWS SIDS AND NOT NAMES. `icacls` prints and accepts localized account
1002
+ * names, and this project's hosts are frequently zh-CN (`Everyone` shows up as
1003
+ * `Everyone` but `BUILTIN\Administrators` does not). The `*S-1-5-…` form makes
1004
+ * every argument locale-independent, so the same argv works on any UI language.
1005
+ *
1006
+ * WHY `OWNER RIGHTS` (S-1-3-4) RATHER THAN THE CURRENT USER. Resolving the
1007
+ * current user's SID costs a child process (`whoami`) on every hardening round,
1008
+ * and the answer is already implied: the process that creates a file becomes its
1009
+ * owner, so `OWNER RIGHTS` grants exactly the account that will read it back.
1010
+ * `SYSTEM` and `Administrators` are kept so backup/AV/service software that
1011
+ * legitimately expects to reach user files is not locked out — removing them
1012
+ * would make the vault unmanageable on a machine where the user's own session is
1013
+ * not the one repairing it.
1014
+ *
1015
+ * WHAT THIS IS AND IS NOT. This is the issue's suggestion #2 (explicit ACLs
1016
+ * after writing), which it calls "the smallest change". It is NOT DPAPI
1017
+ * encryption (suggestion #1): the bytes on disk remain plaintext, so an
1018
+ * administrator, a SYSTEM service, or an attacker who has already achieved the
1019
+ * user's own token can still read them. Closing that gap requires encrypting the
1020
+ * document with a key bound to the user profile, which is a format change to the
1021
+ * vault and cannot be done without a migration; it is tracked separately. The
1022
+ * README says plainly that the file holds plaintext tokens.
1023
+ *
1024
+ * FAILURE IS NOT FATAL. A credential write is on the sign-in path: refusing to
1025
+ * persist a credential because the ACL could not be applied would turn a
1026
+ * defence-in-depth measure into an outage. Every function here is therefore
1027
+ * best-effort and reports its outcome instead of throwing, and `doctor` surfaces
1028
+ * that outcome so a machine where hardening silently failed is visible rather
1029
+ * than assumed safe.
1030
+ *
1031
+ * @module dsh-connect-workbuddy/windows-acl
1032
+ */
1033
+ /**
1034
+ * Well-known SID for "the owner of this object".
1035
+ *
1036
+ * Deliberately a SID rather than an account name: it needs no lookup, it works
1037
+ * on every UI language, and `icacls` accepts it in the `*S-…` form.
1038
+ */
1039
+ const OWNER_RIGHTS_SID = "S-1-3-4";
1040
+ /** Well-known SID for `NT AUTHORITY\SYSTEM`. */
1041
+ const SYSTEM_SID = "S-1-5-18";
1042
+ /** Well-known SID for `BUILTIN\Administrators`. */
1043
+ const ADMINISTRATORS_SID = "S-1-5-32-544";
1044
+ /**
1045
+ * Principals allowed to keep access, as SIDs.
1046
+ *
1047
+ * Used by {@link inspectCredentialDirectory} to tell "hardened" from "somebody
1048
+ * widened it again"; keeping the list beside the grant specs is what stops the
1049
+ * two from drifting.
1050
+ */
1051
+ const ALLOWED_SIDS = /* @__PURE__ */ new Set([
1052
+ OWNER_RIGHTS_SID,
1053
+ SYSTEM_SID,
1054
+ ADMINISTRATORS_SID
1055
+ ]);
1056
+ /**
1057
+ * Grant specs for a DIRECTORY: `(OI)` object-inherit and `(CI)` container-inherit
1058
+ * make the ACE apply to files and subdirectories created later, which is the
1059
+ * whole mechanism this module relies on.
1060
+ */
1061
+ const DIRECTORY_GRANTS = [
1062
+ `*${OWNER_RIGHTS_SID}:(OI)(CI)(F)`,
1063
+ `*${SYSTEM_SID}:(OI)(CI)(F)`,
1064
+ `*${ADMINISTRATORS_SID}:(OI)(CI)(F)`
1065
+ ];
1066
+ /** How long one `icacls` (or PowerShell) child may take before it is abandoned. */
1067
+ const ACL_COMMAND_TIMEOUT_MS = 1e4;
1068
+ /** Paths already hardened by THIS process, so repeat writes cost nothing. */
1069
+ const protectedDirectories = /* @__PURE__ */ new Set();
1070
+ /** Hardening attempts in flight, keyed by path: a burst joins one child. */
1071
+ const inflightProtection = /* @__PURE__ */ new Map();
1072
+ /** Whether this process is running on Windows; a seam for tests. */
1073
+ function isWindows() {
1074
+ return process.platform === "win32";
1075
+ }
1076
+ /**
1077
+ * Run one child process, resolving to its stdout.
1078
+ *
1079
+ * `windowsHide` is mandatory for the same reason recorded in `at-rest.ts` and
1080
+ * `docs/WINDOWS.md` §1-5: the DSH Desktop host is an Electron GUI process with
1081
+ * no console, so spawning a console program without it flashes a visible black
1082
+ * window. `icacls` here runs on the credential-write path, which a user can
1083
+ * trigger repeatedly from the card — an un-hidden spawn would blink at them on
1084
+ * every account switch.
1085
+ *
1086
+ * Sets `windowsVerbatimArguments: false` implicitly (the default) so each argv
1087
+ * element is quoted by Node rather than concatenated: the grant specs contain
1088
+ * parentheses, which a raw command-line join would hand to `cmd` for parsing.
1089
+ * This is why the arguments go through `execFile` as an ARRAY and never as a
1090
+ * single shell string.
1091
+ */
1092
+ function runCommand(file, args) {
1093
+ return new Promise((resolve, reject) => {
1094
+ execFile(file, [...args], {
1095
+ encoding: "utf8",
1096
+ windowsHide: true,
1097
+ timeout: ACL_COMMAND_TIMEOUT_MS
1098
+ }, (error, stdout) => {
1099
+ if (error !== null) {
1100
+ reject(/* @__PURE__ */ new Error(`${file} exited ${String(error.code ?? error.message)}`));
1101
+ return;
1102
+ }
1103
+ resolve(stdout);
1104
+ });
1105
+ });
1106
+ }
1107
+ /**
1108
+ * Apply one ownership set to `path` with `icacls`.
1109
+ *
1110
+ * `/inheritance:r` drops the inherited ACEs (that is what removes the
1111
+ * `Everyone: FullControl` arriving from `~/.dsh`) and `/grant:r` replaces the
1112
+ * ACE for each named principal rather than adding a duplicate, so the call is
1113
+ * idempotent — measured: running it twice on the same file leaves the same three
1114
+ * ACEs.
1115
+ */
1116
+ async function applyAcl(path, grants) {
1117
+ const args = [path, "/inheritance:r"];
1118
+ for (const grant of grants) args.push("/grant:r", grant);
1119
+ await runCommand("icacls", args);
1120
+ }
1121
+ /**
1122
+ * Harden one credential directory tree so that the files inside are readable
1123
+ * only by their owner, SYSTEM and Administrators.
1124
+ *
1125
+ * ONE `icacls` CALL, NOT A WALK. Measured on a real Windows 11 host: hardening
1126
+ * the parent directory makes Windows RE-PROPAGATE the new inheritable ACEs down
1127
+ * the tree, repairing existing subdirectories AND existing files in the same
1128
+ * step — a file carrying `Everyone: FullControl` inherited from `~/.dsh` came out
1129
+ * with exactly the three intended ACEs (`weak=0`) after only its parent was
1130
+ * hardened. Walking the children would spawn one child process per directory to
1131
+ * re-derive a guarantee this single call already delivers.
1132
+ *
1133
+ * WHY THAT COST MATTERS HERE. This runs on the credential-write path, which the
1134
+ * card can trigger per account switch. `icacls` measured 19–52 ms at rest and
1135
+ * **up to 1242 ms under parallel load** — enough to blow the 1 s polling budget
1136
+ * of `tests/issue12-region-hiding.spec.ts` when the whole suite ran
1137
+ * concurrently. The shape below is therefore deliberate on two axes:
1138
+ *
1139
+ * - CALLS: one, never a walk.
1140
+ * - CONCURRENCY: an attempt already in flight for the same path is JOINED
1141
+ * rather than repeated, so a burst of writes queues one child for one
1142
+ * directory instead of one per write.
1143
+ *
1144
+ * Staying ON the write path is not negotiable: the atomic commit creates a fresh
1145
+ * temp inode and renames it over the target, so a file-level pass AFTERwards
1146
+ * would leave the pre-rename window open and would be undone by the next
1147
+ * replace. Hardening before the write is what makes the replacement inode
1148
+ * inherit the restricted ACEs.
1149
+ *
1150
+ * Memoized per process on SUCCESS only: a failed attempt must be retried by the
1151
+ * next write, or one transient lock on the directory would leave the machine
1152
+ * unhardened for the rest of the session.
1153
+ */
1154
+ async function protectCredentialDirectory(directory) {
1155
+ if (!isWindows()) return { state: "not-windows" };
1156
+ if (protectedDirectories.has(directory)) return { state: "protected" };
1157
+ const pending = inflightProtection.get(directory);
1158
+ if (pending !== void 0) return pending;
1159
+ const attempt = hardenDirectory(directory);
1160
+ inflightProtection.set(directory, attempt);
1161
+ try {
1162
+ return await attempt;
1163
+ } finally {
1164
+ inflightProtection.delete(directory);
1165
+ }
1166
+ }
1167
+ /** The work behind {@link protectCredentialDirectory}: one `icacls` call. */
1168
+ async function hardenDirectory(directory) {
1169
+ try {
1170
+ await mkdir(directory, { recursive: true });
1171
+ await applyAcl(directory, DIRECTORY_GRANTS);
1172
+ protectedDirectories.add(directory);
1173
+ return { state: "protected" };
1174
+ } catch (error) {
1175
+ return {
1176
+ state: "failed",
1177
+ reason: error instanceof Error ? error.message : String(error)
1178
+ };
1179
+ }
1180
+ }
1181
+ /**
1182
+ * Read back the ACL of one credential directory as SIDs, for diagnostics.
1183
+ *
1184
+ * PowerShell rather than `icacls` because the answer has to be COMPARABLE:
1185
+ * `icacls` prints localized account names, so testing "is `Everyone` absent"
1186
+ * against its output would silently pass on a zh-CN host where the name is
1187
+ * spelled differently. `Get-Acl` + `SecurityIdentifier.Value` yields the
1188
+ * language-independent form.
1189
+ *
1190
+ * Read-only and token-free: it never opens the JSON, only the ACL. A failure to
1191
+ * read is reported as `unverified` rather than being folded into `exposed` — the
1192
+ * two need different user actions, and claiming exposure that was not measured
1193
+ * would be its own kind of lie.
1194
+ */
1195
+ async function inspectCredentialDirectory(directory) {
1196
+ if (!isWindows()) return {
1197
+ directory,
1198
+ state: "not-windows"
1199
+ };
1200
+ /**
1201
+ * Deliberately a single quoted expression with no interpolation of `directory`
1202
+ * beyond the literal path: `-LiteralPath` keeps a path containing `[` or `$`
1203
+ * from being treated as a wildcard or a subexpression.
1204
+ */
1205
+ const script = [`$a = Get-Acl -LiteralPath '${directory.replace(/'/gu, "''")}'`, "$a.Access | ForEach-Object { $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value }"].join("; ");
1206
+ let stdout;
1207
+ try {
1208
+ stdout = await runCommand("powershell", [
1209
+ "-NoProfile",
1210
+ "-NonInteractive",
1211
+ "-Command",
1212
+ script
1213
+ ]);
1214
+ } catch (error) {
1215
+ return {
1216
+ directory,
1217
+ state: "unverified",
1218
+ reason: error instanceof Error ? error.message : String(error)
1219
+ };
1220
+ }
1221
+ const entries = stdout.split(/\r?\n/u).map((line) => line.trim()).filter((line) => line !== "" && /^S-1-/u.test(line));
1222
+ if (entries.length === 0) return {
1223
+ directory,
1224
+ state: "unverified",
1225
+ reason: "Get-Acl returned no principals"
1226
+ };
1227
+ const weak = entries.filter((sid) => !ALLOWED_SIDS.has(sid));
1228
+ return {
1229
+ directory,
1230
+ state: weak.length === 0 ? "protected" : "exposed",
1231
+ entries,
1232
+ weak
1233
+ };
1234
+ }
1235
+ /**
1236
+ * 命名空间,且带版本号。
1237
+ *
1238
+ * 不带命名空间,本插件的派生值就可能与另一个工具的派生值在同一个 uid 上撞成
1239
+ * 同值;不带版本号,将来改一次输入格式就会让所有账号**静默换设备**——那正是
1240
+ * 风控最想抓的 device hopping。要改格式,就改这里的 `v1`,并接受"这是一次
1241
+ * 有意的身份变更",而不是让它悄悄发生。
1242
+ */
1243
+ const DEVICE_ID_NAMESPACE = "dsh-connect-workbuddy/device/v1";
1244
+ /** 36 个**小写**十六进制字符,别的一律不认。 */
1245
+ const DEVICE_ID_PATTERN = /^[0-9a-f]{36}$/u;
1246
+ /** 64 个**小写**十六进制字符。 */
1247
+ const DEVICE_SALT_PATTERN = /^[0-9a-f]{64}$/u;
1248
+ /**
1249
+ * Derive one stable, account-scoped device identifier.
1250
+ *
1251
+ * `uid` 为空串时返回空串:匿名请求没有"这台设备属于哪个账号"可言,上游也不要求
1252
+ * (B 的同名实现在 uid 为空时同样不注入)。返回空串而不是抛错,是因为调用方
1253
+ * 只需要"发还是不发",而"没有 uid"是正常状态,不是异常。
1254
+ *
1255
+ * @param uid the account's stable id, as the desktop auth document records it
1256
+ * @param purpose which header this value is for — never reuse one for the other
1257
+ * @param salt this machine's random salt (see `device-salt.ts`); a constant here
1258
+ * would make every install of this plugin derive identical ids
1259
+ */
1260
+ function deriveDeviceId(uid, purpose, salt) {
1261
+ if (uid === "" || salt === "") return "";
1262
+ return createHash("sha256").update(`${DEVICE_ID_NAMESPACE}\0${salt}\0${purpose}\0${uid}`, "utf8").digest("hex").slice(0, 36);
1263
+ }
1264
+ /** Whether `value` is exactly a derived device id (36 lowercase hex). */
1265
+ function isDeviceId(value) {
1266
+ return DEVICE_ID_PATTERN.test(value);
1267
+ }
1268
+ /** Whether `value` is exactly a device salt (64 lowercase hex). */
1269
+ function isDeviceSalt(value) {
1270
+ return DEVICE_SALT_PATTERN.test(value);
1271
+ }
1272
+ /** 文件名,带前导点,与 `.workbuddy-roster-seen.*.json` 同一约定。 */
1273
+ const DEVICE_SALT_FILE_NAME = ".workbuddy-device.json";
1274
+ /** `$DSH_HOME/.workbuddy-device.json`, or `dir` when one is pinned (tests). */
1275
+ function deviceSaltPath(dir) {
1276
+ const base = typeof dir === "string" && dir !== "" ? dir : resolveDshHome();
1277
+ return join(base, DEVICE_SALT_FILE_NAME);
1278
+ }
1279
+ /**
1280
+ * Read one parsed salt document.
1281
+ *
1282
+ * `undefined` means the file is not there at all — the ONLY state that permits
1283
+ * writing a new one. Everything else that is wrong with the file lands in
1284
+ * `reason`, because "we cannot read our own salt" must stay distinguishable from
1285
+ * "there is no salt yet".
1286
+ */
1287
+ function parseDeviceSaltPayload(raw) {
1288
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return { reason: "not a JSON object" };
1289
+ const document = raw;
1290
+ const version = document["version"];
1291
+ if (version !== 1) return { reason: `version ${typeof version === "number" ? version : "(absent)"} is not readable by this build` };
1292
+ const salt = document["salt"];
1293
+ if (typeof salt !== "string" || !isDeviceSalt(salt)) return { reason: "salt field is not 64 lowercase hex characters" };
1294
+ return { salt };
1295
+ }
1296
+ /**
1297
+ * Read the salt WITHOUT writing anything.
1298
+ *
1299
+ * A missing file is `absent`; an unreadable one is `unreadable` (never
1300
+ * `absent`) — see the module note on why that distinction is load-bearing.
1301
+ */
1302
+ async function readDeviceSalt(options = {}) {
1303
+ const path = deviceSaltPath(options.dir);
1304
+ let text;
1305
+ try {
1306
+ text = await readFile(path, "utf8");
1307
+ } catch (error) {
1308
+ const code = error?.code;
1309
+ if (code === "ENOENT") return {
1310
+ path,
1311
+ state: "absent"
1312
+ };
1313
+ return {
1314
+ path,
1315
+ state: "unreadable",
1316
+ reason: code === void 0 ? String(error) : code
1317
+ };
1318
+ }
1319
+ let raw;
1320
+ try {
1321
+ raw = JSON.parse(text);
1322
+ } catch {
1323
+ return {
1324
+ path,
1325
+ state: "unreadable",
1326
+ reason: "file is not valid JSON"
1327
+ };
1328
+ }
1329
+ const parsed = parseDeviceSaltPayload(raw);
1330
+ if ("reason" in parsed) return {
1331
+ path,
1332
+ state: "unreadable",
1333
+ reason: parsed.reason
1334
+ };
1335
+ return {
1336
+ path,
1337
+ state: "ok",
1338
+ salt: parsed.salt
1339
+ };
1340
+ }
1341
+ /**
1342
+ * Read the salt, creating it on the first call that needs one.
1343
+ *
1344
+ * The read happens twice — once unlocked (the common case costs one `readFile`),
1345
+ * once inside the lock before writing — because two processes starting together
1346
+ * would otherwise both find the file missing and both write a different salt;
1347
+ * the loser's salt would then never be used again and its ids would silently
1348
+ * change. Writing asks for `mode: 0o600` under a `0o700` directory: the value is
1349
+ * not a credential, but it IS what makes this machine's derived ids unguessable.
1350
+ * On Windows those bits are a no-op and the DACL decides — this file lives in
1351
+ * `$DSH_HOME`, whose permissions `doctor` already hardens for the vault
1352
+ * (`credentialAcl` in `src/bin.ts`).
1353
+ */
1354
+ async function ensureDeviceSalt(options = {}) {
1355
+ const first = await readDeviceSalt(options);
1356
+ if (first.state !== "absent") return first;
1357
+ const path = first.path;
1358
+ try {
1359
+ return await withFileLock(path, async () => {
1360
+ const again = await readDeviceSalt(options);
1361
+ if (again.state !== "absent") return again;
1362
+ const salt = randomBytes(32).toString("hex");
1363
+ await writeFileAtomic(path, `${JSON.stringify({
1364
+ version: 1,
1365
+ salt,
1366
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1367
+ }, null, 2)}\n`, {
1368
+ mode: 384,
1369
+ dirMode: 448
1370
+ });
1371
+ return {
1372
+ path,
1373
+ state: "ok",
1374
+ salt
1375
+ };
1376
+ });
1377
+ } catch (error) {
1378
+ const code = error?.code;
1379
+ return {
1380
+ path,
1381
+ state: "unwritable",
1382
+ reason: code === void 0 ? String(error) : code
1383
+ };
1384
+ }
1385
+ }
1386
+ //#endregion
1387
+ //#region src/device-token.ts
1388
+ /**
1389
+ * 外部 `X-Device-Token` 的文件源(审计报告 §6 的 P2)。
1390
+ *
1391
+ * ## 为什么只有文件,没有"内联配置值"
1392
+ *
1393
+ * token 的有效期是分钟级(A 实测 10 分钟,旧值最多 24 小时可复用)。写在配置里
1394
+ * 的值是死的:十分钟后它过期,只能靠人去改配置——那是一条每十分钟需要人工介入的
1395
+ * 路径,实际上只在一次性排障里成立。文件可以由任何东西刷新(A 自己的
1396
+ * `.turing_token_cache.json`、一个 cron、一个脚本),插件按 TTL 重读即可。
1397
+ *
1398
+ * ## 它与 B 的 `device_token.go` 差在哪(三处,都是刻意的)
1399
+ *
1400
+ * 1. **上限 4 KB,不是 1 KB**。A 现取的 token 实测 **1210 字符**(`v3:` 前缀、
1401
+ * 单段不透明 blob),B 的 1024 字节上限会把它判成"过长"→ 返回空 →
1402
+ * **静默不注入**。token 明明有,网关那边却当作没有。
1403
+ * 2. **JSON 信封与裸值都吃**。A 写的是 `{"token":"v3:…","ts":…}`,B 只认
1404
+ * 裸值——直接把 B 指到 A 的缓存上,注入的会是整段 JSON。
1405
+ * 3. **失败会记一条 warn**。B 是完全静默的,"配了但没生效"因此无法从任何地方
1406
+ * 看出来。这里只在**状态发生变化**时告警一次,避免每条请求刷一行。
1407
+ *
1408
+ * ## 安全
1409
+ *
1410
+ * token 是设备身份,不是访问凭据,但它同样不该进日志:本模块的任何输出
1411
+ * (包括错误、warn、doctor)都只带**路径、状态、时长**,绝不含 token 字节。
1412
+ *
1413
+ * @module dsh-connect-workbuddy/device-token
1414
+ */
1415
+ /**
1416
+ * 文件大小上限,单位字节。
1417
+ *
1418
+ * 4 KB 不是随手放的:A 的真实 token 是 1210 字符,B 的 1 KB 上限会误杀它;同时
1419
+ * 4 KB 仍然远小于"贴错文件"的量级(把整个 auth.json 指过来会立刻被判过长)。
1420
+ */
1421
+ const DEVICE_TOKEN_MAX_BYTES = 4096;
1422
+ /** 默认重读周期。与 A 的磁盘缓存一致(10 分钟 token / 5 分钟重读)。 */
1423
+ const DEVICE_TOKEN_DEFAULT_TTL_MS = 3e5;
1424
+ /**
1425
+ * 设备 token 文件路径的环境变量。
1426
+ *
1427
+ * **它不是第二个真源**,而是同一个值的第二种写法:插件配置 `deviceToken.file`
1428
+ * 为空时才回落到它,而 `doctor` 只能看到环境变量(它读不到插件配置)。同一个
1429
+ * 值、两个读者,因此不会出现"插件在用 A、CLI 报告 B"。
1430
+ */
1431
+ const WORKBUDDY_DEVICE_TOKEN_FILE_ENV = "WORKBUDDY_DEVICE_TOKEN_FILE";
1432
+ /**
1433
+ * Expand a configured path.
1434
+ *
1435
+ * `~` is supported because that is how the one interesting path (`A` 的
1436
+ * `.turing_token_cache.json`) is naturally written; everything else resolves
1437
+ * against the process cwd, which is why the docs ask for an absolute path.
1438
+ */
1439
+ function resolveDeviceTokenPath(file) {
1440
+ const trimmed = file.trim();
1441
+ if (trimmed === "~") return homedir();
1442
+ if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) return join(homedir(), trimmed.slice(2));
1443
+ return resolve(trimmed);
1444
+ }
1445
+ /**
1446
+ * Parse the file body: either a bare token or A's `{token, ts}` envelope.
1447
+ *
1448
+ * The envelope is not a nicety — pointing this reader at A's cache file is the
1449
+ * whole reason a user of both tools gets a working token with no extra script.
1450
+ */
1451
+ function parseDeviceTokenDocument(text) {
1452
+ const trimmed = text.trim();
1453
+ if (trimmed === "") return { reason: "file is empty" };
1454
+ if (trimmed.startsWith("{")) {
1455
+ let document;
1456
+ try {
1457
+ document = JSON.parse(trimmed);
1458
+ } catch {
1459
+ return { reason: "file starts with { but is not valid JSON" };
1460
+ }
1461
+ if (typeof document !== "object" || document === null || Array.isArray(document)) return { reason: "JSON document is not an object" };
1462
+ const token = document["token"];
1463
+ if (typeof token !== "string" || token.trim() === "") return { reason: "JSON envelope has no non-empty token field" };
1464
+ return { token: token.trim() };
1465
+ }
1466
+ if (/\s/u.test(trimmed)) return { reason: "raw token must be a single line without whitespace" };
1467
+ return { token: trimmed };
1468
+ }
1469
+ /** Read the token file once. No caching — see {@link createDeviceTokenReader}. */
1470
+ async function readDeviceTokenFile(file, nowMs = Date.now()) {
1471
+ const path = resolveDeviceTokenPath(file);
1472
+ let size;
1473
+ let modifiedMs;
1474
+ try {
1475
+ const info = await stat(path);
1476
+ if (!info.isFile()) return {
1477
+ path,
1478
+ state: "unreadable",
1479
+ reason: "path is not a regular file"
1480
+ };
1481
+ size = info.size;
1482
+ modifiedMs = info.mtimeMs;
1483
+ } catch (error) {
1484
+ const code = error?.code;
1485
+ if (code === "ENOENT") return {
1486
+ path,
1487
+ state: "absent"
1488
+ };
1489
+ return {
1490
+ path,
1491
+ state: "unreadable",
1492
+ reason: code === void 0 ? String(error) : code
1493
+ };
1494
+ }
1495
+ if (size > 4096) return {
1496
+ path,
1497
+ state: "too-large",
1498
+ reason: `${size} bytes exceeds the ${DEVICE_TOKEN_MAX_BYTES}-byte limit`
1499
+ };
1500
+ let text;
1501
+ try {
1502
+ text = await readFile(path, "utf8");
1503
+ } catch (error) {
1504
+ const code = error?.code;
1505
+ return {
1506
+ path,
1507
+ state: "unreadable",
1508
+ reason: code === void 0 ? String(error) : code
1509
+ };
1510
+ }
1511
+ const parsed = parseDeviceTokenDocument(text);
1512
+ if ("reason" in parsed) return {
1513
+ path,
1514
+ state: "unreadable",
1515
+ reason: parsed.reason
1516
+ };
1517
+ return {
1518
+ path,
1519
+ state: "ok",
1520
+ token: parsed.token,
1521
+ ageMs: Math.max(0, nowMs - modifiedMs)
1522
+ };
1523
+ }
1524
+ /**
1525
+ * Build the reader.
1526
+ *
1527
+ * `warn` fires **only when the state changes** — a missing file would otherwise
1528
+ * write one line per request, which is the noise that trains people to ignore
1529
+ * logs. Recovery resets the memory, so a later break is reported again.
1530
+ */
1531
+ function createDeviceTokenReader(options) {
1532
+ const ttlMs = options.ttlMs !== void 0 && Number.isFinite(options.ttlMs) && options.ttlMs > 0 ? options.ttlMs : DEVICE_TOKEN_DEFAULT_TTL_MS;
1533
+ let cached;
1534
+ let lastBadState;
1535
+ return {
1536
+ async current(nowMs = Date.now()) {
1537
+ if (cached !== void 0 && nowMs - cached.at < ttlMs) return cached.readout.token;
1538
+ const readout = await readDeviceTokenFile(options.file, nowMs);
1539
+ cached = {
1540
+ at: nowMs,
1541
+ readout
1542
+ };
1543
+ if (readout.state === "ok") {
1544
+ lastBadState = void 0;
1545
+ return readout.token;
1546
+ }
1547
+ if (readout.state !== lastBadState) {
1548
+ lastBadState = readout.state;
1549
+ options.warn?.(`device token file is ${readout.state}${readout.reason === void 0 ? "" : ` (${readout.reason})`}; X-Device-Token will not be sent. Path: ${readout.path}`);
1550
+ }
1551
+ },
1552
+ last() {
1553
+ return cached?.readout;
1554
+ }
1555
+ };
1556
+ }
1557
+ //#endregion
965
1558
  //#region src/native-modality.ts
966
1559
  /**
967
1560
  * Reviewed vendor classifications, keyed by EXACT model id (never a prefix).
@@ -2408,6 +3001,11 @@ const ERROR_BODY_LIMIT = 4096;
2408
3001
  * with nothing in the UI to say which one it was. Ten seconds is comfortably
2409
3002
  * above a working gateway's first byte and far below a user's patience; the
2410
3003
  * budget covers the response only, never the one-line body that follows.
3004
+ *
3005
+ * It also does not cover THIS MACHINE's identity work. Since P3 the header build
3006
+ * may spawn the device-token subprocess (budget 20 s), and starting the clock
3007
+ * before that would turn a healthy gateway into "unreachable" on a cold start —
3008
+ * see the note in `probeChat` for why that matters to the pool.
2411
3009
  */
2412
3010
  const PROBE_TIMEOUT_MS = 1e4;
2413
3011
  /**
@@ -3161,8 +3759,16 @@ function billingBase(credential) {
3161
3759
  function originReferer(credential) {
3162
3760
  return regionOf(credential.domain) === "global" ? globalBase(credential.domain) : CN_BILLING_BASE;
3163
3761
  }
3164
- /** Headers every upstream request shares. */
3165
- function commonHeaders(credential) {
3762
+ /**
3763
+ * 5.16.0 的公共头,**不含 P1 增补**。
3764
+ *
3765
+ * 只给 {@link refreshHeaders} 用,而且是有意的:refresh 是整条链路里唯一
3766
+ * "失败就等于掉登录"的一跳,它的字节不该因为一次身份统一而变化。B 的
3767
+ * `RefreshHeaders` 确实也走 `CommonHeaders`(因此带 `X-CodeBuddy-Request`),
3768
+ * 但那是 B 一直在跑的形状;本插件没有在 refresh 上验过任何新头,
3769
+ * "别人这么发" 不等于 "我们可以这么改"。
3770
+ */
3771
+ function legacyCommonHeaders(credential) {
3166
3772
  return {
3167
3773
  "Accept": "application/json, text/plain, */*",
3168
3774
  "X-Requested-With": "XMLHttpRequest",
@@ -3172,6 +3778,20 @@ function commonHeaders(credential) {
3172
3778
  };
3173
3779
  }
3174
3780
  /**
3781
+ * 客户端调用(chat 家族)的公共头 = {@link legacyCommonHeaders} + P1 增补。
3782
+ *
3783
+ * 目前只有 chat 一条路径用它(`chatStream` 与 `probeChat`,两者是同一个合同)。
3784
+ * 元数据读与维护跳走 `legacyCommonHeaders`,见那条注释里的边界说明。
3785
+ */
3786
+ function commonHeaders(credential, identity = {}) {
3787
+ const headers = legacyCommonHeaders(credential);
3788
+ if (profileOf(identity) === "balanced") {
3789
+ headers["X-CodeBuddy-Request"] = "1";
3790
+ headers["Accept-Language"] = acceptLanguageOf(credential);
3791
+ }
3792
+ return headers;
3793
+ }
3794
+ /**
3175
3795
  * The conversation-identity triple the chat endpoint now requires (issue #66).
3176
3796
  *
3177
3797
  * WHY THIS EXISTS. The international gateway added a second gate on top of the
@@ -3222,9 +3842,11 @@ function conversationHeaders(shape, identity = {}) {
3222
3842
  const officialIds = shape === "chat" && identity.usageIdentity === true;
3223
3843
  const id = officialIds ? uuidv7 : randomUUID;
3224
3844
  const messageId = id();
3845
+ const conversationRequestId = id();
3225
3846
  return {
3226
3847
  "X-Conversation-ID": id(),
3227
- "X-Conversation-Request-ID": id(),
3848
+ "X-Conversation-Request-ID": conversationRequestId,
3849
+ ...profileOf(identity) === "balanced" ? { "X-Root-Request-ID": conversationRequestId } : {},
3228
3850
  "X-Conversation-Message-ID": messageId,
3229
3851
  ...officialIds ? { "X-Request-ID": messageId } : {}
3230
3852
  };
@@ -3256,70 +3878,185 @@ function uuidv7(nowMs = Date.now()) {
3256
3878
  return bytes.toString("hex");
3257
3879
  }
3258
3880
  /**
3259
- * The IDE identity headers the official desktop client sends on chat (issue #132).
3881
+ * 没有显式配置时用的档位。
3260
3882
  *
3261
- * WHY. The gateway records the usage page's 使用端 (client) column from
3262
- * `X-IDE-Name`, and it is EMPTY when the header is absent. The plugin has always
3263
- * spoken the CLI channel — {@link CLIENT_UA}, which is correct for the chat
3264
- * contract — but it sent no `X-IDE-*` at all, so every request this plugin made
3265
- * appeared on the user's own usage page as an unidentified client while the
3266
- * official app's requests read `WorkBuddy`. That is a reporting mismatch, not a
3267
- * gate: the reporter measured that adding the header changes the usage column
3268
- * and nothing else (HTTP 200, model unaffected).
3883
+ * `balanced`:P0.5 已证实有效,默认就应该吃到收益;`conservative` 留给
3884
+ * "某台机器上某个账号忽然不行了"的排查场景。
3885
+ */
3886
+ const DEFAULT_WIRE_PROFILE = "balanced";
3887
+ /** 生效档位;未配置时取默认。 */
3888
+ function profileOf(identity) {
3889
+ return identity.profile ?? "balanced";
3890
+ }
3891
+ /**
3892
+ * 归属头的产品名。
3893
+ *
3894
+ * `WorkBuddy` 而不是 `SaaS`:`SaaS` 是"某种 SaaS 租户"的泛化标签,官方客户端
3895
+ * 从不会这么称呼自己;A(`client_name` 默认 `WorkBuddy`)与 B
3896
+ * (`attributionClientName` 默认 `WorkBuddy`)都发 `WorkBuddy`,而 B 的注释直接
3897
+ * 把 `SaaS` 称作"还原旧行为"。同值三头(Name / Type / Product)也是两家的共同
3898
+ * 形状——官方客户端不会一边说自己是 WorkBuddy、一边说自己是 CLI。
3899
+ */
3900
+ const ATTRIBUTION_CLIENT_NAME = "WorkBuddy";
3901
+ /**
3902
+ * `Accept-Language`:按账号域切。
3903
+ *
3904
+ * 官方客户端按账号所属区发对应语言(B 的 D5:CN `zh-CN` / global `en-US`)。
3905
+ * 一个中文账号发 `en-US` 是"这台机器换了语言",而语言是设备指纹里最廉价、
3906
+ * 也最常被用来做聚类的一维——顺手对齐没有成本。
3907
+ */
3908
+ function acceptLanguageOf(credential) {
3909
+ return regionOf(credential.domain) === "global" ? "en-US" : "zh-CN";
3910
+ }
3911
+ /**
3912
+ * 归属头:这台客户端"是谁",一次说清(P1 的"统一为 WorkBuddy 客户端")。
3913
+ *
3914
+ * ## 为什么是从 `ideHeaders` 扩成函数族
3915
+ *
3916
+ * 5.16.0 发的是 `X-Product: SaaS` + 可选的 `X-IDE-Type: CLI` / `X-IDE-Name:
3917
+ * WorkBuddy`,而且三个头分两处、其中两个还被 `usageIdentity` 挡着。结果是同一条
3918
+ * 请求里"产品"说自己是泛化 SaaS、"类型"说自己是 CLI、"名字"说自己是 WorkBuddy —
3919
+ * 三个互不相同的自称。A 与 B 都不是这么做的:两家都是 Name / Type / Product
3920
+ * **同值**,且都发 `X-Agent-Purpose: conversation`。
3921
+ *
3922
+ * ## `conservative` 为什么还原的是 `SaaS` 而不是"少发几个"
3923
+ *
3924
+ * 回退档的契约是"逐字节等于 5.16.0"。只删新头、留下改名后的 `X-Product`,等于
3925
+ * 造出第三个从未上线过的形状——排查时最怕的就是"回退了但没完全回退"。
3269
3926
  *
3270
- * `X-IDE-Type` stays `CLI` on purpose. Claiming the desktop app's type as well
3271
- * would be a bigger identity claim than the one this fix needs, and the mixed
3272
- * CLI + WorkBuddy shape is what the reporter measured. The version comes from
3273
- * {@link PRODUCT_UA} rather than a second hardcoded number, so the two cannot
3274
- * drift apart when the app version is bumped.
3927
+ * 版本号取 {@link APP_VERSION}(从 {@link PRODUCT_UA} 解析出来),不写字面量:
3928
+ * 两个独立字面量正是版本升级时开始互相矛盾的方式。
3929
+ */
3930
+ function attributionHeaders(identity) {
3931
+ if (profileOf(identity) !== "balanced") return { "X-Product": "SaaS" };
3932
+ return {
3933
+ "X-Agent-Purpose": "conversation",
3934
+ "X-IDE-Name": ATTRIBUTION_CLIENT_NAME,
3935
+ "X-IDE-Type": ATTRIBUTION_CLIENT_NAME,
3936
+ "X-IDE-Version": APP_VERSION,
3937
+ "X-Product": ATTRIBUTION_CLIENT_NAME
3938
+ };
3939
+ }
3940
+ /**
3941
+ * 设备头:真实值档只发真 token;虚拟值档发派生的 id 对(+ P2 的文件 token,若有)。
3942
+ *
3943
+ * 盐来自本机 `$DSH_HOME/.workbuddy-device.json`(见 `src/device-salt.ts`),由
3944
+ * 客户端解析一次后放进 identity;**盐缺席就整对不发**——只发 Machine-ID 不发
3945
+ * Session-ID 是一个真实客户端不会出现的形状。token 来自
3946
+ * `deviceToken.file`(见 `src/device-token.ts`),每 5 分钟重读。
3947
+ *
3948
+ * ## 两档互斥,且互斥在**代码**里
3949
+ *
3950
+ * 真 token 内含设备信息(A 调 `fetchDeviceToken({includesDeviceInfo:true})`),
3951
+ * 再配一对伪造 id 等于自证不一致(审计 §5.3)。P2 把这个组合先放上线是为了让
3952
+ * 档位规则由实测决定;P3 的决定是:真实值档只发 token,派生对整对不发。这里不是
3953
+ * "少发几个头",是两条互斥的返回路径——同时带着两者发出去的那条路已经不存在了,
3954
+ * 也就没有配置能配出矛盾组合。
3955
+ */
3956
+ function deviceHeaders(credential, identity) {
3957
+ if (profileOf(identity) !== "balanced") return {};
3958
+ if (identity.deviceTier === "real") return identity.deviceReal === void 0 || identity.deviceReal === "" ? {} : { "X-Device-Token": identity.deviceReal };
3959
+ const headers = {};
3960
+ if (identity.deviceToken !== void 0 && identity.deviceToken !== "") headers["X-Device-Token"] = identity.deviceToken;
3961
+ const salt = identity.deviceSalt;
3962
+ const override = identity.deviceProfile;
3963
+ const derivedMachine = salt !== void 0 && salt !== "" && credential.uid !== "" ? deriveDeviceId(credential.uid, "machine", salt) : "";
3964
+ const derivedSession = salt !== void 0 && salt !== "" && credential.uid !== "" ? deriveDeviceId(credential.uid, "session", salt) : "";
3965
+ const machineId = override?.machineId !== void 0 && override.machineId !== "" ? override.machineId : derivedMachine;
3966
+ const sessionId = override?.sessionId !== void 0 && override.sessionId !== "" ? override.sessionId : derivedSession;
3967
+ if (machineId !== "") headers["X-Machine-ID"] = machineId;
3968
+ if (sessionId !== "") headers["X-Session-ID"] = sessionId;
3969
+ return headers;
3970
+ }
3971
+ /**
3972
+ * 把 identity 补全成"可以直接拿去构造头"的形态——解析本机设备盐。
3275
3973
  *
3276
- * Sent only when {@link WorkBuddyWireIdentity.usageIdentity} is on — see that
3277
- * field for the evidence tier behind the default.
3974
+ * 三条提前返回,各有理由:
3975
+ * - 非 `balanced`:这一档根本不发设备头,去读盘只是浪费一次 IO;
3976
+ * - 调用方已经给了盐(测试、或 doctor 已经解析过):不复读;
3977
+ * - 读不到(absent / unreadable / unwritable):原样返回,`deviceHeaders`
3978
+ * 会因为 `deviceSalt === undefined` 整对不发。**绝不现场造一个临时盐**。
3278
3979
  */
3279
- function ideHeaders(identity) {
3280
- if (identity.usageIdentity !== true) return {};
3980
+ async function resolveWireIdentity(identity) {
3981
+ if (profileOf(identity) !== "balanced") return identity;
3982
+ if (identity.deviceSalt !== void 0 && identity.deviceSalt !== "") return identity;
3983
+ const readout = await ensureDeviceSalt();
3984
+ if (readout.state !== "ok") return identity;
3281
3985
  return {
3282
- "X-IDE-Type": "CLI",
3283
- "X-IDE-Name": "WorkBuddy",
3284
- "X-IDE-Version": APP_VERSION
3986
+ ...identity,
3987
+ deviceSalt: readout.salt
3285
3988
  };
3286
3989
  }
3287
3990
  /** Chat request headers, including the X-No-* conventions the official CLI uses. */
3288
3991
  function chatHeaders(credential, identity = {}) {
3289
3992
  return {
3290
- ...commonHeaders(credential),
3993
+ ...commonHeaders(credential, identity),
3291
3994
  "Content-Type": "application/json",
3292
3995
  ...credential.uid === "" ? { "X-No-User-Id": "1" } : { "X-User-Id": credential.uid },
3293
3996
  ...credential.enterpriseId === void 0 || credential.enterpriseId === "" ? { "X-No-Enterprise-Id": "1" } : { "X-Enterprise-Id": credential.enterpriseId },
3294
3997
  ...credential.domain === "" ? { "X-No-Department-Info": "1" } : { "X-Domain": credential.domain },
3295
- "X-Product": "SaaS",
3296
- ...ideHeaders(identity),
3998
+ ...attributionHeaders(identity),
3999
+ ...deviceHeaders(credential, identity),
3297
4000
  ...conversationHeaders("chat", identity)
3298
4001
  };
3299
4002
  }
3300
- /** Refresh-endpoint headers; X-Refresh-Token appears here and nowhere else. */
4003
+ /**
4004
+ * Refresh-endpoint headers; X-Refresh-Token appears here and nowhere else.
4005
+ *
4006
+ * **签名里刻意没有 `identity`**:这条路径不参与 P1 的身份统一,多一个用不到的
4007
+ * 参数只会让下一个人以为它本该用上。见 {@link legacyCommonHeaders}。
4008
+ */
3301
4009
  function refreshHeaders(credential) {
3302
4010
  const headers = {
3303
- ...commonHeaders(credential),
4011
+ ...legacyCommonHeaders(credential),
3304
4012
  "X-Refresh-Token": credential.refreshToken,
3305
4013
  "X-Auth-Refresh-Source": "workbuddy"
3306
4014
  };
3307
4015
  if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") headers["X-Enterprise-Id"] = credential.enterpriseId;
3308
4016
  return headers;
3309
4017
  }
3310
- /** Billing request headers. */
3311
- function billingHeaders(credential) {
4018
+ /**
4019
+ * Billing request headers.
4020
+ *
4021
+ * ## 为什么这条路径要补这么多(审计 §1.3 的 D2)
4022
+ *
4023
+ * 5.16.0 的 billing 只发三件套 + 用户/企业/域,**没有 UA、没有 Origin/Referer、
4024
+ * 没有 X-Requested-With、没有任何归属头**。于是同一个 token 在同一分钟里发出
4025
+ * 两种客户端:chat 声称自己是 CLI,billing 声称自己是一个连 UA 都没有的裸 HTTP
4026
+ * 客户端。这种"两条路径互不承认"的反差不需要任何启发式就能被静态规则挑出来,
4027
+ * 而 billing 恰好是签到、领补偿这类**写操作**所在的域——最不该显得可疑的地方。
4028
+ *
4029
+ * 补齐的四类,每一类都有参照实现:
4030
+ * - `User-Agent: WorkBuddy/<ver>`:B 的 billing 域用单段形态(官方 banner
4031
+ * 白名单头组不带 CLI 段),A 则对所有路径复用同一套头。
4032
+ * - `Origin` / `Referer` / `X-Requested-With`:B 的 `CommonHeaders` 全路径发送。
4033
+ * - `X-CodeBuddy-Request` + `Accept-Language`:B 在 billing 域单独注入(D1/D5)。
4034
+ * - 归属头与设备头:与本插件的 chat 路径同源,保证"同一个客户端"这个说法成立。
4035
+ *
4036
+ * `conservative` 档整段跳过,billing 逐字节还原 5.16.0 的裸形状。
4037
+ */
4038
+ function billingHeaders(credential, identity = {}) {
4039
+ const balanced = profileOf(identity) === "balanced";
3312
4040
  const headers = {
3313
4041
  "Authorization": `Bearer ${credential.accessToken}`,
3314
4042
  "Accept": "application/json",
3315
4043
  "Content-Type": "application/json"
3316
4044
  };
4045
+ if (balanced) {
4046
+ headers["User-Agent"] = `WorkBuddy/${APP_VERSION}`;
4047
+ headers["X-Requested-With"] = "XMLHttpRequest";
4048
+ headers["X-CodeBuddy-Request"] = "1";
4049
+ headers["Accept-Language"] = acceptLanguageOf(credential);
4050
+ headers["Origin"] = originReferer(credential);
4051
+ headers["Referer"] = `${originReferer(credential)}/`;
4052
+ }
3317
4053
  if (credential.uid !== "") headers["X-User-Id"] = credential.uid;
3318
4054
  if (credential.enterpriseId !== void 0 && credential.enterpriseId !== "") {
3319
4055
  headers["X-Enterprise-Id"] = credential.enterpriseId;
3320
4056
  headers["X-Tenant-Id"] = credential.enterpriseId;
3321
4057
  }
3322
4058
  if (credential.domain !== "") headers["X-Domain"] = credential.domain;
4059
+ if (balanced) Object.assign(headers, attributionHeaders(identity), deviceHeaders(credential, identity));
3323
4060
  return headers;
3324
4061
  }
3325
4062
  /**
@@ -3330,6 +4067,26 @@ function billingHeaders(credential) {
3330
4067
  * `www.workbuddy.cn` 两个入口都返回 200。刻意**不带** `Origin` / `Referer`:
3331
4068
  * 探针当时没带,带了只是多一个可能被网关拒掉的变量,没有收益。
3332
4069
  *
4070
+ * 2026-10-31(P1):`X-Product` 由 `SaaS` 改为 `WorkBuddy`,并补上
4071
+ * `X-Agent-Purpose` / `X-IDE-*` 与设备对,与 chat / billing 同一份自称(见
4072
+ * {@link attributionHeaders})。这里遵守的是一条明确的界线:
4073
+ *
4074
+ * - **身份类头**(`X-Product` / `X-IDE-*` / `X-Agent-Purpose` / 设备对)跟着
4075
+ * 统一走。不统一的代价是新的 D2:同一个 host 上 chat 说自己是 WorkBuddy、
4076
+ * 生图说自己是 SaaS,而这个矛盾恰恰是这次要消掉的东西。
4077
+ * - **网络环境类头**(`Origin` / `Referer`)保持上表的实测形态。它们回答的是
4078
+ * "这条请求从哪来",与"谁在说话"不是一个判据,当时特意排除就先不请回来。
4079
+ *
4080
+ * 代价说清楚:这毕竟是在一条逐字节测过的路径上加了几个头。若生图那道闸哪天
4081
+ * 开始拒,第一个该试的是把 `wireProfile` 切到 `conservative` —— 那一档会把这
4082
+ * 一行连同所有新增头一起还原成 5.16.0。
4083
+ *
4084
+ * 增量的边界是"**自我描述**":`X-Product` / `X-IDE-*` / `X-Agent-Purpose` /
4085
+ * 设备对 / `X-Root-Request-ID` 进,`X-CodeBuddy-Request` 与 `Accept-Language`
4086
+ * **不进**。后两个不是身份而是传输层标记:若闸门真的要求 `X-CodeBuddy-Request`,
4087
+ * 生图(从来没发过它)今天就该失败,而它一直是 200;语言同理,生图输出不是
4088
+ * 语言相关的东西。没有收益的变量不加——这条正是上面那段实测留下的规则。
4089
+ *
3333
4090
  * 复用 {@link conversationHeaders}:官方 CLI 的 ImageService 也是每次现生成
3334
4091
  * 一组会话 UUID。但这里**传 `'image'`,且刻意不跟 `usageIdentity` 开关走**:
3335
4092
  * issue #132 的实测只覆盖 chat,而生图这两个入口在 2026-10-21 是用带连字符的
@@ -3347,15 +4104,45 @@ function imageHeaders(credential, identity = {}) {
3347
4104
  "Accept": "application/json, text/plain, */*",
3348
4105
  "Content-Type": "application/json",
3349
4106
  "User-Agent": PRODUCT_UA,
3350
- "X-Product": "SaaS",
3351
4107
  "X-Requested-With": "XMLHttpRequest",
3352
4108
  ...credential.uid === "" ? { "X-No-User-Id": "1" } : { "X-User-Id": credential.uid },
3353
4109
  ...credential.enterpriseId === void 0 || credential.enterpriseId === "" ? { "X-No-Enterprise-Id": "1" } : { "X-Enterprise-Id": credential.enterpriseId },
3354
4110
  ...credential.domain === "" ? { "X-No-Department-Info": "1" } : { "X-Domain": credential.domain },
4111
+ ...attributionHeaders(identity),
4112
+ ...deviceHeaders(credential, identity),
3355
4113
  ...conversationHeaders("image", identity)
3356
4114
  };
3357
4115
  }
3358
4116
  /**
4117
+ * The header NAMES one outbound request would carry — names only, never values.
4118
+ *
4119
+ * WHY THIS EXISTS. 审计(`docs/DEVICE-IDENTITY-AUDIT.md`)的 P0 要回答"我们现在
4120
+ * 到底发了什么",而这个答案必须**由代码给出**,不能由一段写死的清单给出:写死的
4121
+ * 清单在上线三个月后一定与真实请求脱节,届时它会安静地撒谎。因此这里直接调用
4122
+ * 请求路径上同一批构造器({@link chatHeaders} / {@link imageHeaders} /
4123
+ * {@link refreshHeaders} / {@link billingHeaders}),返回它们的键集合——往
4124
+ * `chatHeaders` 里加一个头,这里自动跟着变,不需要第二次修改。
4125
+ *
4126
+ * 两处**刻意与调用点对齐**的地方:
4127
+ * - `chat` 的 `Authorization` 由调用点合并(`:3739` / `:3810`),不在这批构造器
4128
+ * 里,所以这里补上;不补的话,"chat 有没有带鉴权"会被答成"没有"。
4129
+ * - `refresh` 确实没有 `Authorization`(它用 `X-Refresh-Token`),不补。
4130
+ *
4131
+ * READ-ONLY:不发请求、不返回任何值、不打印任何东西。调用方(`doctor`)决定
4132
+ * 显示到哪一层。
4133
+ */
4134
+ function describeRequestHeaderNames(kind, credential, identity = {}) {
4135
+ switch (kind) {
4136
+ case "chat": return Object.keys({
4137
+ ...chatHeaders(credential, identity),
4138
+ Authorization: `Bearer ${credential.accessToken}`
4139
+ });
4140
+ case "image": return Object.keys(imageHeaders(credential, identity));
4141
+ case "refresh": return Object.keys(refreshHeaders(credential));
4142
+ case "billing": return Object.keys(billingHeaders(credential, identity));
4143
+ }
4144
+ }
4145
+ /**
3359
4146
  * Stand-in system message for a request that reached the wire carrying none.
3360
4147
  *
3361
4148
  * Not a stylistic default: both WorkBuddy gateways want the conversation to
@@ -4843,7 +5630,6 @@ function requestEvidenceOf(bodyJson) {
4843
5630
  */
4844
5631
  var WorkBuddyUpstreamClient = class {
4845
5632
  onFallback;
4846
- identity;
4847
5633
  /**
4848
5634
  * Reports an anomaly the reader or classifier had to tolerate.
4849
5635
  *
@@ -4853,20 +5639,97 @@ var WorkBuddyUpstreamClient = class {
4853
5639
  * `ctx.logger.warn` in; without a host the event is dropped, which is the
4854
5640
  * same silence the previous single-source reader had.
4855
5641
  */
4856
- constructor(onFallback, identity = {}) {
5642
+ /**
5643
+ * 解析一次的底座:设备盐(P1)。真 token 不在这里——它分钟级过期,
5644
+ * 必须每条请求现取,见 {@link wireIdentity}。
5645
+ */
5646
+ baseIdentity;
5647
+ /** 外部 device token 的 TTL 读取器;未配置时为 undefined。 */
5648
+ deviceTokens;
5649
+ /** 每账号覆盖值的读取器(设置里齿轮保存的那些);未接线时为 undefined。 */
5650
+ deviceProfiles;
5651
+ /** 真实值档的 token 源(本机安装的桌面端 SDK);未接线时为 undefined。 */
5652
+ realDevice;
5653
+ constructor(onFallback, identity = {}, options = {}) {
4857
5654
  this.onFallback = onFallback;
4858
- this.identity = identity;
5655
+ this.baseIdentity = resolveWireIdentity(identity);
5656
+ this.deviceProfiles = options.deviceProfiles;
5657
+ this.realDevice = options.realDevice;
5658
+ const file = options.deviceTokenFile === void 0 ? "" : options.deviceTokenFile.trim();
5659
+ this.deviceTokens = file === "" ? void 0 : createDeviceTokenReader({
5660
+ file,
5661
+ ...options.deviceTokenTtlMs === void 0 ? {} : { ttlMs: options.deviceTokenTtlMs },
5662
+ warn: (message) => this.onFallback?.(message)
5663
+ });
5664
+ }
5665
+ /**
5666
+ * 本次请求的完整身份:底座(盐)+ 当前有效的真 token + 这个账号的覆盖值。
5667
+ *
5668
+ * 为什么不是"构造时算一次":盐是本机常量,token 是分钟级过期的东西,覆盖值是
5669
+ * 用户随时会改的设置。三者里只有盐是常量,把另外两个钉在构造期,一个跑了几小时
5670
+ * 的进程会一直发过期 token、也永远看不到刚保存的覆盖值。
5671
+ */
5672
+ async wireIdentity(credential) {
5673
+ const base = await this.baseIdentity;
5674
+ if (profileOf(base) !== "balanced") return base;
5675
+ if ((this.deviceProfiles === void 0 ? "virtual" : await this.deviceProfiles.mode()) === "real") {
5676
+ const real = this.realDevice === void 0 ? void 0 : await this.realDevice.current();
5677
+ if (real !== void 0) return {
5678
+ ...base,
5679
+ deviceTier: "real",
5680
+ deviceReal: real
5681
+ };
5682
+ /**
5683
+ * 取不到真实 token。两条路,由用户在卡片上选(作者意见 #2)。
5684
+ *
5685
+ * **不退回(默认关时会走到这里,也是 P3 原来的行为)**:一个设备头都不发。
5686
+ * 那是"SDK 不可用"时唯一不会说谎的答案——拿虚拟值顶上而界面写着「真实值」
5687
+ * 会让线上与界面对不上。
5688
+ *
5689
+ * **退回**(默认开):落到下面的虚拟值通道,但**档位降成 `virtual`**,不是
5690
+ * 保留 `real` 再补一对派生 id。这一点是刻意的:`deviceTier` 既决定发哪些头,
5691
+ * 也决定界面与 `doctor` 怎么称呼"现在发的是什么"。保留 `real` 会让报告与
5692
+ * 出站字节相反,而报告正是用户用来判断"到底退没退"的唯一依据。
5693
+ *
5694
+ * 退回的那个瞬间不会静默:`readout()` 里 token 状态是 `unavailable` 并带
5695
+ * 原因,卡片与 `doctor` 都照实显示"现在发的是虚拟值,因为 SDK 取不到 token"。
5696
+ */
5697
+ if (this.deviceProfiles === void 0 || !await this.deviceProfiles.fallbackToVirtual()) return {
5698
+ ...base,
5699
+ deviceTier: "real"
5700
+ };
5701
+ const fallbackToken = this.deviceTokens === void 0 ? void 0 : await this.deviceTokens.current();
5702
+ return {
5703
+ ...base,
5704
+ deviceTier: "virtual",
5705
+ ...fallbackToken === void 0 ? {} : { deviceToken: fallbackToken }
5706
+ };
5707
+ }
5708
+ const token = this.deviceTokens === void 0 ? void 0 : await this.deviceTokens.current();
5709
+ const profile = this.deviceProfiles === void 0 ? void 0 : await this.deviceProfiles.forUid(credential.uid);
5710
+ return {
5711
+ ...base,
5712
+ ...token === void 0 ? {} : { deviceToken: token },
5713
+ ...profile === void 0 ? {} : { deviceProfile: profile }
5714
+ };
4859
5715
  }
4860
5716
  /** POST the chat endpoint; a successful answer is the raw SSE response. */
4861
5717
  async chatStream(credential, bodyJson, signal) {
4862
5718
  let response;
4863
5719
  try {
5720
+ const headers = {
5721
+ ...chatHeaders(credential, await this.wireIdentity(credential)),
5722
+ "Authorization": `Bearer ${credential.accessToken}`
5723
+ };
5724
+ if (signal?.aborted === true) return {
5725
+ ok: false,
5726
+ status: 0,
5727
+ kind: "server",
5728
+ message: "cancelled before send"
5729
+ };
4864
5730
  response = await fetch(`${chatBase(credential)}/v2/chat/completions`, {
4865
5731
  method: "POST",
4866
- headers: {
4867
- ...chatHeaders(credential, this.identity),
4868
- "Authorization": `Bearer ${credential.accessToken}`
4869
- },
5732
+ headers,
4870
5733
  body: bodyJson,
4871
5734
  ...signal === void 0 ? {} : { signal }
4872
5735
  });
@@ -4918,8 +5781,24 @@ var WorkBuddyUpstreamClient = class {
4918
5781
  * model on the same clock as a dead endpoint, and the whole point of the
4919
5782
  * period is to answer "did the upstream answer at all". A probe asks for a
4920
5783
  * single token, so the body that follows is one SSE line.
5784
+ *
5785
+ * It likewise does not cover building the headers. That step became slow in P3
5786
+ * (the device-token path is a subprocess with a 20 s budget), and starting the
5787
+ * clock first made a healthy gateway answer `status 0` on a cold start — which
5788
+ * the pool reads as "unreachable" and acts on by benching the account. Hence
5789
+ * the deliberate order below: resolve identity, THEN arm the timer.
4921
5790
  */
4922
5791
  async probeChat(credential, bodyJson, signal) {
5792
+ const headers = {
5793
+ ...chatHeaders(credential, await this.wireIdentity(credential)),
5794
+ "Authorization": `Bearer ${credential.accessToken}`
5795
+ };
5796
+ if (signal?.aborted === true) return {
5797
+ ok: false,
5798
+ status: 0,
5799
+ retryAfter: null,
5800
+ body: "cancelled before send"
5801
+ };
4923
5802
  let response;
4924
5803
  const ceiling = new AbortController();
4925
5804
  const timer = setTimeout(() => {
@@ -4928,10 +5807,7 @@ var WorkBuddyUpstreamClient = class {
4928
5807
  try {
4929
5808
  response = await fetch(`${chatBase(credential)}/v2/chat/completions`, {
4930
5809
  method: "POST",
4931
- headers: {
4932
- ...chatHeaders(credential, this.identity),
4933
- "Authorization": `Bearer ${credential.accessToken}`
4934
- },
5810
+ headers,
4935
5811
  body: bodyJson,
4936
5812
  signal: signal === void 0 ? ceiling.signal : AbortSignal.any([signal, ceiling.signal])
4937
5813
  });
@@ -5067,7 +5943,7 @@ var WorkBuddyUpstreamClient = class {
5067
5943
  const response = await fetch(`${chatBase(credential)}${MODEL_BUSY_PATH}`, {
5068
5944
  method: "POST",
5069
5945
  headers: {
5070
- ...commonHeaders(credential),
5946
+ ...legacyCommonHeaders(credential),
5071
5947
  "Authorization": `Bearer ${credential.accessToken}`,
5072
5948
  "Content-Type": "application/json"
5073
5949
  },
@@ -5143,7 +6019,7 @@ var WorkBuddyUpstreamClient = class {
5143
6019
  async generateImage(credential, request, signal) {
5144
6020
  const response = await fetch(`${chatBase(credential)}${IMAGE_GENERATIONS_PATH}`, {
5145
6021
  method: "POST",
5146
- headers: imageHeaders(credential, this.identity),
6022
+ headers: imageHeaders(credential, await this.wireIdentity(credential)),
5147
6023
  body: JSON.stringify(buildImageBody(request)),
5148
6024
  signal: signal ?? AbortSignal.timeout(IMAGE_TIMEOUT_MS)
5149
6025
  });
@@ -5172,7 +6048,7 @@ var WorkBuddyUpstreamClient = class {
5172
6048
  if (request.image.length === 0) throw new WorkBuddyImageError("workbuddy image: 改图请求缺少输入图(image 数组为空)。", "INVALID_ARGS");
5173
6049
  const response = await fetch(`${chatBase(credential)}${IMAGE_EDITS_PATH}`, {
5174
6050
  method: "POST",
5175
- headers: imageHeaders(credential),
6051
+ headers: imageHeaders(credential, await this.wireIdentity(credential)),
5176
6052
  body: JSON.stringify(buildEditBody(request)),
5177
6053
  signal: signal ?? AbortSignal.timeout(IMAGE_TIMEOUT_MS)
5178
6054
  });
@@ -5213,7 +6089,7 @@ var WorkBuddyUpstreamClient = class {
5213
6089
  }, isImageToVideo);
5214
6090
  const response = await fetch(`${chatBase(credential)}${VIDEO_GENERATIONS_PATH}`, {
5215
6091
  method: "POST",
5216
- headers: imageHeaders(credential, this.identity),
6092
+ headers: imageHeaders(credential, await this.wireIdentity(credential)),
5217
6093
  body: JSON.stringify(body),
5218
6094
  signal: signal ?? AbortSignal.timeout(VIDEO_TIMEOUT_MS)
5219
6095
  });
@@ -5249,7 +6125,7 @@ var WorkBuddyUpstreamClient = class {
5249
6125
  try {
5250
6126
  const response = await fetch(`${chatBase(credential)}${VIDEO_TASKS_PATH}`, {
5251
6127
  method: "POST",
5252
- headers: imageHeaders(credential, this.identity),
6128
+ headers: imageHeaders(credential, await this.wireIdentity(credential)),
5253
6129
  body: JSON.stringify({ task_id: taskId }),
5254
6130
  signal: combined
5255
6131
  });
@@ -5307,7 +6183,7 @@ var WorkBuddyUpstreamClient = class {
5307
6183
  async fetchCheckinStatus(credential) {
5308
6184
  const response = await fetch(`${billingBase(credential)}/v2/billing/meter/checkin-activity-status`, {
5309
6185
  method: "POST",
5310
- headers: billingHeaders(credential),
6186
+ headers: billingHeaders(credential, await this.wireIdentity(credential)),
5311
6187
  body: "{}",
5312
6188
  signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
5313
6189
  });
@@ -5360,7 +6236,7 @@ var WorkBuddyUpstreamClient = class {
5360
6236
  async readBenefitStatus(kind, credential, path) {
5361
6237
  const response = await fetch(`${billingBase(credential)}${path}`, {
5362
6238
  method: "POST",
5363
- headers: billingHeaders(credential),
6239
+ headers: billingHeaders(credential, await this.wireIdentity(credential)),
5364
6240
  body: "{}",
5365
6241
  signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
5366
6242
  });
@@ -5405,7 +6281,7 @@ var WorkBuddyUpstreamClient = class {
5405
6281
  async claimBenefit(credential, kind) {
5406
6282
  const response = await fetch(`${billingBase(credential)}${BENEFIT_CLAIM_PATHS[kind]}`, {
5407
6283
  method: "POST",
5408
- headers: billingHeaders(credential),
6284
+ headers: billingHeaders(credential, await this.wireIdentity(credential)),
5409
6285
  body: "{}",
5410
6286
  signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
5411
6287
  });
@@ -5416,7 +6292,7 @@ var WorkBuddyUpstreamClient = class {
5416
6292
  async claimDailyCheckin(credential) {
5417
6293
  const response = await fetch(`${billingBase(credential)}/v2/billing/meter/daily-checkin`, {
5418
6294
  method: "POST",
5419
- headers: billingHeaders(credential),
6295
+ headers: billingHeaders(credential, await this.wireIdentity(credential)),
5420
6296
  body: "{}",
5421
6297
  signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
5422
6298
  });
@@ -5453,7 +6329,7 @@ var WorkBuddyUpstreamClient = class {
5453
6329
  async fetchEnterpriseCredits(credential) {
5454
6330
  const response = await fetch(`${billingBase(credential)}/billing/meter/get-enterprise-user-usage`, {
5455
6331
  method: "POST",
5456
- headers: billingHeaders(credential),
6332
+ headers: billingHeaders(credential, await this.wireIdentity(credential)),
5457
6333
  body: JSON.stringify({}),
5458
6334
  signal: AbortSignal.timeout(JSON_TIMEOUT_MS)
5459
6335
  });
@@ -5502,7 +6378,7 @@ var WorkBuddyUpstreamClient = class {
5502
6378
  ].join(":");
5503
6379
  const response = await fetch(`${billingBase(credential)}/v2/billing/meter/get-user-resource`, {
5504
6380
  method: "POST",
5505
- headers: billingHeaders(credential),
6381
+ headers: billingHeaders(credential, await this.wireIdentity(credential)),
5506
6382
  body: JSON.stringify({
5507
6383
  PageNumber: 1,
5508
6384
  PageSize: 100,
@@ -6277,9 +7153,42 @@ async function readVaultEntries(dir) {
6277
7153
  }
6278
7154
  return entries;
6279
7155
  }
6280
- /** Write one vault entry atomically under the file lock. */
7156
+ /**
7157
+ * Write one vault entry atomically under the file lock.
7158
+ *
7159
+ * The directory is hardened BEFORE the file is created (issue #183). Order
7160
+ * matters: `writeFileAtomic` commits by creating a temp inode and renaming it
7161
+ * over the target, so an ACL applied to the file afterwards would leave the
7162
+ * pre-rename window open, and a crash between the two would leave a plaintext
7163
+ * token in a file nobody hardened. Hardening the directory first means the
7164
+ * replacement inode inherits the restricted ACEs at creation.
7165
+ *
7166
+ * The hardening is best-effort on purpose: it is defence in depth, and refusing
7167
+ * to persist a credential because an ACL call failed would turn it into an
7168
+ * outage. `doctor` reports the outcome so a machine where it failed is visible.
7169
+ * On POSIX this call is a no-op, and `mode` below carries the same intent.
7170
+ */
6281
7171
  async function writeVaultEntry(dir, accountId, credential, refreshedFrom) {
6282
7172
  const path = join(dir, `${accountId}.json`);
7173
+ /**
7174
+ * Harden the vault ROOT, which also hardens this region's directory and sweeps
7175
+ * the files already inside (issue #183).
7176
+ *
7177
+ * The root, not just `dir`: `dir` is `<vault>/<region>`, and the root is what
7178
+ * carries the inherited `Everyone: FullControl` from `~/.dsh`. Leaving the
7179
+ * root widened would let any local process delete or replace the region
7180
+ * directory itself, which defeats the file-level restriction inside it.
7181
+ *
7182
+ * BEFORE the write, so the commit's temp inode — and the file it is renamed
7183
+ * over — inherit the hardened ACEs instead of the widened ones. A file-level
7184
+ * pass AFTER the write would leave the pre-rename window open and would be
7185
+ * lost by the next atomic replace, which creates a fresh inode each time.
7186
+ *
7187
+ * Memoized per directory per process, so the second account costs nothing: see
7188
+ * the cost model in `src/windows-acl.ts` for why the per-write budget matters
7189
+ * here.
7190
+ */
7191
+ await protectCredentialDirectory(dirname(dir));
6283
7192
  await withFileLock(path, async () => {
6284
7193
  await writeFileAtomic(path, `${JSON.stringify(vaultDocument(credential, accountId, refreshedFrom), null, 2)}\n`, {
6285
7194
  mode: 384,
@@ -7559,6 +8468,830 @@ var WorkBuddyCatalog = class {
7559
8468
  this.models = models.map((model) => ({ ...model }));
7560
8469
  }
7561
8470
  };
8471
+ /** 文件名,带前导点,与 `.workbuddy-device.json` 同一约定。 */
8472
+ const DEVICE_PROFILE_FILE_NAME = ".workbuddy-device-profiles.json";
8473
+ /**
8474
+ * 文件不存在、不可读、版本不认识时的答案:虚拟档、无覆盖、回退开、无手填目录。
8475
+ *
8476
+ * 回退默认**开**,所以一个 5.16.0 时代写下的文件(没有这个字段)升级后立刻拿到
8477
+ * 作者希望的默认行为,不需要用户去点一次。
8478
+ */
8479
+ function emptyDocument() {
8480
+ return {
8481
+ version: 1,
8482
+ mode: "virtual",
8483
+ accounts: {},
8484
+ sdkDir: "",
8485
+ sdkFallbackToVirtual: true
8486
+ };
8487
+ }
8488
+ /**
8489
+ * 读盘缓存:同一进程内的请求路径不该每条都去读 200 字节。
8490
+ *
8491
+ * **按路径索引**,不是一个全局槽:这个模块同时服务"真实 DSH home"与测试里
8492
+ * 那些临时目录,一个全局槽会让第二台机器(或第二个测试)读到第一份内容。
8493
+ */
8494
+ const CACHE_MS = 5e3;
8495
+ const cache = /* @__PURE__ */ new Map();
8496
+ /** Drop the cache — every write calls this, so a save is visible immediately. */
8497
+ function invalidate() {
8498
+ cache.clear();
8499
+ }
8500
+ /** `$DSH_HOME/.workbuddy-device-profiles.json`, or `dir` when one is pinned (tests). */
8501
+ function deviceProfilePath(dir) {
8502
+ const base = typeof dir === "string" && dir !== "" ? dir : resolveDshHome();
8503
+ return join(base, DEVICE_PROFILE_FILE_NAME);
8504
+ }
8505
+ /** Whether an unknown value is a mode this build understands. */
8506
+ function isDeviceMode(value) {
8507
+ return value === "virtual" || value === "real";
8508
+ }
8509
+ /** Keep only the fields that are well-formed; a hand-edited file must not break a request. */
8510
+ function sanitizeAccount(raw) {
8511
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return void 0;
8512
+ const record = raw;
8513
+ const account = {};
8514
+ if (typeof record["uid"] === "string" && record["uid"] !== "") account.uid = record["uid"];
8515
+ if (typeof record["machineId"] === "string" && isDeviceId(record["machineId"])) account.machineId = record["machineId"];
8516
+ if (typeof record["sessionId"] === "string" && isDeviceId(record["sessionId"])) account.sessionId = record["sessionId"];
8517
+ if (typeof record["updatedAt"] === "string") account.updatedAt = record["updatedAt"];
8518
+ return account.uid === void 0 && account.machineId === void 0 && account.sessionId === void 0 ? void 0 : account;
8519
+ }
8520
+ /** Read the on-disk document, tolerating anything a hand edit can produce. */
8521
+ async function readStored(dir, nowMs = Date.now(), fresh = false) {
8522
+ const path = deviceProfilePath(dir);
8523
+ const hit = cache.get(path);
8524
+ if (!fresh && hit !== void 0 && nowMs - hit.at < CACHE_MS) return hit.document;
8525
+ const remember = (document) => {
8526
+ cache.set(path, {
8527
+ at: nowMs,
8528
+ document
8529
+ });
8530
+ return document;
8531
+ };
8532
+ let text;
8533
+ try {
8534
+ text = await readFile(path, "utf8");
8535
+ } catch {
8536
+ return remember(emptyDocument());
8537
+ }
8538
+ let parsed;
8539
+ try {
8540
+ parsed = JSON.parse(text);
8541
+ } catch {
8542
+ return remember(emptyDocument());
8543
+ }
8544
+ const record = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : {};
8545
+ if (record["version"] !== 1) return remember(emptyDocument());
8546
+ const accounts = {};
8547
+ const rawAccounts = record["accounts"];
8548
+ if (typeof rawAccounts === "object" && rawAccounts !== null && !Array.isArray(rawAccounts)) for (const [id, value] of Object.entries(rawAccounts)) {
8549
+ const account = sanitizeAccount(value);
8550
+ if (account !== void 0) accounts[id] = account;
8551
+ }
8552
+ return remember({
8553
+ version: 1,
8554
+ mode: isDeviceMode(record["mode"]) ? record["mode"] : "virtual",
8555
+ accounts,
8556
+ sdkDir: typeof record["sdkDir"] === "string" ? record["sdkDir"].trim() : "",
8557
+ sdkFallbackToVirtual: record["sdkFallbackToVirtual"] !== false
8558
+ });
8559
+ }
8560
+ /** The browser-facing shape: no uids, no timestamps it cannot use. */
8561
+ function toSettings(document) {
8562
+ const accounts = {};
8563
+ for (const [id, account] of Object.entries(document.accounts)) {
8564
+ const profile = {
8565
+ ...account.machineId === void 0 ? {} : { machineId: account.machineId },
8566
+ ...account.sessionId === void 0 ? {} : { sessionId: account.sessionId }
8567
+ };
8568
+ if (profile.machineId !== void 0 || profile.sessionId !== void 0) accounts[id] = profile;
8569
+ }
8570
+ return {
8571
+ mode: document.mode,
8572
+ accounts,
8573
+ sdkDir: document.sdkDir,
8574
+ sdkFallbackToVirtual: document.sdkFallbackToVirtual
8575
+ };
8576
+ }
8577
+ /** Read the settings the card renders. Never throws. */
8578
+ async function readDeviceSettings(options = {}) {
8579
+ return toSettings(await readStored(options.dir));
8580
+ }
8581
+ /**
8582
+ * 算出每个账号"留空时会发出"的那一对 id,供弹窗直接显示。
8583
+ *
8584
+ * 为什么需要它:弹窗里两个输入框为空时只写"留空 = 自动派生",用户既看不到
8585
+ * 结果,也无法判断两个账号是否被算成了同一台设备。把派生值摆出来,"留空"就从
8586
+ * 一句承诺变成了一个可核对的事实。
8587
+ *
8588
+ * `uid` 由调用方(Host 的凭据库)提供——浏览器只知道 accountId,而**派生必须
8589
+ * 用 uid**,因为构头时 `deviceHeaders()` 手上只有 credential.uid。两边用同一种
8590
+ * 输入,界面显示的值才等于真正发出去的值。
8591
+ *
8592
+ * 盐不可用时返回 `undefined`(而不是空对象):那一档一个设备头都不发,显示一个
8593
+ * "派生值"会是在说谎;而空对象表示"盐是好的,但这些账号没有一个算得出来"
8594
+ * (没有 uid),两者在界面上要说不同的话。
8595
+ */
8596
+ async function describeDerivedDevices(entries, options = {}) {
8597
+ let salt = options.salt;
8598
+ if (salt === void 0) {
8599
+ const readout = options.dir === void 0 ? await readDeviceSalt() : await readDeviceSalt({ dir: options.dir });
8600
+ if (readout.state !== "ok") return void 0;
8601
+ salt = readout.salt;
8602
+ }
8603
+ if (salt === "") return void 0;
8604
+ const derived = {};
8605
+ for (const entry of entries) {
8606
+ if (entry.accountId === "" || entry.uid === "") continue;
8607
+ derived[entry.accountId] = {
8608
+ machineId: deriveDeviceId(entry.uid, "machine", salt),
8609
+ sessionId: deriveDeviceId(entry.uid, "session", salt)
8610
+ };
8611
+ }
8612
+ return derived;
8613
+ }
8614
+ /**
8615
+ * Persist one document atomically.
8616
+ *
8617
+ * **The caller holds the lock.** Every write path takes `withFileLock` itself
8618
+ * (read-merge-write must be one step against another process), so this function
8619
+ * must not take it again — a second acquisition on the same path is how a save
8620
+ * turns into a hang.
8621
+ */
8622
+ async function writeStored(document, dir) {
8623
+ await writeFileAtomic(deviceProfilePath(dir), `${JSON.stringify(document, null, 2)}\n`, {
8624
+ mode: 384,
8625
+ dirMode: 448
8626
+ });
8627
+ invalidate();
8628
+ }
8629
+ /**
8630
+ * Switch the device-head tier.
8631
+ *
8632
+ * 「真实值」目前只被记住,不改任何出站字节——P3 才接真 token 与互斥规则。
8633
+ * 界面上必须把这件事说清楚(`row.deviceModeRealNote`),否则用户会以为切过去
8634
+ * 就换成了真实设备。
8635
+ */
8636
+ async function setDeviceMode(mode, options = {}) {
8637
+ return withFileLock(deviceProfilePath(options.dir), async () => {
8638
+ const next = {
8639
+ ...await readStored(options.dir, Date.now(), true),
8640
+ mode
8641
+ };
8642
+ await writeStored(next, options.dir);
8643
+ return toSettings(next);
8644
+ });
8645
+ }
8646
+ /**
8647
+ * Save the two SDK settings the card edits (作者意见 #1 与 #2).
8648
+ *
8649
+ * 两项都是**可选**参数,`undefined` 表示"不要动这一项"——与
8650
+ * {@link saveDeviceProfile} 同一条约定:卡片上有两个独立控件,其中一个的保存
8651
+ * 不该把另一个刚改的值写回旧值。
8652
+ *
8653
+ * `sdkDir` 只做去空白,不做存在性校验:一个路径填错的正确反馈是「探不到 SDK」
8654
+ * (`probe` 会答 `missing` 或 `error` 并带上那个路径),而不是在这里拒绝保存——
8655
+ * 后者会让用户面对一个"保存没反应"的输入框,而他刚刚明明看见文件在那儿。
8656
+ */
8657
+ async function saveDeviceSdkSettings(values, options = {}) {
8658
+ return withFileLock(deviceProfilePath(options.dir), async () => {
8659
+ const next = {
8660
+ ...await readStored(options.dir, Date.now(), true),
8661
+ ...typeof values.sdkDir === "string" ? { sdkDir: values.sdkDir.trim() } : {},
8662
+ ...typeof values.sdkFallbackToVirtual === "boolean" ? { sdkFallbackToVirtual: values.sdkFallbackToVirtual } : {}
8663
+ };
8664
+ await writeStored(next, options.dir);
8665
+ return toSettings(next);
8666
+ });
8667
+ }
8668
+ /**
8669
+ * Save (or clear) one account's overrides.
8670
+ *
8671
+ * `machineId` / `sessionId` 为 `''` 表示"清掉这一项、回到派生值";为 `undefined`
8672
+ * 表示"不要动这一项"。两种省略必须能分开:弹窗里只改机器 id 时,不能把用户之前
8673
+ * 设的 session id 顺手抹掉。
8674
+ *
8675
+ * @throws when a supplied value is not a 36-character lowercase hex id — the
8676
+ * route turns that into a 400 rather than writing a value the upstream will reject.
8677
+ */
8678
+ async function saveDeviceProfile(accountId, values, options = {}) {
8679
+ for (const value of [values.machineId, values.sessionId]) if (value !== void 0 && value !== "" && !isDeviceId(value)) throw new Error("device id must be 36 lowercase hex characters");
8680
+ return withFileLock(deviceProfilePath(options.dir), async () => {
8681
+ const document = await readStored(options.dir, Date.now(), true);
8682
+ const next = { ...document.accounts[accountId] ?? {} };
8683
+ if (values.uid !== void 0 && values.uid !== "") next.uid = values.uid;
8684
+ for (const key of ["machineId", "sessionId"]) {
8685
+ const value = values[key];
8686
+ if (value === void 0) continue;
8687
+ if (value === "") delete next[key];
8688
+ else next[key] = value;
8689
+ }
8690
+ next.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
8691
+ const accounts = {
8692
+ ...document.accounts,
8693
+ [accountId]: next
8694
+ };
8695
+ if (next.machineId === void 0 && next.sessionId === void 0) delete accounts[accountId];
8696
+ const merged = {
8697
+ ...document,
8698
+ accounts
8699
+ };
8700
+ await writeStored(merged, options.dir);
8701
+ return toSettings(merged);
8702
+ });
8703
+ }
8704
+ /** Build the lookup; `ttlMs` exists so an externally edited file is still picked up. */
8705
+ function createDeviceProfileLookup(options = {}) {
8706
+ const byUid = (document) => {
8707
+ const map = /* @__PURE__ */ new Map();
8708
+ for (const account of Object.values(document.accounts)) {
8709
+ if (account.uid === void 0) continue;
8710
+ const profile = {
8711
+ ...account.machineId === void 0 ? {} : { machineId: account.machineId },
8712
+ ...account.sessionId === void 0 ? {} : { sessionId: account.sessionId }
8713
+ };
8714
+ if (profile.machineId !== void 0 || profile.sessionId !== void 0) map.set(account.uid, profile);
8715
+ }
8716
+ return map;
8717
+ };
8718
+ return {
8719
+ async forUid(uid) {
8720
+ if (uid === "") return void 0;
8721
+ return byUid(await readStored(options.dir)).get(uid);
8722
+ },
8723
+ async mode() {
8724
+ return (await readStored(options.dir)).mode;
8725
+ },
8726
+ async fallbackToVirtual() {
8727
+ return (await readStored(options.dir)).sdkFallbackToVirtual;
8728
+ },
8729
+ async sdkDir() {
8730
+ return (await readStored(options.dir)).sdkDir;
8731
+ }
8732
+ };
8733
+ }
8734
+ //#endregion
8735
+ //#region src/turing-sdk.ts
8736
+ /**
8737
+ * 真实设备参数:本机已安装的 WorkBuddy 桌面端自带 Turing Shield SDK 的取链(P3)。
8738
+ *
8739
+ * ## SDK 从哪来
8740
+ *
8741
+ * 插件**不携带任何 SDK 副本**。原生模块与厂商 DLL 是桌面端自己的构建产物
8742
+ * (`turing_sdk.node` 内的 pdb 路径指向桌面端仓库),随插件再分发既无 provenance
8743
+ * 也无许可证,因此这个模块找的是**用户机器上已安装的那份**:环境变量
8744
+ * `WORKBUDDY_TURING_SDK_DIR` 显式指定优先,否则按桌面端的安装形状(Windows 卸载
8745
+ * 注册表 + 常见目录,macOS `/Applications` 与 `~/Applications` 的 bundle)现推
8746
+ * SDK 目录。找不到就是 `missing`——真实值档下发零个设备头,与从前"这个平台没有
8747
+ * 副本"是同一个降级,用户能做的是装上桌面端或指定目录。
8748
+ *
8749
+ * ## 它补的是哪一格
8750
+ *
8751
+ * 「虚拟值」档的设备对(`X-Machine-ID` / `X-Session-ID`)是算出来的:稳定、按号
8752
+ * 隔离,但**任何一台机器都能算出同样的形状**。「真实值」档要的是这台机器上
8753
+ * 真的装着的那套东西——由 SDK 向风控服务换回的 `X-Device-Token`。两者互斥,不能
8754
+ * 叠加:真 token 内含设备信息,旁边再挂一对伪造 id 等于自证不一致。
8755
+ *
8756
+ * ## 为什么要子进程
8757
+ *
8758
+ * SDK 是原生插件(N-API),加载它会绑定宿主进程:一次 ABI/缺 DLL/被替换的失败
8759
+ * 就是插件进程的失败,而不是"设备头不可用";它的 Promise 没有 cancel,一次超时
8760
+ * 会把句柄留在进程里。子进程把这两件事都降级成"这一条命令失败",父进程杀掉它
8761
+ * 就是干净的收场。代价是每次冷启动多一次进程创建(本机实测 ~6 ms)。
8762
+ *
8763
+ * ## 缓存策略
8764
+ *
8765
+ * token 是分钟级的东西、进程是小时级的,所以**绝不能只取一次**。内存 TTL 10 分钟,
8766
+ * 失败时回落到 24 小时内的旧值并标记 `stale`(设备 token 的有效期远长于它的
8767
+ * 刷新周期)。**不落盘**:多一份 secret 文件换来的只是省掉一次 100 ms 的取数,
8768
+ * 不划算——这与 P2 的文件源是两种东西,那个读的是别人写的文件。
8769
+ *
8770
+ * ## 谁来决定"什么时候取"
8771
+ *
8772
+ * 请求路径只在**要发请求**时调 {@link TuringTokenSource.current},所以一个空闲
8773
+ * 进程一辈子不会刷新 token——面板上永远是"已加载、没取过",而用户无法把这句话
8774
+ * 与"SDK 坏了"区分开。插件 apply 时调 {@link TuringSdk.startAutoRefresh}:立刻
8775
+ * 取一次,此后在 TTL 到期前自动换新;失败按 {@link TuringKeepAliveTiming.retryMs}
8776
+ * 重试,本机没有 SDK 则按 {@link TuringKeepAliveTiming.unavailableMs} 慢查。
8777
+ *
8778
+ * ## 从不打印 token
8779
+ *
8780
+ * 这个模块的任何日志、任何返回给浏览器的状态里都只有掩码与长度。完整值只经
8781
+ * {@link TuringTokenSource.reveal} 在用户显式点击时给一次。
8782
+ *
8783
+ * @module dsh-connect-workbuddy/turing-sdk
8784
+ */
8785
+ /** 允许指向别的 SDK 副本(自建、或桌面端安装目录)。 */
8786
+ const TURING_SDK_DIR_ENV = "WORKBUDDY_TURING_SDK_DIR";
8787
+ /** 取不到新 token 时,旧值最多还能用多久。设备 token 本身长期有效。 */
8788
+ const TURING_TOKEN_STALE_MS = 864e5;
8789
+ /** 子进程的总预算。SDK 在本机实测 ~110 ms;给到 20 s 是为了覆盖冷启动与 DNS 慢。 */
8790
+ const RUN_TIMEOUT_MS = 2e4;
8791
+ /** `probe` 的缓存时长:SDK 在进程生命周期内不会变,但 DLL 可能被外部替换。 */
8792
+ const PROBE_CACHE_MS = 6e4;
8793
+ /**
8794
+ * 取数失败后的退避窗口。
8795
+ *
8796
+ * 这不是性能优化,是正确性:一次对话会并发打出十几条请求,如果每次失败都重试,
8797
+ * 一个 SDK 故障会变成"每轮十几个子进程 + 十几个 20 秒超时"。退避期间直接返回上一枚
8798
+ * 可用值(没有就返回 `undefined`),而**手动「重新获取」绕过它**——用户点那个按钮,
8799
+ * 就是要求现在再试一次。
8800
+ */
8801
+ const RETRY_BACKOFF_MS = 3e4;
8802
+ /** 生产用法;测试可以整体或部分覆盖(见 `createTuringSdk` 的 `keepAliveTiming`)。 */
8803
+ const TURING_KEEP_ALIVE_TIMING = {
8804
+ leadMs: 15e3,
8805
+ retryMs: 6e4,
8806
+ unavailableMs: 3e5,
8807
+ minDelayMs: 5e3
8808
+ };
8809
+ /** 决定下一次自动预热的延迟(毫秒)。导出来是为了能直接测调度,而不必真等十分钟。 */
8810
+ function nextAutoRefreshDelayMs(input, timing = TURING_KEEP_ALIVE_TIMING) {
8811
+ const { nowMs, ttlMs, fetchedAtMs, lastFailureAtMs, sdkState } = input;
8812
+ if (fetchedAtMs !== void 0) {
8813
+ if (lastFailureAtMs !== void 0 && lastFailureAtMs >= fetchedAtMs) return timing.retryMs;
8814
+ const remainMs = ttlMs - timing.leadMs - (nowMs - fetchedAtMs);
8815
+ return Math.max(remainMs, timing.minDelayMs);
8816
+ }
8817
+ return sdkState !== void 0 && sdkState !== "ready" ? timing.unavailableMs : timing.retryMs;
8818
+ }
8819
+ /** 内置副本的目录名,按 `platform-arch` 分。目前只有 Windows。 */
8820
+ /** 展示用的主机的三元组,`win32-x64` 之类。SDK 目录**不再**按它拼——见下方发现逻辑。 */
8821
+ function bundledSdkBundleId(platform = process.platform, arch = process.arch) {
8822
+ return `${platform}-${arch}`;
8823
+ }
8824
+ /**
8825
+ * 插件自带的 `native/turing-sdk` 根目录——现在里面**只有** `worker.cjs` 与这份
8826
+ * README,不再有 SDK 副本(原生模块与厂商 DLL 是桌面端的构建产物,不随插件分发)。
8827
+ *
8828
+ * `import.meta.url` 指向 `lib/index.js`(构建产物)或 `src/turing-sdk.ts`(开发与
8829
+ * 测试),两者都在包根下一层,所以 `../native/...` 在两种形态下都成立——这是
8830
+ * 不用 `process.cwd()` 的原因:cwd 是调用者的,不是插件的。
8831
+ */
8832
+ function bundledSdkRoot() {
8833
+ return fileURLToPath(new URL("../native/turing-sdk", import.meta.url));
8834
+ }
8835
+ /** 子进程脚本的路径;随插件分发,加载的是**用户机器上**的 SDK。 */
8836
+ function workerPath() {
8837
+ return join(bundledSdkRoot(), "worker.cjs");
8838
+ }
8839
+ /**
8840
+ * SDK 目录相对桌面端安装根目录的形状(Electron 把原生模块从 asar 里解包出来)。
8841
+ *
8842
+ * macOS 实测(A 级,2026-11-01,`/Applications/WorkBuddy.app` 与
8843
+ * `"/Applications/WorkBuddy AI.app"` 两份都在):
8844
+ * `<bundle>/Contents/Resources/app.asar.unpacked/native/turing-sdk`,里面有
8845
+ * `index.cjs` / `package.json` / `build/Release/turing_sdk.node`。
8846
+ * Windows 实测(A 级,2026-11-01,`F:\智能体安装路径\WorkBuddy`):
8847
+ * `<install>\resources\app.asar.unpacked\native\turing-sdk` 同形状成立——
8848
+ * `WorkBuddy.exe` → 该目录 → `hasTuringSdkBinding` 命中,doctor 报
8849
+ * `ready (win32-x64 — <install>\resources\app.asar.unpacked\native\turing-sdk)`
8850
+ * 并经桌面端自己的 SDK 副本取到 1174 字符真 token。另经 app.asar 解包核对:
8851
+ * `native/turing-sdk` 在 asar 头里标 `unpacked`,实体只在 `app.asar.unpacked`
8852
+ * 一侧,两条路径就是全部分布。注意 DSH Desktop / DSH NEXT 本身是另一种应用、
8853
+ * **不含**这份 SDK——发现的搜索对象是 WorkBuddy 桌面端,不是运行宿主。
8854
+ */
8855
+ function installedSdkDirFromExecutable(platform, executable) {
8856
+ if (platform === "win32") {
8857
+ const install = win32.dirname(executable);
8858
+ return win32.join(install, "resources", "app.asar.unpacked", "native", "turing-sdk");
8859
+ }
8860
+ if (platform === "darwin") {
8861
+ const contents = posix.dirname(posix.dirname(executable));
8862
+ const bundle = posix.dirname(contents);
8863
+ return posix.join(bundle, "Contents", "Resources", "app.asar.unpacked", "native", "turing-sdk");
8864
+ }
8865
+ }
8866
+ /** 一份 turing-sdk 目录是不是能用:原生模块在不在它声明的位置。 */
8867
+ function hasTuringSdkBinding(dir, exists = existsSync, platform = process.platform) {
8868
+ const parts = [
8869
+ "build",
8870
+ "Release",
8871
+ "turing_sdk.node"
8872
+ ];
8873
+ const dataJoin = platform === "win32" ? win32.join : posix.join;
8874
+ const alternateJoin = platform === "win32" ? posix.join : win32.join;
8875
+ const dataPath = dataJoin(dir, ...parts);
8876
+ if (exists(dataPath)) return true;
8877
+ const alternatePath = alternateJoin(dir, ...parts);
8878
+ return alternatePath !== dataPath && exists(alternatePath);
8879
+ }
8880
+ /**
8881
+ * 按桌面端的安装形状找本机已安装的 SDK 目录,返回**第一个可用的**。
8882
+ *
8883
+ * 候选来自 `at-rest.ts` 的同一套安装形状(env 覆盖 → 默认布局;win32 再加
8884
+ * 卸载注册表这一路,覆盖装在非默认盘的情况)。所有 win32 路径都用
8885
+ * `path.win32`、darwin 用 `path.posix` 拼:这些是**数据**规定的分隔符,
8886
+ * 用宿主的 `join` 会在 macOS CI 上产出永不存在的混分隔符路径(docs/WINDOWS.md
8887
+ * 的铁律,`at-rest.ts` 里已有前科)。
8888
+ *
8889
+ * 每个注入参数都是测试缝(RELEASING.md §2.5:断言不能钉住跑测试的机器):
8890
+ * `exists` 决定"这份安装里有没有 SDK",`readRegistryAppPath` 决定注册表答案;
8891
+ * 注册表只在 `platform === 'win32'` 时读——否则 macOS 上的单元测试会去 spawn
8892
+ * 一个本机根本不存在的 `reg.exe`。
8893
+ */
8894
+ function discoverInstalledSdkDir(options = {}) {
8895
+ const platform = options.platform ?? process.platform;
8896
+ const home = options.home ?? homedir();
8897
+ const env = options.env ?? process.env;
8898
+ const exists = options.exists ?? existsSync;
8899
+ const executables = workbuddyAppExecutableCandidates(platform, home, env);
8900
+ if (platform === "win32") {
8901
+ const fromRegistry = (options.readRegistryAppPath ?? windowsRegistryAppExecutable)();
8902
+ if (fromRegistry !== void 0) executables.push(fromRegistry);
8903
+ }
8904
+ const seen = /* @__PURE__ */ new Set();
8905
+ for (const executable of executables) {
8906
+ const dir = installedSdkDirFromExecutable(platform, executable);
8907
+ if (dir === void 0 || seen.has(dir)) continue;
8908
+ seen.add(dir);
8909
+ if (!exists(executable)) continue;
8910
+ if (hasTuringSdkBinding(dir, exists, platform)) return dir;
8911
+ }
8912
+ }
8913
+ /** 掩码:保住 scheme 前缀,其余一律星号。`v3:` 是 SDK 的格式标记,不是内容。 */
8914
+ function maskToken(token) {
8915
+ if (token === "") return "";
8916
+ const colon = token.indexOf(":");
8917
+ return `${colon > 0 && colon <= 8 ? token.slice(0, colon + 1) : ""}${"*".repeat(16)}`;
8918
+ }
8919
+ /**
8920
+ * Run the worker once.
8921
+ *
8922
+ * `env` 只带 SDK 需要的白名单,不整份继承:父进程环境里有插件的凭据与用户配置,
8923
+ * 一个只需要网络和系统 DLL 的子进程没有理由看到它们。
8924
+ */
8925
+ function runWorker(mode, options) {
8926
+ return new Promise((resolve) => {
8927
+ const runtime = process.execPath;
8928
+ const env = {
8929
+ TURING_SDK_DIR: options.dir,
8930
+ TURING_CHANNEL_ID: options.channelId,
8931
+ TURING_PRODUCT_NAME: options.productName,
8932
+ TURING_PRODUCT_VERSION: options.productVersion,
8933
+ TURING_TIMEOUT_MS: String(options.timeoutMs ?? 18e3),
8934
+ TURING_KEYCHAIN_STORAGE: options.keychainStorage === true ? "1" : "0"
8935
+ };
8936
+ for (const name of [
8937
+ "PATH",
8938
+ "SystemRoot",
8939
+ "windir",
8940
+ "TEMP",
8941
+ "TMP",
8942
+ "USERPROFILE",
8943
+ "HOME",
8944
+ "LOCALAPPDATA",
8945
+ "APPDATA",
8946
+ "PROCESSOR_ARCHITECTURE",
8947
+ "NUMBER_OF_PROCESSORS",
8948
+ "LANG",
8949
+ "LC_ALL"
8950
+ ]) {
8951
+ const value = process.env[name];
8952
+ if (value !== void 0) env[name] = value;
8953
+ }
8954
+ if (process.versions.electron !== void 0) env["ELECTRON_RUN_AS_NODE"] = "1";
8955
+ let stdout = "";
8956
+ let stderr = "";
8957
+ let settled = false;
8958
+ const settle = (answer) => {
8959
+ if (settled) return;
8960
+ settled = true;
8961
+ clearTimeout(killer);
8962
+ resolve(answer);
8963
+ };
8964
+ const child = spawn(runtime, [options.worker, mode], {
8965
+ env,
8966
+ windowsHide: true,
8967
+ stdio: [
8968
+ "ignore",
8969
+ "pipe",
8970
+ "pipe"
8971
+ ]
8972
+ });
8973
+ const killer = setTimeout(() => {
8974
+ child.kill("SIGKILL");
8975
+ settle({
8976
+ ok: false,
8977
+ reason: "timeout",
8978
+ message: `worker did not answer within ${options.timeoutMs ?? RUN_TIMEOUT_MS}ms`
8979
+ });
8980
+ }, options.timeoutMs ?? RUN_TIMEOUT_MS);
8981
+ child.stdout?.setEncoding("utf8");
8982
+ child.stdout?.on("data", (chunk) => {
8983
+ stdout += chunk;
8984
+ });
8985
+ child.stderr?.setEncoding("utf8");
8986
+ child.stderr?.on("data", (chunk) => {
8987
+ stderr = `${stderr}${chunk}`.split("\n").slice(-4).join("\n");
8988
+ });
8989
+ child.on("error", (error) => {
8990
+ settle({
8991
+ ok: false,
8992
+ reason: "spawn-failed",
8993
+ message: error.message
8994
+ });
8995
+ });
8996
+ child.on("close", (code) => {
8997
+ const line = stdout.trim().split("\n").filter(Boolean).at(-1);
8998
+ if (line === void 0) {
8999
+ settle({
9000
+ ok: false,
9001
+ reason: "no-output",
9002
+ message: stderr.trim() || `worker exited with code ${String(code)}`
9003
+ });
9004
+ return;
9005
+ }
9006
+ try {
9007
+ settle(JSON.parse(line));
9008
+ } catch {
9009
+ settle({
9010
+ ok: false,
9011
+ reason: "bad-output",
9012
+ message: stderr.trim() || "worker printed no JSON"
9013
+ });
9014
+ }
9015
+ });
9016
+ });
9017
+ }
9018
+ /**
9019
+ * Wire a {@link TuringSdk} into the card.
9020
+ *
9021
+ * `mode` 从设备设置读,不缓存:用户刚切换的那一下必须立刻反映到面板上。
9022
+ */
9023
+ function createDeviceSdkPort(options) {
9024
+ const snap = async () => ({
9025
+ tier: await options.mode(),
9026
+ sdk: await options.sdk.info(),
9027
+ token: options.sdk.tokens.readout()
9028
+ });
9029
+ return {
9030
+ read: snap,
9031
+ async refresh() {
9032
+ await options.sdk.tokens.refresh();
9033
+ return snap();
9034
+ },
9035
+ reveal: () => options.sdk.tokens.reveal()
9036
+ };
9037
+ }
9038
+ /**
9039
+ * Build the SDK handle.
9040
+ *
9041
+ * `version` 默认取插件自称的应用版本(与 `User-Agent` 同源),因为它就是这台机器
9042
+ * 上那个客户端报给上游的版本;`channelId` 与产品名跟桌面端 `product.json` 一致。
9043
+ */
9044
+ function createTuringSdk(options = {}) {
9045
+ const now = options.now ?? (() => Date.now());
9046
+ const worker = options.worker ?? workerPath();
9047
+ const ttlMs = options.ttlMs ?? 6e5;
9048
+ const keepAliveTiming = {
9049
+ ...TURING_KEEP_ALIVE_TIMING,
9050
+ ...options.keepAliveTiming
9051
+ };
9052
+ const platform = options.platform ?? process.platform;
9053
+ const arch = options.arch ?? process.arch;
9054
+ const env = options.env ?? process.env;
9055
+ const exists = options.exists ?? existsSync;
9056
+ const bundle = bundledSdkBundleId(platform, arch);
9057
+ /**
9058
+ * SDK 目录的**解析器**,不是一个常量(作者意见 #1)。
9059
+ *
9060
+ * 卡片上填一个目录、点保存,下一步就该看见 `ready`——所以目录必须在每次
9061
+ * `probe` 时重新问一次,而不是在 `createTuringSdk` 时钉死。构造期钉死会让
9062
+ * "填了但没生效"成为唯一的可能结果,而用户没有任何办法判断是路径错了还是需要
9063
+ * 重启(后者在这条链路上根本不存在)。
9064
+ *
9065
+ * 优先级:显式 `dir`(测试)→ `WORKBUDDY_TURING_SDK_DIR`(排障旁路)→ 卡片上
9066
+ * 手填的值({@link TuringSdkOptions.dirSource})→ 自动发现 → 空串(`missing`)。
9067
+ * 环境变量压过设置的理由写在 `device-profile.ts` 的 `sdkDir` 上。
9068
+ */
9069
+ const resolveDir = async () => {
9070
+ const configured = options.dir ?? env["WORKBUDDY_TURING_SDK_DIR"];
9071
+ if (configured !== void 0 && configured.trim() !== "") return configured.trim();
9072
+ const fromCard = options.dirSource === void 0 ? "" : (await options.dirSource()).trim();
9073
+ if (fromCard !== "") return fromCard;
9074
+ return discoverInstalledSdkDir({
9075
+ platform,
9076
+ home: options.home,
9077
+ env,
9078
+ exists,
9079
+ readRegistryAppPath: options.readRegistryAppPath
9080
+ }) ?? "";
9081
+ };
9082
+ const channelId = options.channelId ?? env["WORKBUDDY_TURING_CHANNEL_ID"] ?? "109144";
9083
+ const productName = options.productName ?? env["WORKBUDDY_TURING_PRODUCT_NAME"] ?? "WorkBuddy";
9084
+ const productVersion = options.productVersion ?? env["WORKBUDDY_TURING_PRODUCT_VERSION"] ?? "5.8.3";
9085
+ const keychainStorage = options.keychainStorage ?? /^(?:1|true)$/u.test(String(env["WORKBUDDY_TURING_KEYCHAIN_STORAGE"] ?? "").trim());
9086
+ let probeCache;
9087
+ let cached;
9088
+ let lastAttemptMs;
9089
+ let lastFailure;
9090
+ /** 最近一次失败的时刻;退避窗口由它算。 */
9091
+ let lastFailureAtMs;
9092
+ let inFlight;
9093
+ /** 后台预热的定时器;`undefined` 表示当前没有排下一轮。 */
9094
+ let keepAliveTimer;
9095
+ let keepAliveActive = false;
9096
+ /** 最近一次 probe 的结论,用来决定"没有 token"时多久再问一次。 */
9097
+ let lastSdkState;
9098
+ const runtimeLabel = process.versions.electron === void 0 ? process.version.replace(/^v/u, "") : `electron ${process.versions.electron}`;
9099
+ const missingInfo = (path) => {
9100
+ const present = path !== "" && exists(path);
9101
+ return {
9102
+ state: present ? "error" : "missing",
9103
+ bundle,
9104
+ path,
9105
+ platform,
9106
+ arch,
9107
+ runtime: runtimeLabel,
9108
+ reason: present ? "SDK directory exists but the native binding was not found" : `no installed WorkBuddy desktop SDK detected on ${bundle}; install the desktop app or set ${TURING_SDK_DIR_ENV}`
9109
+ };
9110
+ };
9111
+ async function probe() {
9112
+ const at = now();
9113
+ const dir = await resolveDir();
9114
+ if (probeCache !== void 0 && probeCache.path === dir && at - probeCache.at < PROBE_CACHE_MS) return probeCache.info;
9115
+ let info;
9116
+ if (dir === "" || !hasTuringSdkBinding(dir, exists, platform)) info = missingInfo(dir);
9117
+ else {
9118
+ const answer = await runWorker("probe", {
9119
+ dir,
9120
+ worker,
9121
+ channelId,
9122
+ productName,
9123
+ productVersion,
9124
+ timeoutMs: 15e3,
9125
+ keychainStorage
9126
+ });
9127
+ const supported = answer.ok === true && answer.supported === true;
9128
+ info = {
9129
+ state: supported ? "ready" : answer.ok === true ? "unsupported" : "error",
9130
+ bundle,
9131
+ path: dir,
9132
+ platform,
9133
+ arch,
9134
+ runtime: answer.node ?? runtimeLabel,
9135
+ ...supported ? {} : { reason: answer.loadError ?? answer.message ?? answer.reason ?? "sdk reported unsupported" }
9136
+ };
9137
+ }
9138
+ probeCache = {
9139
+ at,
9140
+ path: dir,
9141
+ info
9142
+ };
9143
+ return info;
9144
+ }
9145
+ function readout() {
9146
+ const at = now();
9147
+ if (cached === void 0) return {
9148
+ state: "idle",
9149
+ masked: "",
9150
+ length: 0,
9151
+ ...lastAttemptMs === void 0 ? {} : { lastAttemptMs },
9152
+ ...lastFailure === void 0 ? {} : { reason: lastFailure }
9153
+ };
9154
+ const ageMs = at - cached.fetchedAtMs;
9155
+ const expired = ageMs > ttlMs;
9156
+ const tooOld = ageMs > TURING_TOKEN_STALE_MS;
9157
+ const failedSinceFetch = lastFailure !== void 0 && lastAttemptMs !== void 0 && lastAttemptMs >= cached.fetchedAtMs;
9158
+ return {
9159
+ state: tooOld ? "unavailable" : expired || failedSinceFetch ? "stale" : "ok",
9160
+ masked: maskToken(cached.token),
9161
+ length: cached.token.length,
9162
+ fetchedAtMs: cached.fetchedAtMs,
9163
+ ...lastAttemptMs === void 0 ? {} : { lastAttemptMs },
9164
+ ...expired || failedSinceFetch ? { reason: lastFailure ?? `older than ${Math.round(ttlMs / 6e4)}m` } : {}
9165
+ };
9166
+ }
9167
+ async function fetchOnce() {
9168
+ lastAttemptMs = now();
9169
+ const info = await probe();
9170
+ lastSdkState = info.state;
9171
+ if (info.state !== "ready") {
9172
+ lastFailure = info.reason ?? `sdk is ${info.state}`;
9173
+ lastFailureAtMs = lastAttemptMs;
9174
+ return;
9175
+ }
9176
+ const answer = await runWorker("token", {
9177
+ dir: info.path,
9178
+ worker,
9179
+ channelId,
9180
+ productName,
9181
+ productVersion,
9182
+ keychainStorage
9183
+ });
9184
+ const token = typeof answer.token === "string" ? answer.token.trim() : "";
9185
+ if (answer.ok !== true || token === "") {
9186
+ lastFailure = answer.message ?? answer.reason ?? "sdk returned no token";
9187
+ lastFailureAtMs = lastAttemptMs;
9188
+ return;
9189
+ }
9190
+ cached = {
9191
+ token,
9192
+ fetchedAtMs: now()
9193
+ };
9194
+ lastFailure = void 0;
9195
+ lastFailureAtMs = void 0;
9196
+ return token;
9197
+ }
9198
+ async function current() {
9199
+ const at = now();
9200
+ if (cached !== void 0 && at - cached.fetchedAtMs <= ttlMs) return cached.token;
9201
+ if (lastFailureAtMs !== void 0 && at - lastFailureAtMs < RETRY_BACKOFF_MS) return cached !== void 0 && at - cached.fetchedAtMs <= TURING_TOKEN_STALE_MS ? cached.token : void 0;
9202
+ if (inFlight !== void 0) return inFlight;
9203
+ inFlight = fetchOnce().finally(() => {
9204
+ inFlight = void 0;
9205
+ });
9206
+ const token = await inFlight;
9207
+ if (token !== void 0) return token;
9208
+ if (cached !== void 0 && now() - cached.fetchedAtMs <= TURING_TOKEN_STALE_MS) return cached.token;
9209
+ }
9210
+ /**
9211
+ * 预热一次:到期前换新,其余情况什么都不做。
9212
+ *
9213
+ * 与 {@link current} 的分工是这条需求的核心。`current()` 只在**请求要发出去**时
9214
+ * 被调用,所以一个空闲的进程永远不会刷新 token——面板看到的永远是"已加载、
9215
+ * 没取过",而用户无法分辨那是"SDK 没工作"还是"还没轮到它工作"。预热在启动时
9216
+ * 与每次到期前跑,让"现在这枚 token 是什么"随时可以回答。
9217
+ *
9218
+ * 幂等:不算到期就返回,失败退避窗口内也返回,已有请求在飞就等它。
9219
+ */
9220
+ async function warm() {
9221
+ const at = now();
9222
+ const failedSinceFetch = cached !== void 0 && lastFailureAtMs !== void 0 && lastFailureAtMs >= cached.fetchedAtMs;
9223
+ if (cached !== void 0 && at - cached.fetchedAtMs < ttlMs - keepAliveTiming.leadMs && !failedSinceFetch) return;
9224
+ if (lastFailureAtMs !== void 0 && at - lastFailureAtMs < RETRY_BACKOFF_MS) return;
9225
+ if (inFlight !== void 0) {
9226
+ await inFlight;
9227
+ return;
9228
+ }
9229
+ inFlight = fetchOnce().finally(() => {
9230
+ inFlight = void 0;
9231
+ });
9232
+ await inFlight;
9233
+ }
9234
+ function nextDelayMs() {
9235
+ return nextAutoRefreshDelayMs({
9236
+ nowMs: now(),
9237
+ ttlMs,
9238
+ ...cached === void 0 ? {} : { fetchedAtMs: cached.fetchedAtMs },
9239
+ ...lastFailureAtMs === void 0 ? {} : { lastFailureAtMs },
9240
+ ...lastSdkState === void 0 ? {} : { sdkState: lastSdkState }
9241
+ }, keepAliveTiming);
9242
+ }
9243
+ /**
9244
+ * 一轮预热:取一次,然后按 {@link nextDelayMs} 排下一轮。
9245
+ *
9246
+ * 单链而不是 `setInterval`:间隔不是常数(成功是"到 TTL 前 15 秒",失败是 60 秒,
9247
+ * SDK 不在这台机器上是 5 分钟),而且每一轮都要按**当下**的时间重算,否则系统
9248
+ * 休眠回来后会把积压的 tick 一次放出来。
9249
+ */
9250
+ async function tick() {
9251
+ if (!keepAliveActive) return;
9252
+ try {
9253
+ await warm();
9254
+ } catch {}
9255
+ if (!keepAliveActive) return;
9256
+ keepAliveTimer = setTimeout(() => {
9257
+ tick();
9258
+ }, nextDelayMs());
9259
+ keepAliveTimer.unref?.();
9260
+ }
9261
+ return {
9262
+ info: probe,
9263
+ startAutoRefresh() {
9264
+ if (keepAliveActive) return;
9265
+ keepAliveActive = true;
9266
+ tick();
9267
+ },
9268
+ stopAutoRefresh() {
9269
+ keepAliveActive = false;
9270
+ if (keepAliveTimer !== void 0) {
9271
+ clearTimeout(keepAliveTimer);
9272
+ keepAliveTimer = void 0;
9273
+ }
9274
+ },
9275
+ tokens: {
9276
+ current,
9277
+ readout,
9278
+ reveal: current,
9279
+ /**
9280
+ * Force a refetch — but **keep** whatever is cached until the new value
9281
+ * arrives. 清空再取会让"手动刷新失败"顺手抹掉一枚还在宽限期内可用的
9282
+ * token,那正好是用户点刷新想避免的结果。
9283
+ */
9284
+ async refresh() {
9285
+ if (inFlight !== void 0) return inFlight.then(() => readout());
9286
+ inFlight = fetchOnce().finally(() => {
9287
+ inFlight = void 0;
9288
+ });
9289
+ await inFlight;
9290
+ return readout();
9291
+ }
9292
+ }
9293
+ };
9294
+ }
7562
9295
  //#endregion
7563
9296
  //#region src/pi-ai-runtime.ts
7564
9297
  /**
@@ -7932,7 +9665,7 @@ function describeRosterSeenPayload(raw) {
7932
9665
  //#endregion
7933
9666
  //#region src/version.ts
7934
9667
  /** The npm package version this build was produced from. */
7935
- const WORKBUDDY_CONNECT_VERSION = "5.15.2";
9668
+ const WORKBUDDY_CONNECT_VERSION = "5.17.0";
7936
9669
  //#endregion
7937
9670
  //#region src/host-heartbeat.ts
7938
9671
  /**
@@ -8143,4 +9876,4 @@ async function clearHostHeartbeat() {
8143
9876
  await rm(workbuddyHostHeartbeatPath(), { force: true });
8144
9877
  }
8145
9878
  //#endregion
8146
- export { parseCreditMultiplier as $, resolveDshHome as $t, isEncryptedCredentialError as A, pickMediaModel as At, WorkBuddyCredentialRejectedError as B, deriveAtRestKey as Bt, WorkBuddyCredentialStore as C, IMAGE_TAG_TEXT_TO_IMAGE as Ct, defaultDesktopAuthDirs as D, imageMimeForPath as Dt, defaultDesktopAuthCandidates as E, imageDataUrl as Et, workbuddyAccountId as F, NATIVE_MODALITY_BY_MODEL_ID as Ft, forceNeutralHead as G, isEncryptedFieldWrapper as Gt, channelGateMemberOf as H, fetchAtRestKeyPayload as Ht, workbuddyOwnAuthPath as I, imageDefaultFor as It, isCredentialRejectedError as J, macosNestedAppBundles as Jt, isContextTooLongBody as K, isWorkbuddyBundle as Kt, CONTEXT_OVERFLOW_MARKER as L, nativeModalityOf as Lt, legacyWorkbuddyOwnAuthPath as M, parseQueueAnswer as Mt, parseWorkBuddyAuth as N, queueNoticeText as Nt, defaultDesktopAuthPath as O, isBareBase64Image as Ot, preferredAccountName as P, pruneTempDir as Pt, openingEvidenceOfBody as Q, hostPeersInfo as Qt, CREDENTIAL_REJECTED_CODE as R, WORKBUDDY_APP_EXECUTABLE_ENV as Rt, WORKBUDDY_AUTH_FILE_ENV as S, IMAGE_TAG_IMAGE_TO_IMAGE as St, authFileName as T, WorkBuddyImageError as Tt, classifyUpstreamError as U, findWorkbuddyAppExecutable as Ut, WorkBuddyUpstreamClient as V, deriveAtRestKeyId as Vt, declaredTools as W, findWorkbuddyAppExecutableWithSource as Wt, knownRegionOf as X, readAtRestKey as Xt, isFirstMessageGateBody as Y, openEncryptedField as Yt, modelIdOfBody as Z, workbuddyAppExecutableCandidates as Zt, deriveCatalog as _, WorkBuddyVideoError as _t, readHostHeartbeat as a, requestEvidenceOf as at, ENCRYPTED_CREDENTIAL_CODE as b, resolveVideoParams as bt, WORKBUDDY_CONNECT_VERSION as c, REFUSES_OFF_MODEL_IDS as ct, rosterSeenPath as d, offDefaultFor as dt, withFileLock as en, parseReasoning as et, piAiRuntimeInfo as f, offRefused as ft, applyContextBudgets as g, VIDEO_TAG_TEXT_TO_VIDEO as gt, WorkBuddyCatalog as h, VIDEO_TAG_IMAGE_TO_VIDEO as ht, processStartTimeMs as i, regionOf as it, isVaultAccountId as j, sniffImageMime as jt, hasEncryptedCredentialFields as k, parseImageDataUrl as kt, createFileRosterSeenStore as l, defaultOffModelIds as lt, FALLBACK_WORKBUDDY_MODELS_GLOBAL as m, withEffectiveOff as mt, clearHostHeartbeat as n, perturbChannelFingerprints as nt, workbuddyHostHeartbeatPath as o, rewriteSessionTitleModel as ot, FALLBACK_WORKBUDDY_MODELS as p, recordRefusal as pt, isConversationIdGateBody as q, macosBundleExecutable as qt, isHeartbeatProcessAlive as r, prepareChatBody as rt, writeHostHeartbeat as s, attachBusyLevels as st, WORKBUDDY_HOST_HEARTBEAT_FILENAME as t, writeFileAtomic as tn, parseUpstreamModel as tt, describeRosterSeenPayload as u, lastRefusalFor as ut, fallbackModelsFor as v, parseSupportedSecondsRange as vt, WorkBuddyEncryptedCredentialError as w, MAX_INPUT_IMAGE_BYTES as wt, WORKBUDDY_AUTH_FILENAME as x, DEFAULT_IMAGE_SIZE as xt, withoutRouters as y, pickVideoModel as yt, WORKBUDDY_FALLBACK_SYSTEM_PROMPT as z, clearAtRestKeyCache as zt };
9879
+ export { WorkBuddyCredentialRejectedError as $, readDeviceTokenFile as $t, WORKBUDDY_AUTH_FILENAME as A, VIDEO_TAG_TEXT_TO_VIDEO as At, isEncryptedCredentialError as B, imageDataUrl as Bt, FALLBACK_WORKBUDDY_MODELS_GLOBAL as C, writeFileAtomic as Cn, defaultOffModelIds as Ct, fallbackModelsFor as D, recordRefusal as Dt, deriveCatalog as E, offRefused as Et, authFileName as F, DEFAULT_IMAGE_SIZE as Ft, workbuddyAccountId as G, sniffImageMime as Gt, legacyWorkbuddyOwnAuthPath as H, isBareBase64Image as Ht, defaultDesktopAuthCandidates as I, IMAGE_TAG_IMAGE_TO_IMAGE as It, APP_VERSION as J, pruneTempDir as Jt, workbuddyOwnAuthPath as K, parseQueueAnswer as Kt, defaultDesktopAuthDirs as L, IMAGE_TAG_TEXT_TO_IMAGE as Lt, WORKBUDDY_VAULT_DIRNAME as M, parseSupportedSecondsRange as Mt, WorkBuddyCredentialStore as N, pickVideoModel as Nt, withoutRouters as O, withEffectiveOff as Ot, WorkBuddyEncryptedCredentialError as P, resolveVideoParams as Pt, WORKBUDDY_FALLBACK_SYSTEM_PROMPT as Q, WORKBUDDY_DEVICE_TOKEN_FILE_ENV as Qt, defaultDesktopAuthPath as R, MAX_INPUT_IMAGE_BYTES as Rt, FALLBACK_WORKBUDDY_MODELS as S, withFileLock as Sn, REFUSES_OFF_MODEL_IDS as St, applyContextBudgets as T, offDefaultFor as Tt, parseWorkBuddyAuth as U, parseImageDataUrl as Ut, isVaultAccountId as V, imageMimeForPath as Vt, preferredAccountName as W, pickMediaModel as Wt, CREDENTIAL_REJECTED_CODE as X, imageDefaultFor as Xt, CONTEXT_OVERFLOW_MARKER as Y, NATIVE_MODALITY_BY_MODEL_ID as Yt, DEFAULT_WIRE_PROFILE as Z, nativeModalityOf as Zt, isDeviceMode as _, openEncryptedField as _n, prepareChatBody as _t, readHostHeartbeat as a, protectCredentialDirectory as an, forceNeutralHead as at, saveDeviceSdkSettings as b, hostPeersInfo as bn, rewriteSessionTitleModel as bt, WORKBUDDY_CONNECT_VERSION as c, deriveAtRestKey as cn, isCredentialRejectedError as ct, rosterSeenPath as d, findWorkbuddyAppExecutable as dn, modelIdOfBody as dt, ensureDeviceSalt as en, WorkBuddyUpstreamClient as et, piAiRuntimeInfo as f, findWorkbuddyAppExecutableWithSource as fn, openingEvidenceOfBody as ft, describeDerivedDevices as g, macosNestedAppBundles as gn, perturbChannelFingerprints as gt, createDeviceProfileLookup as h, macosBundleExecutable as hn, parseUpstreamModel as ht, processStartTimeMs as i, inspectCredentialDirectory as in, describeRequestHeaderNames as it, WORKBUDDY_AUTH_FILE_ENV as j, WorkBuddyVideoError as jt, ENCRYPTED_CREDENTIAL_CODE as k, VIDEO_TAG_IMAGE_TO_VIDEO as kt, createFileRosterSeenStore as l, deriveAtRestKeyId as ln, isFirstMessageGateBody as lt, createTuringSdk as m, isWorkbuddyBundle as mn, parseReasoning as mt, clearHostHeartbeat as n, deriveDeviceId as nn, classifyUpstreamError as nt, workbuddyHostHeartbeatPath as o, WORKBUDDY_APP_EXECUTABLE_ENV as on, isContextTooLongBody as ot, createDeviceSdkPort as p, isEncryptedFieldWrapper as pn, parseCreditMultiplier as pt, workbuddyVaultDir as q, queueNoticeText as qt, isHeartbeatProcessAlive as r, isDeviceId as rn, declaredTools as rt, writeHostHeartbeat as s, clearAtRestKeyCache as sn, isConversationIdGateBody as st, WORKBUDDY_HOST_HEARTBEAT_FILENAME as t, readDeviceSalt as tn, channelGateMemberOf as tt, describeRosterSeenPayload as u, fetchAtRestKeyPayload as un, knownRegionOf as ut, readDeviceSettings as v, readAtRestKey as vn, regionOf as vt, WorkBuddyCatalog as w, lastRefusalFor as wt, setDeviceMode as x, resolveDshHome as xn, attachBusyLevels as xt, saveDeviceProfile as y, workbuddyAppExecutableCandidates as yn, requestEvidenceOf as yt, hasEncryptedCredentialFields as z, WorkBuddyImageError as zt };