dsh-go-codearts 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,334 @@
1
+ import { existsSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { execFileSync, spawn } from "node:child_process";
5
+ import { fileURLToPath } from "node:url";
6
+ //#region src/keeper.ts
7
+ /**
8
+ * 凭证守护进程:把 refresh_token 交给一个**常驻子进程**去续期。
9
+ *
10
+ * ## 为什么需要它
11
+ *
12
+ * CodeArts 签发的 STS token 有效期是**固定的 2 小时**(实测,见 `auth.ts` 的
13
+ * `REFRESH_SKEW_MS` 注释),而 refresh_token 有 30 天。插件自己的 `keepAliveLoop`
14
+ * 只在 DSH 运行时能跑 —— 用户晚上关掉 DSH,凭证两小时后就过期,第二天打开又要重新
15
+ * 登录。要跨过「DSH 没开」这段时间,续期动作必须发生在 DSH 之外,所以这里起一个
16
+ * 独立的常驻进程。
17
+ *
18
+ * ## 进程形态
19
+ *
20
+ * DSH Desktop 是 Electron,宿主 exe 可以直接当 Node 用:设置
21
+ * `ELECTRON_RUN_AS_NODE=1` 后启动它就是 node 24.21.0(已实测)。但**优先用宿主自带的
22
+ * 真 node.exe**(`resources/runtime/<runtime>/dependencies/node/bin/node.exe`)—— 宿主 exe 的
23
+ * 进程名是 `DeepSeek Harness.exe`,会被更新安装器当成「应用还在跑」而挡住更新
24
+ * (见 `bundledNodeExecutable`)。两者都不依赖用户装没装 node,也不引入任何原生依赖。
25
+ * 启动后 `detached` + `unref` + `stdio:'ignore'`,DSH 退出它不跟着退出(同样已实测)。
26
+ *
27
+ * ## 谁有权续期(重要)
28
+ *
29
+ * refresh_token 是**一次性的**:刷一次就轮换,另一份旧的就作废。如果守护进程和 DSH
30
+ * 插件同时续期,后刷的那次会拿着已作废的 token 失败,并把账号写成 `stale` —— 正是
31
+ * 「隔天就要重新登录」这个症状的成因之一。所以两者**互斥**:
32
+ *
33
+ * - 守护进程活着且心跳新鲜时,**由它独占续期**,插件自己不再刷,只从磁盘重读它写回
34
+ * 的结果;
35
+ * - 守护进程不在(被 kill、崩溃、从未开启)时,插件恢复自己刷。
36
+ *
37
+ * 判据就是心跳文件 `~/.dsh/.codearts-keeper.json` 的 `heartbeatAt` 与那个 `pid` 是否
38
+ * 还在 —— 光看文件不够,进程被 kill 时来不及写任何东西,文件会留成「看起来很新鲜」。
39
+ *
40
+ * @module dsh-codearts/keeper
41
+ */
42
+ /** 心跳超过这么久没更新,就认为守护进程已经不在(它每 30 秒写一次)。 */
43
+ const KEEPER_STALE_MS = 9e4;
44
+ /** Windows 上探活要起一次 tasklist:给足超时,卡住就按「活着」处理。 */
45
+ const PID_PROBE_TIMEOUT_MS = 5e3;
46
+ /** 心跳写入间隔。 */
47
+ const KEEPER_HEARTBEAT_MS = 3e4;
48
+ /** 守护进程的续期节奏:每 20 分钟过一遍,与插件里的 `KEEP_ALIVE_INTERVAL_MS` 对齐。 */
49
+ const KEEPER_TICK_MS = 12e5;
50
+ function dshHome() {
51
+ return process.env.DSH_HOME ?? join(homedir(), ".dsh");
52
+ }
53
+ /** 心跳/状态文件:`~/.dsh/.codearts-keeper.json`。 */
54
+ function keeperStatePath(home) {
55
+ return join(home ?? dshHome(), ".codearts-keeper.json");
56
+ }
57
+ /** 守护进程自己的日志(stdout 被 ignore 了,出问题只能看这里)。 */
58
+ function keeperLogPath(home) {
59
+ return join(home ?? dshHome(), ".codearts-keeper.log");
60
+ }
61
+ /** 读状态文件;读不到/格式不对都返回 undefined(不抛)。 */
62
+ function readKeeperState(home) {
63
+ try {
64
+ const parsed = JSON.parse(readFileSync(keeperStatePath(home), "utf8"));
65
+ if (typeof parsed.pid !== "number" || typeof parsed.heartbeatAt !== "number") return void 0;
66
+ return {
67
+ version: 1,
68
+ pid: parsed.pid,
69
+ startedAt: typeof parsed.startedAt === "number" ? parsed.startedAt : parsed.heartbeatAt,
70
+ heartbeatAt: parsed.heartbeatAt,
71
+ ...parsed.pluginVersion === void 0 ? {} : { pluginVersion: parsed.pluginVersion },
72
+ ...parsed.lastPass === void 0 ? {} : { lastPass: parsed.lastPass }
73
+ };
74
+ } catch {
75
+ return;
76
+ }
77
+ }
78
+ function writeKeeperState(state, home) {
79
+ try {
80
+ writeFileSync(keeperStatePath(home), JSON.stringify(state, null, 2), { mode: 384 });
81
+ } catch {}
82
+ }
83
+ /** 进程还在吗。信号 0 只探活,不真的发信号(Windows 上同样适用)。 */
84
+ /**
85
+ * 某个 pid 是否还活着。
86
+ *
87
+ * **不能用 `process.kill(pid, 0)`**:那个「发信号 0 只是探活」的约定只在 POSIX 上
88
+ * 成立。Windows 上 Node 的实现不看信号值,直接 `TerminateProcess` —— 探活会把目标
89
+ * 进程**当场杀掉**。这里的调用方是 `keeperStats()`,探的正是守护进程本身,用错实现
90
+ * 就成了「插件每查一次状态就杀一次 keeper」,而 keeper 一死插件就再也不自己续期。
91
+ */
92
+ function pidAlive(pid) {
93
+ if (!Number.isInteger(pid) || pid <= 0) return false;
94
+ if (pid === process.pid) return true;
95
+ if (process.platform !== "win32") try {
96
+ process.kill(pid, 0);
97
+ return true;
98
+ } catch (error) {
99
+ return error?.code === "EPERM";
100
+ }
101
+ try {
102
+ const out = execFileSync("tasklist", [
103
+ "/FI",
104
+ `PID eq ${pid}`,
105
+ "/NH"
106
+ ], {
107
+ encoding: "utf8",
108
+ stdio: [
109
+ "ignore",
110
+ "pipe",
111
+ "ignore"
112
+ ],
113
+ timeout: PID_PROBE_TIMEOUT_MS,
114
+ windowsHide: true
115
+ });
116
+ return new RegExp(`\\b${pid}\\b`).test(out);
117
+ } catch {
118
+ return true;
119
+ }
120
+ }
121
+ /** 状态文件的 mtime(用来判断账号文档是不是被守护进程改过)。 */
122
+ function keeperStats(home) {
123
+ const state = readKeeperState(home);
124
+ if (state === void 0) return { alive: false };
125
+ return {
126
+ alive: Date.now() - state.heartbeatAt <= 9e4 && pidAlive(state.pid),
127
+ state
128
+ };
129
+ }
130
+ /**
131
+ * 下一个 tick 最晚会在什么时候发生。
132
+ *
133
+ * 守护进程每 `KEEPER_TICK_MS` 跑一轮,但那一刻没在跑不代表它死了 —— 两轮之间就是
134
+ * 20 分钟的空窗。插件要判断「这一轮的续期该由谁来负责」,必须看这个时间点,而不是
135
+ * 只看 `alive`。
136
+ *
137
+ * 补了一点余量(`KEEPER_STALE_MS`):tick 本身要读文档、逐号发请求,慢的时候能拖上
138
+ * 几十秒,卡在边界上会让插件抢在 keeper 落库前就把号刷了 —— 那正是要避免的双刷。
139
+ */
140
+ function keeperNextPassAt(state) {
141
+ if (state === void 0) return 0;
142
+ return (state.lastPass?.at ?? state.startedAt) + KEEPER_TICK_MS + KEEPER_STALE_MS;
143
+ }
144
+ /** 守护进程的脚本路径:和当前 bundle 同目录的 `keeper-main.mjs`(tsdown 入口名)。 */
145
+ function keeperScriptPath() {
146
+ return fileURLToPath(new URL("./keeper-main.mjs", import.meta.url));
147
+ }
148
+ /**
149
+ * 宿主自带的 node(`resources/runtime/<runtime>/dependencies/node/bin/node.exe`)。
150
+ *
151
+ * 为什么不直接用 `process.execPath`:那是宿主 exe,keeper 的进程名就成了
152
+ * `DeepSeek Harness.exe`。DSH 的更新安装器会枚举同名进程判断「应用是否已关闭」,
153
+ * 看到 keeper 就认为应用还在跑 —— 更新在十秒左右中止,而且安装器不会把应用拉回来
154
+ * (2026-11-16 实测:装 0.2.2-rc.3 时两次都是被这个挡住的)。
155
+ *
156
+ * 运行时目录名会随版本变(`primary-runtime` / `dsh-primary-runtime`),所以按目录枚举,
157
+ * 不把某一版的名字写死。拿不到就返回 undefined,由调用方退回宿主 exe。
158
+ */
159
+ function bundledNodeExecutable() {
160
+ const name = process.platform === "win32" ? "node.exe" : "node";
161
+ const roots = [];
162
+ const resources = process.resourcesPath;
163
+ if (typeof resources === "string" && resources !== "") roots.push(resources);
164
+ roots.push(join(dirname(process.execPath), "resources"));
165
+ for (const root of roots) {
166
+ const runtime = join(root, "runtime");
167
+ let runtimes;
168
+ try {
169
+ runtimes = readdirSync(runtime);
170
+ } catch {
171
+ continue;
172
+ }
173
+ for (const runtimeName of runtimes) {
174
+ const candidate = join(runtime, runtimeName, "dependencies", "node", "bin", name);
175
+ if (existsSync(candidate)) return candidate;
176
+ }
177
+ }
178
+ }
179
+ /**
180
+ * 拿 `ELECTRON_RUN_AS_NODE` 这条路启动 node 所需的 exe。
181
+ *
182
+ * 优先级:宿主自己给的 `DSH_DESKTOP_NODE_EXECUTABLE`(Desktop 注入,最准)→
183
+ * 宿主自带的 node.exe(见 `bundledNodeExecutable`,进程名不会撞 DSH)→
184
+ * `process.execPath`(Electron 自己或普通 node 都适用)。
185
+ */
186
+ function nodeLauncher() {
187
+ const desktop = process.env.DSH_DESKTOP_NODE_EXECUTABLE;
188
+ if (desktop !== void 0 && desktop !== "" && existsSync(desktop)) return {
189
+ command: desktop,
190
+ env: {
191
+ ...process.env,
192
+ ELECTRON_RUN_AS_NODE: "1"
193
+ }
194
+ };
195
+ const bundled = bundledNodeExecutable();
196
+ if (bundled !== void 0) return {
197
+ command: bundled,
198
+ env: { ...process.env }
199
+ };
200
+ return {
201
+ command: process.execPath,
202
+ env: {
203
+ ...process.env,
204
+ ELECTRON_RUN_AS_NODE: "1"
205
+ }
206
+ };
207
+ }
208
+ /**
209
+ * 这是 DSH 更新安装器在 `%TEMP%` 里建的插件目录吗。
210
+ *
211
+ * 安装器(NSIS)一启动就把自己签名的 `window-frame.dll` 解到 `%TEMP%\ns*.tmp\`。
212
+ * 用「目录名 + 那个 dll」两条一起判,用户装别的软件留下同名目录也不会误伤。
213
+ */
214
+ function isDshInstallerTempDir(path) {
215
+ if (!/^ns[\w.-]{2,}\.tmp$/i.test(basename(path))) return false;
216
+ return existsSync(join(path, "window-frame.dll"));
217
+ }
218
+ /** 「让路」标记:keeper 为更新安装器主动退出时写,插件据此不把开关关掉。 */
219
+ function keeperHandoffPath(home) {
220
+ return join(home ?? dshHome(), ".codearts-keeper.handoff");
221
+ }
222
+ function writeKeeperHandoff(reason, home) {
223
+ try {
224
+ writeFileSync(keeperHandoffPath(home), JSON.stringify({
225
+ at: Date.now(),
226
+ reason
227
+ }), { mode: 384 });
228
+ } catch {}
229
+ }
230
+ /** 最近发生过一次「为更新让路」的退出吗(默认 15 分钟内)。 */
231
+ function keeperHandoffRecent(home, maxAgeMs = 9e5) {
232
+ try {
233
+ const parsed = JSON.parse(readFileSync(keeperHandoffPath(home), "utf8"));
234
+ return typeof parsed.at === "number" && Date.now() - parsed.at <= maxAgeMs;
235
+ } catch {
236
+ return false;
237
+ }
238
+ }
239
+ function clearKeeperHandoff(home) {
240
+ try {
241
+ if (existsSync(keeperHandoffPath(home))) unlinkSync(keeperHandoffPath(home));
242
+ } catch {}
243
+ }
244
+ /**
245
+ * 起一个守护进程。已经在跑就返回现有的那个(幂等,不重复起)。
246
+ *
247
+ * `detached` + `unref` + `stdio:'ignore'` 三件套缺一不可:少了任何一个,DSH 退出时
248
+ * 子进程会被一起带走(Windows 上尤其明显),守护也就没有意义了。
249
+ */
250
+ function spawnKeeper(options) {
251
+ if (!existsSync(options.scriptPath)) return {
252
+ ok: false,
253
+ reason: `keeper script missing: ${options.scriptPath}`
254
+ };
255
+ const running = keeperStats();
256
+ if (running.alive && running.state !== void 0) return {
257
+ ok: true,
258
+ pid: running.state.pid
259
+ };
260
+ const { command, env } = nodeLauncher();
261
+ try {
262
+ const child = spawn(command, [
263
+ options.scriptPath,
264
+ "--home",
265
+ dshHome()
266
+ ], {
267
+ detached: true,
268
+ stdio: "ignore",
269
+ windowsHide: true,
270
+ env: {
271
+ ...env,
272
+ ...options.pluginVersion === void 0 ? {} : { DSH_CODEARTS_PLUGIN_VERSION: options.pluginVersion }
273
+ }
274
+ });
275
+ child.unref();
276
+ if (child.pid === void 0) return {
277
+ ok: false,
278
+ reason: "spawn produced no pid"
279
+ };
280
+ return {
281
+ ok: true,
282
+ pid: child.pid
283
+ };
284
+ } catch (error) {
285
+ return {
286
+ ok: false,
287
+ reason: error instanceof Error ? error.message : String(error)
288
+ };
289
+ }
290
+ }
291
+ /**
292
+ * 停掉守护进程。
293
+ *
294
+ * 先礼后兵:先请它自己退(它能顺手把状态文件标成已停),等一小会儿还在就直杀。
295
+ * 不管走哪条路,最后都把状态文件删掉 —— 留着它只会让下一次启动以为「已经在跑」。
296
+ */
297
+ async function stopKeeper(home) {
298
+ const state = readKeeperState(home);
299
+ if (state === void 0 || !pidAlive(state.pid)) {
300
+ clearKeeperState(home);
301
+ return { ok: true };
302
+ }
303
+ try {
304
+ writeFileSync(join(home ?? dshHome(), ".codearts-keeper.stop"), String(Date.now()), { mode: 384 });
305
+ } catch {}
306
+ const deadline = Date.now() + 3e3;
307
+ while (Date.now() < deadline && pidAlive(state.pid)) await new Promise((resolve) => setTimeout(resolve, 100));
308
+ if (pidAlive(state.pid)) try {
309
+ process.kill(state.pid);
310
+ } catch (error) {
311
+ if (error?.code !== "ESRCH") return {
312
+ ok: false,
313
+ pid: state.pid,
314
+ reason: error instanceof Error ? error.message : String(error)
315
+ };
316
+ }
317
+ clearKeeperState(home);
318
+ return {
319
+ ok: true,
320
+ pid: state.pid
321
+ };
322
+ }
323
+ /** 删掉状态文件与停止标记。 */
324
+ function clearKeeperState(home) {
325
+ for (const path of [keeperStatePath(home), join(home ?? dshHome(), ".codearts-keeper.stop")]) try {
326
+ if (existsSync(path)) unlinkSync(path);
327
+ } catch {}
328
+ }
329
+ /** 停止标记存在吗(守护进程每轮自查)。 */
330
+ function stopRequested(home) {
331
+ return existsSync(join(home ?? dshHome(), ".codearts-keeper.stop"));
332
+ }
333
+ //#endregion
334
+ export { writeKeeperState as _, clearKeeperState as a, keeperLogPath as c, keeperStatePath as d, keeperStats as f, writeKeeperHandoff as g, stopRequested as h, clearKeeperHandoff as i, keeperNextPassAt as l, stopKeeper as m, KEEPER_STALE_MS as n, isDshInstallerTempDir as o, spawnKeeper as p, KEEPER_TICK_MS as r, keeperHandoffRecent as s, KEEPER_HEARTBEAT_MS as t, keeperScriptPath as u };
@@ -0,0 +1,304 @@
1
+ import { d as refreshLockPath, f as withRefreshLock, h as refreshToken, i as codeartsAccountsPath, l as readAccountDocument, m as defaultLoginConfig, p as OAuthTokenError, u as writeJsonAtomic } from "./auth-T5qnGSPp.mjs";
2
+ import { _ as writeKeeperState, a as clearKeeperState, c as keeperLogPath, d as keeperStatePath, f as keeperStats, g as writeKeeperHandoff, h as stopRequested, i as clearKeeperHandoff, o as isDshInstallerTempDir, r as KEEPER_TICK_MS, t as KEEPER_HEARTBEAT_MS } from "./keeper-BWHQDFAh.mjs";
3
+ import { appendFileSync, existsSync, unlinkSync, watch } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ //#region src/keeper-main.ts
6
+ /**
7
+ * dsh-codearts 凭证守护进程(独立入口,由 DSH 用 `ELECTRON_RUN_AS_NODE=1` 拉起)。
8
+ *
9
+ * 它只做一件事:**在 DSH 关掉之后,继续把 refresh_token 续下去**,这样第二天打开
10
+ * DSH 不必重新登录。DSH 开着的时候它同样活着,但续期的**独占权**在它手里
11
+ * (见 `keeper.ts` 的模块注释:refresh_token 一次性,两边同时刷会把号刷成 stale)。
12
+ *
13
+ * 进程形态上的三条硬要求,缺一条这个功能就不成立:
14
+ *
15
+ * 1. `detached: true` —— 不跟着 DSH 的进程组一起被回收;
16
+ * 2. `child.unref()` —— 父进程的事件循环不为它续命;
17
+ * 3. `stdio: 'ignore'` —— 父进程退出后管道断了,子孙进程写 stdout 会 EPIPE。
18
+ *
19
+ * 三条都在 `keeper.ts` 的 `spawnKeeper` 里。本文件只被当作独立入口跑,
20
+ * **不要从插件主流程 import 它**(import 会顺手执行监听逻辑)。
21
+ *
22
+ * @module dsh-codearts/keeper-main
23
+ */
24
+ /** 距过期不足这么久就续(与服务端插件保持一致)。 */
25
+ const REFRESH_SKEW_MS = 18e5;
26
+ /**
27
+ * `STS5.1806` 连续撞上几次才判死(与 `auth.ts` 的 `REFRESH_USED_MAX_STREAK` 对齐)。
28
+ *
29
+ * 这个码只说明「这个 refresh_token 已经被用掉了」,最常见的原因是插件刚刚先刷了
30
+ * 一次。磁盘上若已经有新令牌,重读就行;磁盘还没更新(对方正在写)时也会撞上,
31
+ * 那更不能判死 —— 下一轮就恢复正常了。
32
+ */
33
+ const USED_MAX_STREAK = 3;
34
+ /** 睡眠看门狗的检查间隔:机器醒过来最多 30 秒就会补跑一轮。 */
35
+ const SLEEP_WATCHDOG_MS = 3e4;
36
+ function parseHomeArg(argv) {
37
+ const at = argv.indexOf("--home");
38
+ if (at >= 0 && at + 1 < argv.length) return argv[at + 1];
39
+ }
40
+ const home = parseHomeArg(process.argv.slice(2));
41
+ const logPath = keeperLogPath(home);
42
+ /** 只往日志里写人能看懂的一行;绝不写 token/refresh_token/私钥。 */
43
+ function log(message) {
44
+ try {
45
+ appendFileSync(logPath, `${(/* @__PURE__ */ new Date()).toISOString()} ${message}\n`, { mode: 384 });
46
+ } catch {}
47
+ }
48
+ /**
49
+ * 只有一份守护进程。
50
+ *
51
+ * 从卡片连点两次、或同时开两个 DSH 窗口时,第二次 spawn 必须让路 —— 两个进程同时
52
+ * 刷 refresh_token 就是上面说的那个翻车场景。
53
+ *
54
+ * 判据用 `keeperStats`(心跳 + pid 都算),不能只看 pid:上一份 keeper 被强杀后
55
+ * 状态文件会留在盘上,而 Windows 很快就把那个 pid 发给别的进程 —— 只探 pid 会
56
+ * 把一个正常的新进程当成「已有 keeper」,于是每次启动都立刻退出(2026-11-16 实测)。
57
+ */
58
+ function alreadyRunning() {
59
+ const stats = keeperStats(home);
60
+ if (!stats.alive || stats.state === void 0) return void 0;
61
+ if (stats.state.pid === process.pid) return void 0;
62
+ return stats.state.pid;
63
+ }
64
+ /**
65
+ * 一轮续期:读文档 → 逐个续 → 写回。
66
+ *
67
+ * 每轮都重新读盘,而不是启动时读一次:DSH 在运行期间会登录新账号、删账号、写新
68
+ * 凭证,守护进程必须看见这些变化,否则会把一份过期的内存快照写回去,把刚登录的
69
+ * 号覆盖掉。
70
+ */
71
+ /** 每个账号连续撞上「令牌已被用掉」的次数;成功续上一次就清零。 */
72
+ const usedStreak = /* @__PURE__ */ new Map();
73
+ async function tick(state) {
74
+ const accountsPath = codeartsAccountsPath(home);
75
+ const doc = await readAccountDocument(accountsPath);
76
+ if (doc === void 0) {
77
+ state.lastPass = {
78
+ at: Date.now(),
79
+ checked: 0,
80
+ refreshed: 0,
81
+ needsLogin: []
82
+ };
83
+ return;
84
+ }
85
+ const needsLogin = [];
86
+ let refreshed = 0;
87
+ let checked = 0;
88
+ let dirty = false;
89
+ for (const id of doc.order) {
90
+ const cred = doc.accounts[id];
91
+ if (cred === void 0) continue;
92
+ if (cred.stale === true) {
93
+ needsLogin.push(id);
94
+ continue;
95
+ }
96
+ if (!cred.refreshToken || !cred.dpopPrivateKey || !cred.clientId) continue;
97
+ const exp = cred.expiration ? Date.parse(cred.expiration) : NaN;
98
+ if (Number.isNaN(exp)) continue;
99
+ if (exp - Date.now() >= REFRESH_SKEW_MS) continue;
100
+ checked += 1;
101
+ const refreshTokenValue = cred.refreshToken;
102
+ const clientIdValue = cred.clientId;
103
+ const dpopPrivateKeyValue = cred.dpopPrivateKey;
104
+ if (refreshTokenValue === void 0 || clientIdValue === void 0 || dpopPrivateKeyValue === void 0) continue;
105
+ const locked = await withRefreshLock(refreshLockPath(dirname(accountsPath)), () => refreshToken(defaultLoginConfig(), {
106
+ userId: cred.userId ?? "",
107
+ userName: cred.userName ?? "",
108
+ domainId: "",
109
+ securityToken: cred.token,
110
+ accessKeyId: cred.accessKeyId ?? "",
111
+ secretAccessKey: cred.secretAccessKey ?? "",
112
+ expiration: cred.expiration ?? "",
113
+ refreshToken: refreshTokenValue,
114
+ clientId: clientIdValue,
115
+ dpopPrivateKey: dpopPrivateKeyValue
116
+ }), { onBusy: () => log(`refresh SKIPPED ${id.slice(0, 12)} (plugin holds the refresh lock)`) });
117
+ if (locked === void 0) continue;
118
+ try {
119
+ const next = locked;
120
+ usedStreak.delete(id);
121
+ doc.accounts[id] = {
122
+ ...cred,
123
+ token: next.securityToken,
124
+ accessKeyId: next.accessKeyId,
125
+ secretAccessKey: next.secretAccessKey,
126
+ refreshToken: next.refreshToken === "" ? cred.refreshToken : next.refreshToken,
127
+ dpopPrivateKey: next.dpopPrivateKey,
128
+ clientId: next.clientId,
129
+ expiration: next.expiration,
130
+ storedAt: Date.now(),
131
+ stale: false
132
+ };
133
+ dirty = true;
134
+ refreshed += 1;
135
+ log(`refreshed ${id.slice(0, 12)} → expires ${next.expiration}`);
136
+ } catch (error) {
137
+ const used = error instanceof OAuthTokenError && error.refreshTokenUsed;
138
+ let markStale = false;
139
+ if (used) {
140
+ const fresh = await readAccountDocument(accountsPath);
141
+ const advanced = fresh !== void 0 && fresh.accounts[id]?.refreshToken !== void 0 && fresh.accounts[id]?.refreshToken !== cred.refreshToken;
142
+ const streak = (usedStreak.get(id) ?? 0) + 1;
143
+ usedStreak.set(id, streak);
144
+ markStale = !advanced && streak >= USED_MAX_STREAK;
145
+ log(`refresh SKIPPED ${id.slice(0, 12)} (refresh token already used${advanced ? ", newer token on disk" : ""}, streak ${streak}/${USED_MAX_STREAK})`);
146
+ } else {
147
+ usedStreak.delete(id);
148
+ markStale = error instanceof OAuthTokenError && error.permanent;
149
+ }
150
+ if (markStale) {
151
+ doc.accounts[id] = {
152
+ ...cred,
153
+ stale: true
154
+ };
155
+ dirty = true;
156
+ needsLogin.push(id);
157
+ }
158
+ const reason = error instanceof OAuthTokenError ? `HTTP ${error.status} ${error.body.slice(0, 200)}` : error instanceof Error ? error.message : String(error);
159
+ log(`refresh FAILED ${id.slice(0, 12)} (${markStale ? "permanent, marked stale" : "transient, retry next pass"}): ${reason}`);
160
+ }
161
+ }
162
+ if (dirty) await writeJsonAtomic(accountsPath, doc);
163
+ state.lastPass = {
164
+ at: Date.now(),
165
+ checked,
166
+ refreshed,
167
+ needsLogin
168
+ };
169
+ if (refreshed > 0 || needsLogin.length > 0) log(`pass done: checked=${checked} refreshed=${refreshed} needsLogin=${needsLogin.length}`);
170
+ }
171
+ /**
172
+ * 更新安装器一出现就通知调用方让路。
173
+ *
174
+ * 为什么需要:安装器启动后会枚举进程判断「应用是否已关闭」,keeper 只要还在跑就
175
+ * 可能被当成应用本身,更新在十秒左右中止、也不把应用拉回来(`keeper.ts` 的
176
+ * `bundledNodeExecutable` 注释里有完整现场)。换 node.exe 是主路,这里是双保险 —
177
+ * 安装器就算按安装路径匹配也挡不住。
178
+ *
179
+ * 实现上用 `fs.watch` 盯 `%TEMP%`(事件驱动,不轮询):只有新出现的 `ns*.tmp`
180
+ * 目录里真有安装器的 `window-frame.dll` 才算数,用户装别的软件不会误伤。
181
+ */
182
+ function watchForUpdateInstaller(onSeen) {
183
+ if (process.platform !== "win32") return;
184
+ const root = process.env.TEMP ?? process.env.TMP;
185
+ if (root === void 0 || root === "") return;
186
+ const confirm = (name, attempt) => {
187
+ if (!name.toLowerCase().startsWith("ns")) return;
188
+ const dir = join(root, name);
189
+ if (isDshInstallerTempDir(dir)) {
190
+ onSeen();
191
+ return;
192
+ }
193
+ if (attempt < 2) setTimeout(() => confirm(name, attempt + 1), 500);
194
+ };
195
+ try {
196
+ watch(root, (_event, filename) => {
197
+ if (filename === null) return;
198
+ confirm(String(filename), 0);
199
+ });
200
+ } catch (error) {
201
+ log(`installer watch unavailable: ${error instanceof Error ? error.message : String(error)}`);
202
+ }
203
+ }
204
+ async function main() {
205
+ const other = alreadyRunning();
206
+ if (other !== void 0) {
207
+ log(`another keeper is already running (pid ${other}); exiting`);
208
+ process.exit(0);
209
+ }
210
+ const state = {
211
+ version: 1,
212
+ pid: process.pid,
213
+ startedAt: Date.now(),
214
+ heartbeatAt: Date.now(),
215
+ ...process.env.DSH_CODEARTS_PLUGIN_VERSION === void 0 ? {} : { pluginVersion: process.env.DSH_CODEARTS_PLUGIN_VERSION }
216
+ };
217
+ writeKeeperState(state, home);
218
+ log(`keeper started pid=${process.pid}`);
219
+ let stopped = false;
220
+ const shutdown = (reason) => {
221
+ if (stopped) return;
222
+ stopped = true;
223
+ log(`keeper stopping: ${reason}`);
224
+ clearKeeperState(home);
225
+ process.exit(0);
226
+ };
227
+ clearKeeperHandoff(home);
228
+ /**
229
+ * 为更新安装让路。
230
+ *
231
+ * 和 `shutdown` 的区别只有一条:留一个「让路」标记。插件看到它会知道这是预期内
232
+ * 的退出,不把「常驻保活」开关关掉 —— 新版应用起来后开关还开着,keeper 会照常被
233
+ * 拉起,用户不会发现自己"被关了保活"。
234
+ */
235
+ const stepAside = (reason) => {
236
+ if (stopped) return;
237
+ log(`keeper stepping aside: ${reason}`);
238
+ writeKeeperHandoff(reason, home);
239
+ clearKeeperState(home);
240
+ stopped = true;
241
+ process.exit(0);
242
+ };
243
+ watchForUpdateInstaller(() => stepAside("update installer detected"));
244
+ for (const signal of [
245
+ "SIGINT",
246
+ "SIGTERM",
247
+ "SIGHUP"
248
+ ]) process.on(signal, () => shutdown(`signal ${signal}`));
249
+ process.on("exit", () => {
250
+ if (!stopped) clearKeeperState(home);
251
+ });
252
+ /** 心跳:卡片据此判断「这个 pid 还活着」,也是插件判断能不能让路的依据。 */
253
+ setInterval(() => {
254
+ state.heartbeatAt = Date.now();
255
+ writeKeeperState(state, home);
256
+ if (stopRequested(home)) shutdown("stop requested by plugin");
257
+ }, KEEPER_HEARTBEAT_MS);
258
+ let timer;
259
+ let lastPassAt = 0;
260
+ const loop = async () => {
261
+ if (stopped) return;
262
+ if (stopRequested(home)) {
263
+ shutdown("stop requested by plugin");
264
+ return;
265
+ }
266
+ try {
267
+ await tick(state);
268
+ } catch (error) {
269
+ log(`pass failed: ${error instanceof Error ? error.message : String(error)}`);
270
+ }
271
+ lastPassAt = Date.now();
272
+ state.heartbeatAt = lastPassAt;
273
+ writeKeeperState(state, home);
274
+ if (stopped) return;
275
+ timer = setTimeout(() => void loop(), KEEPER_TICK_MS);
276
+ };
277
+ /**
278
+ * 睡眠/休眠补偿:setTimeout 只保证「不早于」,机器睡过去的那段时间它是停摆的。
279
+ *
280
+ * 2026-11-18 的现场:守护进程 pid 全程活着,日志却在 06:46–08:06 之间缺了 4 轮
281
+ * tick —— 机器睡了,定时器跟着停。而插件那边看到心跳文件在、pid 也活,就按
282
+ * `keeperRunning()` 让路,于是两边一起不刷,等醒过来凭证已经过期。
283
+ *
284
+ * 这里每 30 秒对一次表:超过一个 tick 周期没跑过一轮就立刻补一轮。补跑会重排
285
+ * 定时器,所以睡醒后不会连撞两次。
286
+ */
287
+ setInterval(() => {
288
+ if (stopped || timer === void 0) return;
289
+ if (Date.now() - lastPassAt < 15e5) return;
290
+ clearTimeout(timer);
291
+ log(`wake-from-sleep: no pass for ${Math.round((Date.now() - lastPassAt) / 1e3)}s, running one now`);
292
+ loop();
293
+ }, SLEEP_WATCHDOG_MS);
294
+ loop();
295
+ }
296
+ main().catch((error) => {
297
+ log(`keeper fatal: ${error instanceof Error ? error.message : String(error)}`);
298
+ try {
299
+ if (existsSync(keeperStatePath(home))) unlinkSync(keeperStatePath(home));
300
+ } catch {}
301
+ process.exit(1);
302
+ });
303
+ //#endregion
304
+ export {};