@cydm/pie 4.12.0 → 4.12.1

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.
@@ -3,7 +3,7 @@ import {
3
3
  isWindowsServiceManager,
4
4
  launchWindowsServiceUpgradeActor,
5
5
  resolveAbsoluteActorEnv
6
- } from "../../../chunks/chunk-6U6UGM4C.js";
6
+ } from "../../../chunks/chunk-Y6AVNVOD.js";
7
7
  import {
8
8
  DISPATCH_PREFIX,
9
9
  IPC_PROTOCOL_VERSION,
@@ -26,12 +26,12 @@ import {
26
26
  } from "../../../chunks/chunk-F7EBZTZO.js";
27
27
  import {
28
28
  liveSessionHolder
29
- } from "../../../chunks/chunk-322WLBDY.js";
29
+ } from "../../../chunks/chunk-Q5PSWX3B.js";
30
30
  import {
31
31
  claimOwnership,
32
- pidDefinitelyDead,
32
+ isPositivelyDeadHolder,
33
33
  readOwnership
34
- } from "../../../chunks/chunk-BSITHT43.js";
34
+ } from "../../../chunks/chunk-Q4NJEPIZ.js";
35
35
  import {
36
36
  loadResolvedModelsConfig
37
37
  } from "../../../chunks/chunk-IZ4DYCJ7.js";
@@ -1232,7 +1232,7 @@ function readLock(binding) {
1232
1232
  return readOwnership(lockPath(binding), (v) => v.binding === binding);
1233
1233
  }
1234
1234
  function lockAlive(info, _now = Date.now()) {
1235
- return !!info && !pidDefinitelyDead(info.pid);
1235
+ return !!info && !isPositivelyDeadHolder(info.pid, info.heartbeatAt);
1236
1236
  }
1237
1237
  function tryClaimConsumer(binding, holder, onLost, shouldYield) {
1238
1238
  try {
@@ -1737,12 +1737,7 @@ function liveManagerForBinding(binding) {
1737
1737
  try {
1738
1738
  const peer = JSON.parse(fs5.readFileSync(pathJoin(ipcDiscoveryRoot(), file), "utf8"));
1739
1739
  if (peer.pid === process.pid || peer.isManager !== true || peer.imBinding !== binding || !Number.isInteger(peer.pid) || !peer.pid || peer.pid <= 0) continue;
1740
- try {
1741
- process.kill(peer.pid, 0);
1742
- return true;
1743
- } catch (error) {
1744
- if (error.code !== "ESRCH") return true;
1745
- }
1740
+ if (!isPositivelyDeadHolder(peer.pid, typeof peer.startedAt === "number" ? peer.startedAt : void 0)) return true;
1746
1741
  } catch {
1747
1742
  }
1748
1743
  }
@@ -3183,9 +3178,17 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
3183
3178
  /permission/i,
3184
3179
  /connect|network|dns|timeout/i
3185
3180
  ];
3181
+ let botIdentityRetryTimer;
3182
+ const clearBotIdentityRetry = () => {
3183
+ if (botIdentityRetryTimer) {
3184
+ clearTimeout(botIdentityRetryTimer);
3185
+ botIdentityRetryTimer = void 0;
3186
+ }
3187
+ };
3186
3188
  const fail = (reason) => {
3187
3189
  if (!failed && !stopped) {
3188
3190
  failed = true;
3191
+ clearBotIdentityRetry();
3189
3192
  callbacks.failure(lastErrorLine ? `${reason} \u2014 ${lastErrorLine}` : reason);
3190
3193
  }
3191
3194
  };
@@ -3203,19 +3206,40 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
3203
3206
  }
3204
3207
  };
3205
3208
  const botIdentity = { openId: void 0, attempts: 0, pending: void 0, nextAttemptAt: 0 };
3209
+ const scheduleBotIdentityRetry = (delayMs) => {
3210
+ if (stopped || closed || failed || botIdentity.openId || botIdentityRetryTimer) return;
3211
+ botIdentityRetryTimer = setTimeout(() => {
3212
+ botIdentityRetryTimer = void 0;
3213
+ if (stopped || closed || failed || botIdentity.openId) return;
3214
+ void resolveBotIdentity();
3215
+ }, delayMs);
3216
+ botIdentityRetryTimer.unref?.();
3217
+ };
3206
3218
  const resolveBotIdentity = () => {
3207
3219
  if (botIdentity.openId) return Promise.resolve();
3208
3220
  if (botIdentity.pending) return botIdentity.pending;
3209
3221
  const now = Date.now();
3210
- if (now < botIdentity.nextAttemptAt) return Promise.resolve();
3211
- botIdentity.nextAttemptAt = now + Math.min(5e3 * 2 ** botIdentity.attempts, 6e5);
3222
+ if (now < botIdentity.nextAttemptAt) {
3223
+ scheduleBotIdentityRetry(Math.max(100, botIdentity.nextAttemptAt - now));
3224
+ return Promise.resolve();
3225
+ }
3226
+ const backoffMs = Math.min(5e3 * 2 ** botIdentity.attempts, 6e4);
3227
+ botIdentity.nextAttemptAt = now + backoffMs;
3212
3228
  botIdentity.attempts += 1;
3229
+ clearBotIdentityRetry();
3213
3230
  const req = call(["api", "GET", "/open-apis/bot/v3/info", "--as", "bot"]).then((info) => {
3214
3231
  if (typeof info?.open_id === "string") {
3215
3232
  botIdentity.openId = info.open_id;
3216
3233
  botIdentity.attempts = 0;
3217
- } else console.warn(`[im-forward] bot identity lookup returned no open_id (attempt ${botIdentity.attempts}); group gating stays UNCLASSIFIED \u2014 new group conversations are refused until the identity resolves`);
3218
- }).catch(() => console.warn(`[im-forward] bot identity lookup failed (attempt ${botIdentity.attempts}); group gating stays UNCLASSIFIED \u2014 new group conversations are refused until the identity resolves`)).finally(() => {
3234
+ clearBotIdentityRetry();
3235
+ } else {
3236
+ console.warn(`[im-forward] bot identity lookup returned no open_id (attempt ${botIdentity.attempts}); group gating stays UNCLASSIFIED \u2014 retrying in ${Math.round(backoffMs / 1e3)}s`);
3237
+ scheduleBotIdentityRetry(backoffMs);
3238
+ }
3239
+ }).catch(() => {
3240
+ console.warn(`[im-forward] bot identity lookup failed (attempt ${botIdentity.attempts}); group gating stays UNCLASSIFIED \u2014 retrying in ${Math.round(backoffMs / 1e3)}s`);
3241
+ scheduleBotIdentityRetry(backoffMs);
3242
+ }).finally(() => {
3219
3243
  botIdentity.pending = void 0;
3220
3244
  });
3221
3245
  botIdentity.pending = req;
@@ -3272,6 +3296,7 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
3272
3296
  }
3273
3297
  return { async stop() {
3274
3298
  stopped = true;
3299
+ clearBotIdentityRetry();
3275
3300
  for (const timer of optionalRespawnTimers.values()) clearTimeout(timer);
3276
3301
  optionalRespawnTimers.clear();
3277
3302
  await Promise.allSettled([...children].map((child2) => shutdownConsumer(child2)));
@@ -15,8 +15,8 @@ import {
15
15
  } from "../../../chunks/chunk-7RJXKN7N.js";
16
16
  import {
17
17
  liveSessionHolder
18
- } from "../../../chunks/chunk-322WLBDY.js";
19
- import "../../../chunks/chunk-BSITHT43.js";
18
+ } from "../../../chunks/chunk-Q5PSWX3B.js";
19
+ import "../../../chunks/chunk-Q4NJEPIZ.js";
20
20
  import {
21
21
  loadResolvedModelsConfig
22
22
  } from "../../../chunks/chunk-IZ4DYCJ7.js";
@@ -0,0 +1,210 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+
3
+ // src/core/node-ownership-lock.ts
4
+ import * as fs from "node:fs";
5
+ import * as os from "node:os";
6
+ import * as path from "node:path";
7
+ import { execFileSync } from "node:child_process";
8
+ import { randomUUID } from "node:crypto";
9
+ var REBOOT_CLOCK_SKEW_MARGIN_MS = 6e4;
10
+ var PROCESS_IDENTITY_PROBE_TIMEOUT_MS = 500;
11
+ var MUTEX_PROBE_THROTTLE_MS = 250;
12
+ var NODE_OR_PIE_IDENTITY_RE = /(?:^|[\s/\\"'=])(?:node(?:\.exe)?|pie(?:\.exe|\.cmd)?|bun(?:\.exe)?|deno(?:\.exe)?|tsx(?:\.cmd)?|service-launcher(?:\.exe)?|cmd(?:\.exe)?|powershell(?:\.exe)?|pwsh(?:\.exe)?|cli\.(?:js|ts|mjs|cjs))(?:$|[\s/\\"'=])/i;
13
+ function pidDefinitelyDead(pid) {
14
+ if (!Number.isInteger(pid) || pid <= 0) return false;
15
+ try {
16
+ process.kill(pid, 0);
17
+ return false;
18
+ } catch (error) {
19
+ return error.code === "ESRCH";
20
+ }
21
+ }
22
+ function isPreRebootTimestamp(timestampMs, nowMs = Date.now(), uptimeSec = os.uptime()) {
23
+ if (typeof timestampMs !== "number" || !Number.isFinite(timestampMs) || timestampMs <= 0) return false;
24
+ if (!Number.isFinite(nowMs) || !Number.isFinite(uptimeSec) || uptimeSec < 0) return false;
25
+ const hostBootMs = nowMs - Math.floor(uptimeSec * 1e3);
26
+ return timestampMs < hostBootMs - REBOOT_CLOCK_SKEW_MARGIN_MS;
27
+ }
28
+ function parseWindowsTasklistImageName(stdout, expectedPid) {
29
+ if (!Number.isInteger(expectedPid) || expectedPid <= 0) return void 0;
30
+ for (const rawLine of stdout.split(/\r?\n/)) {
31
+ const line = rawLine.trim();
32
+ if (!line) continue;
33
+ const match = /^"([^"]+)"\s*,\s*"(\d+)"\s*,/.exec(line);
34
+ if (!match) return void 0;
35
+ const imageName = match[1].trim();
36
+ const rowPid = Number.parseInt(match[2], 10);
37
+ if (!imageName || rowPid !== expectedPid) return void 0;
38
+ return imageName;
39
+ }
40
+ return void 0;
41
+ }
42
+ function parsePosixPsIdentity(stdout, expectedPid) {
43
+ if (!Number.isInteger(expectedPid) || expectedPid <= 0) return void 0;
44
+ for (const rawLine of stdout.split(/\r?\n/)) {
45
+ const line = rawLine.trim();
46
+ if (!line) continue;
47
+ const match = /^(\d+)\s+(\S+)(?:\s+(.*))?$/.exec(line);
48
+ if (!match) return void 0;
49
+ const rowPid = Number.parseInt(match[1], 10);
50
+ const comm = match[2].trim();
51
+ const args = match[3]?.trim() ?? "";
52
+ if (!comm || rowPid !== expectedPid) return void 0;
53
+ return args ? `${comm} ${args}` : comm;
54
+ }
55
+ return void 0;
56
+ }
57
+ function probeProcessIdentity(pid) {
58
+ if (!Number.isInteger(pid) || pid <= 0) return void 0;
59
+ try {
60
+ if (process.platform === "win32") {
61
+ const out2 = execFileSync(
62
+ "tasklist",
63
+ ["/FI", `PID eq ${pid}`, "/FO", "CSV", "/NH"],
64
+ { encoding: "utf8", timeout: PROCESS_IDENTITY_PROBE_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
65
+ );
66
+ return parseWindowsTasklistImageName(out2, pid);
67
+ }
68
+ const out = execFileSync(
69
+ "ps",
70
+ ["-p", String(pid), "-o", "pid=,comm=,args="],
71
+ { encoding: "utf8", timeout: PROCESS_IDENTITY_PROBE_TIMEOUT_MS, stdio: ["ignore", "pipe", "pipe"] }
72
+ );
73
+ return parsePosixPsIdentity(out, pid);
74
+ } catch {
75
+ return void 0;
76
+ }
77
+ }
78
+ function isPositivelyDeadHolder(pid, timestampMs, options) {
79
+ if (!Number.isInteger(pid) || pid <= 0) return false;
80
+ const checkDead = options?.isDead ?? pidDefinitelyDead;
81
+ if (checkDead(pid)) return true;
82
+ const selfPid = options?.selfPid ?? process.pid;
83
+ if (pid === selfPid) return false;
84
+ if (!isPreRebootTimestamp(timestampMs, options?.nowMs, options?.uptimeSec)) return false;
85
+ const identity = (options?.probeIdentity ?? probeProcessIdentity)(pid);
86
+ if (identity === void 0 || identity.trim().length === 0) return false;
87
+ return !NODE_OR_PIE_IDENTITY_RE.test(identity);
88
+ }
89
+ function withOwnershipMutex(lock, fn) {
90
+ fs.mkdirSync(path.dirname(lock), { recursive: true, mode: 448 });
91
+ const token = randomUUID();
92
+ const candidate = `${lock}.acquire.${token}`;
93
+ fs.mkdirSync(candidate, { mode: 448 });
94
+ try {
95
+ fs.writeFileSync(path.join(candidate, `held.${token}`), JSON.stringify({ version: 1, pid: process.pid, at: Date.now() }), { flag: "wx", mode: 384 });
96
+ const deadline = process.hrtime.bigint() + 2000000000n;
97
+ const lastNegativeProbeAt = /* @__PURE__ */ new Map();
98
+ for (; ; ) {
99
+ try {
100
+ fs.renameSync(candidate, lock);
101
+ break;
102
+ } catch (error) {
103
+ if (!["EEXIST", "ENOTEMPTY", "EPERM", "ENOTDIR"].includes(error.code ?? "")) throw error;
104
+ if (process.hrtime.bigint() >= deadline) throw new Error(`Ownership mutex contention: ${lock}`);
105
+ try {
106
+ const entries = fs.readdirSync(lock);
107
+ if (entries.every((name) => {
108
+ if (!/^held\.[a-f0-9-]+$/.test(name)) return false;
109
+ const value = JSON.parse(fs.readFileSync(path.join(lock, name), "utf8"));
110
+ if (value?.version !== 1 || !Number.isInteger(value.pid) || value.pid <= 0) return false;
111
+ if (pidDefinitelyDead(value.pid)) return true;
112
+ const heldAt = typeof value.at === "number" ? value.at : void 0;
113
+ const cacheKey = `${name}:${value.pid}`;
114
+ const now = Date.now();
115
+ const lastProbed = lastNegativeProbeAt.get(cacheKey);
116
+ if (lastProbed !== void 0 && now - lastProbed < MUTEX_PROBE_THROTTLE_MS) return false;
117
+ const dead = isPositivelyDeadHolder(value.pid, heldAt);
118
+ if (!dead) lastNegativeProbeAt.set(cacheKey, now);
119
+ return dead;
120
+ })) {
121
+ for (const name of entries) {
122
+ try {
123
+ fs.unlinkSync(path.join(lock, name));
124
+ } catch (e) {
125
+ if (e.code !== "ENOENT") throw e;
126
+ }
127
+ }
128
+ fs.rmdirSync(lock);
129
+ }
130
+ } catch {
131
+ }
132
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 3);
133
+ }
134
+ }
135
+ try {
136
+ return fn();
137
+ } finally {
138
+ try {
139
+ fs.unlinkSync(path.join(lock, `held.${token}`));
140
+ } catch {
141
+ }
142
+ try {
143
+ fs.rmdirSync(lock);
144
+ } catch {
145
+ }
146
+ }
147
+ } finally {
148
+ fs.rmSync(candidate, { recursive: true, force: true });
149
+ }
150
+ }
151
+ function readOwnership(target, valid) {
152
+ let raw;
153
+ try {
154
+ raw = fs.readFileSync(target, "utf8");
155
+ } catch (error) {
156
+ if (error.code === "ENOENT") return void 0;
157
+ throw error;
158
+ }
159
+ const value = JSON.parse(raw);
160
+ if (!value || !Number.isInteger(value.pid) || value.pid <= 0 || typeof value.holder !== "string" || !Number.isFinite(value.heartbeatAt) || value.generation !== void 0 && typeof value.generation !== "string" || !valid(value)) {
161
+ throw new Error(`Invalid ownership record: ${target}`);
162
+ }
163
+ return value;
164
+ }
165
+ function claimOwnership(target, mine, valid) {
166
+ const mutex = `${target}.mutex`;
167
+ const generation = randomUUID();
168
+ const publish = () => {
169
+ const tmp = `${target}.${randomUUID()}.tmp`;
170
+ try {
171
+ fs.writeFileSync(tmp, `${JSON.stringify({ ...mine, generation, heartbeatAt: Date.now() })}
172
+ `, { flag: "wx", mode: 384 });
173
+ fs.renameSync(tmp, target);
174
+ } finally {
175
+ fs.rmSync(tmp, { force: true });
176
+ }
177
+ };
178
+ const holder = withOwnershipMutex(mutex, () => {
179
+ const current = readOwnership(target, valid);
180
+ if (current && !isPositivelyDeadHolder(current.pid, current.heartbeatAt)) return current;
181
+ publish();
182
+ return void 0;
183
+ });
184
+ if (holder) return { holder };
185
+ let released = false;
186
+ return { handle: {
187
+ heartbeat: () => {
188
+ if (released) return false;
189
+ return withOwnershipMutex(mutex, () => {
190
+ if (readOwnership(target, valid)?.generation !== generation) return false;
191
+ publish();
192
+ return true;
193
+ });
194
+ },
195
+ release: () => {
196
+ if (released) return;
197
+ released = true;
198
+ withOwnershipMutex(mutex, () => {
199
+ if (readOwnership(target, valid)?.generation === generation) fs.unlinkSync(target);
200
+ });
201
+ }
202
+ } };
203
+ }
204
+
205
+ export {
206
+ isPositivelyDeadHolder,
207
+ withOwnershipMutex,
208
+ readOwnership,
209
+ claimOwnership
210
+ };
@@ -1,9 +1,9 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  claimOwnership,
4
- pidDefinitelyDead,
4
+ isPositivelyDeadHolder,
5
5
  readOwnership
6
- } from "./chunk-BSITHT43.js";
6
+ } from "./chunk-Q4NJEPIZ.js";
7
7
  import {
8
8
  getSessionsDir
9
9
  } from "./chunk-CBDQJMUI.js";
@@ -25,7 +25,7 @@ function unavailable(sessionId) {
25
25
  function sessionOwnerAlive(sessionId, _now = Date.now()) {
26
26
  try {
27
27
  const info = readOwnership(lockPath(sessionId), (v) => v.sessionId === sessionId);
28
- return info && !pidDefinitelyDead(info.pid) ? info : void 0;
28
+ return info && !isPositivelyDeadHolder(info.pid, info.heartbeatAt) ? info : void 0;
29
29
  } catch {
30
30
  return unavailable(sessionId);
31
31
  }
@@ -98,8 +98,11 @@ function formatBlockingWindowsPeers(peers) {
98
98
  return `${label} "${p.name}" (pid ${p.pid})`;
99
99
  }).join(", ");
100
100
  }
101
+ function isWindowsTaskNotFoundDetail(detail) {
102
+ return /cannot find|does not exist|not found|找不到指定的文件|系统找不到/i.test(detail);
103
+ }
101
104
  function isWindowsTaskAlreadyStoppedDetail(detail) {
102
- return /not currently running|not running|cannot find|does not exist|not found|当前未运行|尚未运行|没有正在运行|找不到指定的文件|系统找不到/i.test(detail);
105
+ return /not currently running|not running|当前未运行|尚未运行|没有正在运行/i.test(detail) || isWindowsTaskNotFoundDetail(detail);
103
106
  }
104
107
  function parseWindowsTaskNumericState(status, stdout, _stderr = "") {
105
108
  if (status !== 0) return "unknown";
@@ -149,6 +152,30 @@ ${r.stderr ?? ""}`;
149
152
  return "unknown";
150
153
  }
151
154
  }
155
+ function queryWindowsServiceTaskPresence(runQuery) {
156
+ const exec = runQuery ?? ((cmd, args) => spawnSync(cmd, args, {
157
+ encoding: "utf8",
158
+ timeout: 15e3,
159
+ windowsHide: true
160
+ }));
161
+ try {
162
+ const ps = exec("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_TASK_STATE_PS]);
163
+ if (!ps.error) {
164
+ if (ps.status !== 0) return "unknown";
165
+ const m = /^\s*STATE=(NOT_FOUND|[0-4])\s*$/im.exec(ps.stdout ?? "");
166
+ if (!m) return "unknown";
167
+ return m[1].toUpperCase() === "NOT_FOUND" ? "not-found" : "present";
168
+ }
169
+ const r = exec("schtasks", ["/Query", "/TN", "dev.pie.manager"]);
170
+ const combined = `${r.stdout ?? ""}
171
+ ${r.stderr ?? ""}`;
172
+ if (r.error) return "unknown";
173
+ if (r.status === 0) return combined.trim().length > 0 ? "present" : "unknown";
174
+ return isWindowsTaskNotFoundDetail(combined) ? "not-found" : "unknown";
175
+ } catch {
176
+ return "unknown";
177
+ }
178
+ }
152
179
  function runWindowsPreInstallStop(state, deps) {
153
180
  const checkManagerIdle = () => {
154
181
  const liveManager = deps.findManagerResident(state.sessionId);
@@ -570,8 +597,11 @@ export {
570
597
  normalizePreInstallStopOutcome,
571
598
  resolveDefaultTuiUsePidFile,
572
599
  scanBlockingWindowsPeers,
600
+ isWindowsTaskNotFoundDetail,
601
+ isWindowsTaskAlreadyStoppedDetail,
573
602
  parseWindowsTaskNumericState,
574
603
  queryWindowsServiceTaskState,
604
+ queryWindowsServiceTaskPresence,
575
605
  runWindowsPreInstallStop,
576
606
  isWindowsServiceManager,
577
607
  resolveAbsoluteActorEnv,