@cydm/pie 4.10.2 → 4.12.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.
Files changed (38) hide show
  1. package/dist/builtin/extensions/ask-user/index.js +2 -2
  2. package/dist/builtin/extensions/cron/index.js +1 -1
  3. package/dist/builtin/extensions/im-forward/index.js +9128 -7189
  4. package/dist/builtin/extensions/mcp-adapter/index.js +1 -1
  5. package/dist/builtin/extensions/memory/index.js +171 -66
  6. package/dist/builtin/extensions/pie-ipc/index.js +1 -1
  7. package/dist/builtin/extensions/pie-proc/index.js +542 -52
  8. package/dist/builtin/extensions/plan-mode/index.js +2 -2
  9. package/dist/builtin/extensions/subagent/README.md +1 -1
  10. package/dist/builtin/extensions/subagent/index.js +3 -3
  11. package/dist/builtin/extensions/todo/index.js +2 -2
  12. package/dist/chunks/{auth-storage-C3FZMT7J.js → auth-storage-IJEJ2TGE.js} +1 -1
  13. package/dist/chunks/chunk-26ILLZKQ.js +400 -0
  14. package/dist/chunks/{chunk-KWK7KTSZ.js → chunk-322WLBDY.js} +1 -1
  15. package/dist/chunks/{chunk-OU33ROFD.js → chunk-3GG342QY.js} +78 -78
  16. package/dist/chunks/{chunk-BB7ETSJK.js → chunk-6U6UGM4C.js} +119 -3
  17. package/dist/chunks/{chunk-ZPJ3BNQB.js → chunk-BSITHT43.js} +1 -0
  18. package/dist/chunks/{chunk-IZKHSUNQ.js → chunk-CAPBTMLI.js} +18 -1
  19. package/dist/chunks/{chunk-FC5AN5QP.js → chunk-IZ4DYCJ7.js} +268 -107
  20. package/dist/chunks/{chunk-HK3FHIAH.js → chunk-KW46ND3S.js} +1999 -767
  21. package/dist/chunks/{chunk-SW2E33UL.js → chunk-LMDWWT43.js} +123 -4
  22. package/dist/chunks/chunk-OGGL6LUN.js +331 -0
  23. package/dist/chunks/{chunk-BTUMBUDU.js → chunk-QSXBPTOA.js} +1 -1
  24. package/dist/chunks/{chunk-5QMS6RQC.js → chunk-SXBX2P5R.js} +160 -5
  25. package/dist/chunks/{chunk-7LICWWUE.js → chunk-W37NAT3N.js} +2 -2
  26. package/dist/chunks/chunk-WTBLV6F5.js +476 -0
  27. package/dist/chunks/{host-image-fallback-3TEMOQM5.js → host-image-fallback-NXY36VO2.js} +1 -1
  28. package/dist/chunks/{manager-cli-BXI4UFTJ.js → manager-cli-B6GIYTI7.js} +35 -13
  29. package/dist/chunks/{manager-upgrade-XPFXKO7A.js → manager-upgrade-WHER3WTJ.js} +284 -109
  30. package/dist/chunks/memory-git-C3S276QJ.js +19 -0
  31. package/dist/chunks/{model-registry-QKJ3YVDS.js → model-registry-QNEPISBJ.js} +11 -3
  32. package/dist/chunks/{read-file-understanding-N2ZZQLTZ.js → read-file-understanding-ZCBNCQHG.js} +3 -3
  33. package/dist/chunks/{src-F5N6O2HR.js → src-7CU7OTQS.js} +36 -36
  34. package/dist/chunks/{src-3PSR2AAX.js → src-7MZZJVOG.js} +1 -1
  35. package/dist/cli.js +750 -516
  36. package/package.json +2 -2
  37. package/dist/chunks/chunk-6WKBQZWM.js +0 -19
  38. package/dist/chunks/chunk-XMTRKMBG.js +0 -386
@@ -1,42 +1,210 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  normalizePreInstallStopOutcome,
4
+ parseWindowsTaskNumericState,
5
+ queryWindowsServiceTaskState,
4
6
  resolveDefaultTuiUsePidFile,
5
7
  runWindowsPreInstallStop,
6
8
  scanBlockingWindowsPeers
7
- } from "./chunk-BB7ETSJK.js";
9
+ } from "./chunk-6U6UGM4C.js";
8
10
  import {
9
11
  readProcessCommandLine
10
12
  } from "./chunk-7RJXKN7N.js";
13
+ import {
14
+ pidDefinitelyDead,
15
+ withOwnershipMutex
16
+ } from "./chunk-BSITHT43.js";
11
17
  import {
12
18
  VERSION
13
19
  } from "./chunk-CBDQJMUI.js";
14
20
  import "./chunk-LZQXQOPJ.js";
15
21
 
16
22
  // src/commands/manager-upgrade.ts
23
+ import { spawnSync as spawnSync2 } from "node:child_process";
24
+ import * as fs2 from "node:fs";
25
+ import * as os from "node:os";
26
+ import * as path2 from "node:path";
27
+
28
+ // src/commands/manager-upgrade-service.ts
17
29
  import { spawnSync } from "node:child_process";
30
+ import { randomUUID } from "node:crypto";
18
31
  import * as fs from "node:fs";
19
- import * as os from "node:os";
20
32
  import * as path from "node:path";
33
+ function acquireUpgradeLock(lockFile) {
34
+ const mutexDir = `${lockFile}.mutex`;
35
+ const token = randomUUID();
36
+ let acquired = false;
37
+ try {
38
+ acquired = withOwnershipMutex(mutexDir, () => {
39
+ fs.mkdirSync(path.dirname(lockFile), { recursive: true });
40
+ if (fs.existsSync(lockFile)) {
41
+ let holderPid;
42
+ try {
43
+ const holder = JSON.parse(fs.readFileSync(lockFile, "utf8"));
44
+ if (typeof holder.pid === "number" && Number.isInteger(holder.pid) && holder.pid > 0) {
45
+ holderPid = holder.pid;
46
+ }
47
+ } catch {
48
+ return false;
49
+ }
50
+ if (holderPid === void 0 || !pidDefinitelyDead(holderPid)) {
51
+ return false;
52
+ }
53
+ }
54
+ const tmp = `${lockFile}.${process.pid}.${token}.tmp`;
55
+ try {
56
+ fs.writeFileSync(tmp, JSON.stringify({ pid: process.pid, token, at: Date.now() }), { flag: "wx", mode: 384 });
57
+ fs.renameSync(tmp, lockFile);
58
+ return true;
59
+ } finally {
60
+ try {
61
+ fs.rmSync(tmp, { force: true });
62
+ } catch {
63
+ }
64
+ }
65
+ });
66
+ } catch {
67
+ return null;
68
+ }
69
+ if (!acquired) return null;
70
+ let released = false;
71
+ return {
72
+ release: () => {
73
+ if (released) return;
74
+ released = true;
75
+ try {
76
+ withOwnershipMutex(mutexDir, () => {
77
+ try {
78
+ const holder = JSON.parse(fs.readFileSync(lockFile, "utf8"));
79
+ if (holder.pid !== process.pid || holder.token !== token) return;
80
+ } catch {
81
+ return;
82
+ }
83
+ try {
84
+ fs.rmSync(lockFile, { force: true });
85
+ } catch {
86
+ }
87
+ });
88
+ } catch {
89
+ }
90
+ }
91
+ };
92
+ }
93
+ function parseLaunchctlServiceState(status, stdout, stderr) {
94
+ const combined = `${stdout}
95
+ ${stderr}`;
96
+ if (status !== 0) {
97
+ return /could not find service|service not found/i.test(combined) ? "stopped" : "unknown";
98
+ }
99
+ const pidMatch = /^\s*pid\s*=\s*(\d+)\s*$/im.exec(combined);
100
+ if (pidMatch && Number.parseInt(pidMatch[1], 10) > 0) return "running";
101
+ const stateMatch = /^\s*state\s*=\s*(.+)$/im.exec(combined)?.[1]?.trim().toLowerCase();
102
+ if (!stateMatch) return "unknown";
103
+ if (stateMatch === "running") return "running";
104
+ if (stateMatch === "not running" || stateMatch === "waiting" || stateMatch === "spawn scheduled") return "stopped";
105
+ return "unknown";
106
+ }
107
+ function parseSystemctlServiceState(status, stdout, stderr) {
108
+ const combined = `${stdout}
109
+ ${stderr}`;
110
+ if (status !== 0) {
111
+ return /not found|could not be found|no such unit/i.test(combined) ? "stopped" : "unknown";
112
+ }
113
+ const mainPid = Number.parseInt(/^\s*MainPID=(\d+)\s*$/im.exec(combined)?.[1] ?? "0", 10);
114
+ if (Number.isInteger(mainPid) && mainPid > 0) return "running";
115
+ const active = /^\s*ActiveState=([^\r\n]+)$/im.exec(combined)?.[1]?.trim().toLowerCase();
116
+ if (!active) return "unknown";
117
+ if (active === "active" || active === "activating" || active === "reloading") return "running";
118
+ if (active === "inactive" || active === "failed" || active === "deactivating") return "stopped";
119
+ return "unknown";
120
+ }
121
+ function queryPlatformServiceState() {
122
+ try {
123
+ if (process.platform === "win32") return queryWindowsServiceTaskState();
124
+ if (process.platform === "darwin") {
125
+ const uid = process.getuid?.() ?? 501;
126
+ const r = spawnSync("launchctl", ["print", `gui/${uid}/dev.pie.manager`], { encoding: "utf8", timeout: 1e4 });
127
+ if (r.error) return "unknown";
128
+ return parseLaunchctlServiceState(r.status, r.stdout ?? "", r.stderr ?? "");
129
+ }
130
+ if (process.platform === "linux") {
131
+ const r = spawnSync("systemctl", ["--user", "show", "-p", "ActiveState", "-p", "MainPID", "dev.pie.manager"], { encoding: "utf8", timeout: 1e4 });
132
+ if (r.error) return "unknown";
133
+ return parseSystemctlServiceState(r.status, r.stdout ?? "", r.stderr ?? "");
134
+ }
135
+ return "unknown";
136
+ } catch {
137
+ return "unknown";
138
+ }
139
+ }
140
+ function scanLinuxServiceBlockingWorkers(discoveryDir) {
141
+ let files;
142
+ try {
143
+ files = fs.readdirSync(discoveryDir).filter((f) => f.endsWith(".json"));
144
+ } catch (error) {
145
+ if (error.code === "ENOENT") return { busy: false };
146
+ return { busy: true, detail: "discovery directory unreadable" };
147
+ }
148
+ if (files.length > 256) {
149
+ return { busy: true, detail: `too many discovery entries (${files.length}) to verify worker safety` };
150
+ }
151
+ const blocking = [];
152
+ for (const file of files) {
153
+ let raw;
154
+ try {
155
+ raw = fs.readFileSync(path.join(discoveryDir, file), "utf8");
156
+ } catch (error) {
157
+ if (error.code === "ENOENT") continue;
158
+ return { busy: true, detail: `unreadable discovery entry (${file})` };
159
+ }
160
+ let parsed;
161
+ try {
162
+ const decoded = JSON.parse(raw);
163
+ if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) {
164
+ return { busy: true, detail: `malformed discovery entry (${file})` };
165
+ }
166
+ parsed = decoded;
167
+ } catch {
168
+ return { busy: true, detail: `malformed discovery entry (${file})` };
169
+ }
170
+ if (parsed.isManager === true) continue;
171
+ if (parsed.unattended !== true) continue;
172
+ const pid = parsed.pid;
173
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
174
+ blocking.push(`${file}(invalid-pid)`);
175
+ continue;
176
+ }
177
+ if (pid === process.pid) continue;
178
+ if (pidDefinitelyDead(pid)) continue;
179
+ const state = typeof parsed.state === "string" && parsed.state ? parsed.state : "unknown";
180
+ if (state !== "idle") {
181
+ const name = typeof parsed.displayName === "string" && parsed.displayName ? parsed.displayName : String(pid);
182
+ blocking.push(`${name}(${state})`);
183
+ }
184
+ }
185
+ return blocking.length > 0 ? { busy: true, detail: blocking.join(", ") } : { busy: false };
186
+ }
187
+
188
+ // src/commands/manager-upgrade.ts
21
189
  function upgradePaths(entryPath) {
22
190
  const home = os.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
23
191
  const override = process.env.PIE_IPC_CONFIG_DIR;
24
192
  const agentDir = process.env.PIE_CODING_AGENT_DIR?.trim();
25
- const raw = override !== void 0 ? override : agentDir || path.join(home, ".pie");
26
- const configDir = process.platform === "win32" ? raw : path.resolve(raw === "~" ? home : raw.startsWith("~/") ? path.join(home, raw.slice(2)) : raw);
193
+ const raw = override !== void 0 ? override : agentDir || path2.join(home, ".pie");
194
+ const configDir = process.platform === "win32" ? raw : path2.resolve(raw === "~" ? home : raw.startsWith("~/") ? path2.join(home, raw.slice(2)) : raw);
27
195
  return {
28
- workspaceDir: path.join(configDir, "manager"),
29
- discoveryDir: path.join(configDir, "run", "ipc"),
30
- stateFile: path.join(configDir, "manager", "manager.json"),
31
- resultFile: path.join(configDir, "manager", "upgrade.json"),
32
- lockFile: path.join(configDir, "manager", "upgrade.lock"),
196
+ workspaceDir: path2.join(configDir, "manager"),
197
+ discoveryDir: path2.join(configDir, "run", "ipc"),
198
+ stateFile: path2.join(configDir, "manager", "manager.json"),
199
+ resultFile: path2.join(configDir, "manager", "upgrade.json"),
200
+ lockFile: path2.join(configDir, "manager", "upgrade.lock"),
33
201
  entryPath
34
202
  };
35
203
  }
36
204
  function isDistInstall(entryPath) {
37
- let resolved = path.resolve(entryPath);
205
+ let resolved = path2.resolve(entryPath);
38
206
  try {
39
- resolved = fs.realpathSync(resolved);
207
+ resolved = fs2.realpathSync(resolved);
40
208
  } catch {
41
209
  }
42
210
  return /node_modules[\\/]@cydm[\\/]pie[\\/]dist[\\/]cli\.(js|mjs)$/.test(resolved);
@@ -46,23 +214,23 @@ function versionDiffers(a, b) {
46
214
  return canon(a) !== canon(b);
47
215
  }
48
216
  function resolveNpm(nodePath, platform = process.platform, env = process.env) {
49
- const nodeDir = path.dirname(nodePath);
50
- const prefix = path.dirname(nodeDir);
217
+ const nodeDir = path2.dirname(nodePath);
218
+ const prefix = path2.dirname(nodeDir);
51
219
  const windows = platform === "win32";
52
220
  const candidates = [
53
- path.join(nodeDir, "node_modules", "npm", "bin", "npm-cli.js"),
54
- path.join(prefix, "lib", "node_modules", "npm", "bin", "npm-cli.js"),
55
- path.join(prefix, "node_modules", "npm", "bin", "npm-cli.js")
221
+ path2.join(nodeDir, "node_modules", "npm", "bin", "npm-cli.js"),
222
+ path2.join(prefix, "lib", "node_modules", "npm", "bin", "npm-cli.js"),
223
+ path2.join(prefix, "node_modules", "npm", "bin", "npm-cli.js")
56
224
  ];
57
225
  if (windows) {
58
226
  const searchPath = Object.entries(env).find(([key]) => key.toUpperCase() === "PATH")?.[1] ?? "";
59
227
  for (const dir of searchPath.split(";").filter(Boolean)) {
60
- candidates.push(path.resolve(dir.replace(/^"(.*)"$/, "$1"), "node_modules", "npm", "bin", "npm-cli.js"));
228
+ candidates.push(path2.resolve(dir.replace(/^"(.*)"$/, "$1"), "node_modules", "npm", "bin", "npm-cli.js"));
61
229
  }
62
230
  }
63
231
  const isFile = (file) => {
64
232
  try {
65
- return fs.statSync(file).isFile();
233
+ return fs2.statSync(file).isFile();
66
234
  } catch {
67
235
  return false;
68
236
  }
@@ -71,12 +239,12 @@ function resolveNpm(nodePath, platform = process.platform, env = process.env) {
71
239
  if (isFile(npmCli)) return { command: nodePath, prefixArgs: [npmCli], reason: `node + ${npmCli}` };
72
240
  }
73
241
  const binary = windows ? "npm.exe" : "npm";
74
- const sibling = path.join(nodeDir, binary);
242
+ const sibling = path2.join(nodeDir, binary);
75
243
  if (isFile(sibling)) return { command: sibling, prefixArgs: [], reason: `sibling ${sibling}` };
76
244
  return { command: binary, prefixArgs: [], reason: `PATH ${binary}` };
77
245
  }
78
246
  function runNpm(plan, args, timeoutMs) {
79
- const child = spawnSync(plan.command, [...plan.prefixArgs, ...args], {
247
+ const child = spawnSync2(plan.command, [...plan.prefixArgs, ...args], {
80
248
  encoding: "utf8",
81
249
  timeout: timeoutMs,
82
250
  windowsHide: true,
@@ -109,7 +277,7 @@ function parseViewVersion(stdout) {
109
277
  }
110
278
  function readDiscoveryEntry(discoveryDir, file) {
111
279
  try {
112
- const parsed = JSON.parse(fs.readFileSync(path.join(discoveryDir, file), "utf8"));
280
+ const parsed = JSON.parse(fs2.readFileSync(path2.join(discoveryDir, file), "utf8"));
113
281
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
114
282
  return parsed;
115
283
  } catch {
@@ -119,7 +287,7 @@ function readDiscoveryEntry(discoveryDir, file) {
119
287
  function scanWorkers(discoveryDir) {
120
288
  const out = [];
121
289
  try {
122
- const files = fs.readdirSync(discoveryDir).filter((f) => f.endsWith(".json"));
290
+ const files = fs2.readdirSync(discoveryDir).filter((f) => f.endsWith(".json"));
123
291
  for (const file of files.slice(0, 256)) {
124
292
  const parsed = readDiscoveryEntry(discoveryDir, file);
125
293
  if (!parsed) continue;
@@ -128,8 +296,8 @@ function scanWorkers(discoveryDir) {
128
296
  if (parsed.unattended !== true || parsed.isManager === true) continue;
129
297
  try {
130
298
  process.kill(parsed.pid, 0);
131
- } catch {
132
- continue;
299
+ } catch (error) {
300
+ if (error.code === "ESRCH") continue;
133
301
  }
134
302
  out.push({
135
303
  pid: parsed.pid,
@@ -154,7 +322,7 @@ function partitionWorkers(peers) {
154
322
  }
155
323
  function findManagerResident(discoveryDir, sessionId) {
156
324
  try {
157
- const files = fs.readdirSync(discoveryDir).filter((f) => f.endsWith(".json"));
325
+ const files = fs2.readdirSync(discoveryDir).filter((f) => f.endsWith(".json"));
158
326
  for (const file of files.slice(0, 256)) {
159
327
  const parsed = readDiscoveryEntry(discoveryDir, file);
160
328
  if (!parsed || parsed.isManager !== true || typeof parsed.pid !== "number" || !Number.isInteger(parsed.pid) || parsed.pid <= 0) continue;
@@ -185,7 +353,7 @@ function residentCommandLineLooksLikePie(pid, sessionToken) {
185
353
  function processStartedAt(pid) {
186
354
  if (process.platform !== "darwin" && process.platform !== "linux") return void 0;
187
355
  try {
188
- const out = spawnSync("ps", ["-p", String(pid), "-o", "lstart="], { encoding: "utf8", timeout: 5e3 });
356
+ const out = spawnSync2("ps", ["-p", String(pid), "-o", "lstart="], { encoding: "utf8", timeout: 5e3 });
189
357
  const parsed = out.status === 0 ? Date.parse((out.stdout ?? "").trim()) : NaN;
190
358
  return Number.isFinite(parsed) ? parsed : void 0;
191
359
  } catch {
@@ -231,12 +399,28 @@ async function performUpgrade(paths, effects, options) {
231
399
  if (busy.busy) {
232
400
  return finish(build("guard", `refused: the manager is ${busy.state ?? "busy"} (an active turn would be cancelled); retry when idle`));
233
401
  }
402
+ if (state.service === true && effects.serviceRestartWorkersBusy) {
403
+ const workersBusy = effects.serviceRestartWorkersBusy();
404
+ if (workersBusy.busy) {
405
+ return finish(build("guard", `refused: service restart could terminate active/unverified worker(s) (${workersBusy.detail ?? "unknown"}); retry when workers are idle`));
406
+ }
407
+ }
234
408
  stage = "install";
235
409
  const view = options.target === "latest" ? effects.npmViewLatest() : { version: options.target, tail: "" };
236
410
  const toVersion = view.version;
237
411
  if (!toVersion) {
238
412
  return finish(build("install", `could not resolve the target version (${options.target}): ${view.tail || "npm view returned nothing usable"}`));
239
413
  }
414
+ const busyAfterView = effects.managerBusy();
415
+ if (busyAfterView.busy) {
416
+ return finish(build("guard", `refused: the manager became ${busyAfterView.state ?? "busy"} while resolving version (an active turn would be cancelled); retry when idle`));
417
+ }
418
+ if (state.service === true && effects.serviceRestartWorkersBusy) {
419
+ const workersBusyAfterView = effects.serviceRestartWorkersBusy();
420
+ if (workersBusyAfterView.busy) {
421
+ return finish(build("guard", `refused: service restart could terminate active/unverified worker(s) (${workersBusyAfterView.detail ?? "unknown"}); retry when workers are idle`));
422
+ }
423
+ }
240
424
  const differs = versionDiffers(fromVersion, toVersion);
241
425
  const residency = effects.residentStatus(state);
242
426
  if (!differs && !options.force) {
@@ -283,8 +467,24 @@ ${target.detail}${recovery}`));
283
467
  }
284
468
  async function restartAndRecycle(effects, paths, state, fromVersion, toVersion, setStage, build) {
285
469
  setStage("restart");
470
+ const busyBeforeRestart = effects.managerBusy();
471
+ if (busyBeforeRestart.busy) {
472
+ return build(
473
+ "restart",
474
+ `refused: @cydm/pie@${toVersion} is installed, but the manager became ${busyBeforeRestart.state ?? "busy"} before restart (an active turn would be cancelled); restart deferred \u2014 restart the manager once idle (pie manager stop && pie manager start, or pie manager upgrade --force).`
475
+ );
476
+ }
286
477
  let successorPid;
287
478
  if (state.service === true) {
479
+ if (effects.serviceRestartWorkersBusy) {
480
+ const workersBusy = effects.serviceRestartWorkersBusy();
481
+ if (workersBusy.busy) {
482
+ return build(
483
+ "restart",
484
+ `refused: @cydm/pie@${toVersion} is installed, but service restart could terminate active/unverified worker(s) (${workersBusy.detail ?? "unknown"}); restart deferred \u2014 retry once workers are idle.`
485
+ );
486
+ }
487
+ }
288
488
  const restarted = effects.serviceRestart(state, toVersion);
289
489
  if (!restarted.ok) {
290
490
  return build("restart", `service restart not verified: ${restarted.detail ?? "unknown"}. The install succeeded; run pie manager upgrade again (repair) or restart the service manually.`);
@@ -333,121 +533,65 @@ async function restartAndRecycle(effects, paths, state, fromVersion, toVersion,
333
533
  }
334
534
  function readUpgradeResult(resultFile) {
335
535
  try {
336
- return JSON.parse(fs.readFileSync(resultFile, "utf8"));
536
+ return JSON.parse(fs2.readFileSync(resultFile, "utf8"));
337
537
  } catch {
338
538
  return void 0;
339
539
  }
340
540
  }
341
541
  function writeResultAtomic(resultFile, result, log) {
342
542
  try {
343
- fs.mkdirSync(path.dirname(resultFile), { recursive: true });
543
+ fs2.mkdirSync(path2.dirname(resultFile), { recursive: true });
344
544
  const tmp = `${resultFile}.${process.pid}.tmp`;
345
- fs.writeFileSync(tmp, `${JSON.stringify(result, null, " ")}
545
+ fs2.writeFileSync(tmp, `${JSON.stringify(result, null, " ")}
346
546
  `);
347
- fs.renameSync(tmp, resultFile);
547
+ fs2.renameSync(tmp, resultFile);
348
548
  } catch (error) {
349
549
  log(`upgrade: could not write the result file: ${error instanceof Error ? error.message : String(error)}`);
350
550
  }
351
551
  }
352
- function tryLockWithReclamation(lockFile) {
353
- const attempt = () => {
354
- try {
355
- fs.mkdirSync(path.dirname(lockFile), { recursive: true });
356
- const tmp = `${lockFile}.${process.pid}.tmp`;
357
- fs.writeFileSync(tmp, JSON.stringify({ pid: process.pid, at: Date.now() }));
358
- fs.linkSync(tmp, lockFile);
359
- try {
360
- fs.rmSync(tmp, { force: true });
361
- } catch {
362
- }
363
- return true;
364
- } catch {
365
- try {
366
- fs.rmSync(`${lockFile}.${process.pid}.tmp`, { force: true });
367
- } catch {
368
- }
369
- return false;
370
- }
371
- };
372
- if (attempt()) return true;
373
- let holderPid;
374
- try {
375
- const holder = JSON.parse(fs.readFileSync(lockFile, "utf8"));
376
- if (typeof holder.pid === "number" && Number.isInteger(holder.pid) && holder.pid > 0) holderPid = holder.pid;
377
- } catch {
378
- }
379
- if (holderPid === void 0) return false;
380
- try {
381
- process.kill(holderPid, 0);
382
- return false;
383
- } catch (error) {
384
- if (error.code !== "ESRCH") return false;
385
- }
386
- try {
387
- fs.rmSync(lockFile, { force: true });
388
- } catch {
389
- }
390
- if (!attempt()) return false;
391
- try {
392
- const verify = JSON.parse(fs.readFileSync(lockFile, "utf8"));
393
- return verify.pid === process.pid;
394
- } catch {
395
- return false;
396
- }
397
- }
398
- function unlockOwned(lockFile) {
399
- try {
400
- const holder = JSON.parse(fs.readFileSync(lockFile, "utf8"));
401
- if (holder.pid !== process.pid) return;
402
- } catch {
403
- }
404
- try {
405
- fs.rmSync(lockFile, { force: true });
406
- } catch {
407
- }
408
- }
409
552
  function insideServiceCgroup() {
410
553
  if (process.platform !== "linux") return false;
411
554
  try {
412
- return fs.readFileSync("/proc/self/cgroup", "utf8").includes("dev.pie.manager");
555
+ return fs2.readFileSync("/proc/self/cgroup", "utf8").includes("dev.pie.manager");
413
556
  } catch {
414
557
  return false;
415
558
  }
416
559
  }
417
560
  function cliEffects(paths, log) {
418
561
  const npm = resolveNpm(process.execPath);
562
+ let activeLock = null;
419
563
  const effects = {
420
564
  npmInstall: (target) => runNpm(npm, ["install", "-g", `@cydm/pie@${target}`], 5 * 6e4),
421
565
  installTargetCheck: () => {
422
566
  try {
423
- const rootRaw = spawnSync(npm.command, [...npm.prefixArgs, "root", "-g"], { encoding: "utf8", timeout: 3e4, windowsHide: true });
567
+ const rootRaw = spawnSync2(npm.command, [...npm.prefixArgs, "root", "-g"], { encoding: "utf8", timeout: 3e4, windowsHide: true });
424
568
  const npmRoot = String(rootRaw.stdout ?? "").trim().split(/\r?\n/).filter(Boolean).pop() ?? "";
425
569
  if (rootRaw.status !== 0 || !npmRoot) return { ok: false, detail: `npm root -g failed (exit ${rootRaw.status}): ${String(rootRaw.stderr ?? "").slice(-200)}` };
426
570
  let entry;
427
571
  try {
428
- entry = fs.realpathSync(paths.entryPath);
572
+ entry = fs2.realpathSync(paths.entryPath);
429
573
  } catch {
430
574
  return { ok: false, detail: `entry ${paths.entryPath} is not resolvable` };
431
575
  }
432
- let dir = path.dirname(entry);
576
+ let dir = path2.dirname(entry);
433
577
  let pkgRoot;
434
578
  for (let i = 0; i < 6 && dir; i += 1) {
435
- if (fs.existsSync(path.join(dir, "package.json"))) {
579
+ if (fs2.existsSync(path2.join(dir, "package.json"))) {
436
580
  pkgRoot = dir;
437
581
  break;
438
582
  }
439
- const parent = path.dirname(dir);
583
+ const parent = path2.dirname(dir);
440
584
  if (parent === dir) break;
441
585
  dir = parent;
442
586
  }
443
587
  let installedPkg;
444
588
  try {
445
- installedPkg = fs.realpathSync(path.join(npmRoot, "@cydm", "pie"));
589
+ installedPkg = fs2.realpathSync(path2.join(npmRoot, "@cydm", "pie"));
446
590
  } catch {
447
591
  return { ok: false, detail: `npm root ${npmRoot} has no @cydm/pie installed (realpath failed) \u2014 the install did not land in this npm's global tree.` };
448
592
  }
449
593
  if (pkgRoot === void 0 || installedPkg !== pkgRoot) {
450
- return { ok: false, detail: `npm installed ${installedPkg} but the running entry resolves to ${pkgRoot ?? path.dirname(entry)} \u2014 a different prefix owns this Pie (multi-Node or custom npm prefix); the restart would keep the OLD code. Install with the npm that owns ${pkgRoot ?? entry} or fix the entry resolution.` };
594
+ return { ok: false, detail: `npm installed ${installedPkg} but the running entry resolves to ${pkgRoot ?? path2.dirname(entry)} \u2014 a different prefix owns this Pie (multi-Node or custom npm prefix); the restart would keep the OLD code. Install with the npm that owns ${pkgRoot ?? entry} or fix the entry resolution.` };
451
595
  }
452
596
  return { ok: true, detail: `install target verified: ${pkgRoot}` };
453
597
  } catch (error) {
@@ -461,7 +605,7 @@ function cliEffects(paths, log) {
461
605
  },
462
606
  readState: () => {
463
607
  try {
464
- return JSON.parse(fs.readFileSync(paths.stateFile, "utf8"));
608
+ return JSON.parse(fs2.readFileSync(paths.stateFile, "utf8"));
465
609
  } catch {
466
610
  return void 0;
467
611
  }
@@ -476,14 +620,30 @@ function cliEffects(paths, log) {
476
620
  return residentCommandLineLooksLikePie(state.pid, state.sessionId) !== void 0 ? "alive" : "foreign";
477
621
  }
478
622
  const resident = findManagerResident(paths.discoveryDir, state.sessionId);
479
- if (!resident) return "dead";
623
+ if (!resident) {
624
+ if (state.service === true) {
625
+ return queryPlatformServiceState() === "stopped" ? "dead" : "unknown";
626
+ }
627
+ return "dead";
628
+ }
480
629
  return residentCommandLineLooksLikePie(resident.pid, state.sessionId) !== void 0 ? "alive" : "unknown";
481
630
  },
482
631
  managerBusy: () => {
483
632
  const state = effects.readState();
484
633
  const resident = findManagerResident(paths.discoveryDir, state?.sessionId);
485
- if (!resident) return { busy: false };
486
- if (resident.state === "working" || resident.state === "blocked") return { busy: true, state: resident.state };
634
+ if (!resident) {
635
+ if (state && typeof state.pid === "number" && state.pid > 0 && effects.residentStatus(state) === "alive") {
636
+ return { busy: true, state: "unknown (discovery unavailable)" };
637
+ }
638
+ if (state?.service === true) {
639
+ const svcState = queryPlatformServiceState();
640
+ if (svcState !== "stopped") {
641
+ return { busy: true, state: `unknown (service ${svcState} without discovery)` };
642
+ }
643
+ }
644
+ return { busy: false };
645
+ }
646
+ if (resident.state !== "idle") return { busy: true, state: resident.state ?? "unknown" };
487
647
  return { busy: false };
488
648
  },
489
649
  terminateResident: (state) => {
@@ -526,7 +686,7 @@ function cliEffects(paths, log) {
526
686
  }
527
687
  },
528
688
  startSuccessor: () => {
529
- const child = spawnSync(
689
+ const child = spawnSync2(
530
690
  process.execPath,
531
691
  [paths.entryPath, "manager", "start"],
532
692
  { encoding: "utf8", timeout: 9e4, windowsHide: true, cwd: paths.workspaceDir, env: process.env }
@@ -544,7 +704,7 @@ function cliEffects(paths, log) {
544
704
  return { pid: void 0, detail: `pie manager start reported pid ${pid} but no readiness marker: ${out.slice(-300)}` };
545
705
  }
546
706
  try {
547
- const recorded = JSON.parse(fs.readFileSync(paths.stateFile, "utf8"));
707
+ const recorded = JSON.parse(fs2.readFileSync(paths.stateFile, "utf8"));
548
708
  if (recorded.pid !== pid) return { pid: void 0, detail: `recorded state pid ${String(recorded.pid)} \u2260 started pid ${pid} (replaced or stopped concurrently)` };
549
709
  process.kill(pid, 0);
550
710
  } catch (error) {
@@ -556,7 +716,7 @@ function cliEffects(paths, log) {
556
716
  if (insideServiceCgroup()) {
557
717
  try {
558
718
  const unit = `dev.pie.manager-upgrade-${process.pid}`;
559
- const delegated = spawnSync("systemd-run", ["--user", "--unit", unit, "--collect", "systemctl", "--user", "restart", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4 });
719
+ const delegated = spawnSync2("systemd-run", ["--user", "--unit", unit, "--collect", "systemctl", "--user", "restart", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4 });
560
720
  return { ok: false, detail: `restart delegated to transient unit ${unit} (${delegated.status === 0 ? "accepted" : `systemd-run exit ${delegated.status}`}); the actor runs inside the service cgroup and cannot verify the outcome \u2014 check pie manager status afterwards` };
561
721
  } catch (error) {
562
722
  return { ok: false, detail: `could not delegate the service restart: ${error instanceof Error ? error.message : String(error)}` };
@@ -568,16 +728,16 @@ function cliEffects(paths, log) {
568
728
  try {
569
729
  if (process.platform === "darwin") {
570
730
  const uid = process.getuid?.() ?? 501;
571
- const r = spawnSync("launchctl", ["kickstart", "-k", `gui/${uid}/dev.pie.manager`], { encoding: "utf8", timeout: 2e4 });
731
+ const r = spawnSync2("launchctl", ["kickstart", "-k", `gui/${uid}/dev.pie.manager`], { encoding: "utf8", timeout: 2e4 });
572
732
  restartDetail = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
573
733
  restartFailed = r.status !== 0;
574
734
  } else if (process.platform === "linux") {
575
- const r = spawnSync("systemctl", ["--user", "restart", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4 });
735
+ const r = spawnSync2("systemctl", ["--user", "restart", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4 });
576
736
  restartDetail = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
577
737
  restartFailed = r.status !== 0;
578
738
  } else if (process.platform === "win32") {
579
- spawnSync("schtasks", ["/End", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4, windowsHide: true });
580
- const r = spawnSync("schtasks", ["/Run", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4, windowsHide: true });
739
+ spawnSync2("schtasks", ["/End", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4, windowsHide: true });
740
+ const r = spawnSync2("schtasks", ["/Run", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4, windowsHide: true });
581
741
  restartDetail = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
582
742
  restartFailed = r.status !== 0;
583
743
  } else {
@@ -627,8 +787,15 @@ function cliEffects(paths, log) {
627
787
  }
628
788
  },
629
789
  writeResult: (result) => writeResultAtomic(paths.resultFile, result, log),
630
- tryLock: () => tryLockWithReclamation(paths.lockFile),
631
- unlock: () => unlockOwned(paths.lockFile),
790
+ tryLock: () => {
791
+ activeLock = acquireUpgradeLock(paths.lockFile);
792
+ return activeLock !== null;
793
+ },
794
+ unlock: () => {
795
+ activeLock?.release();
796
+ activeLock = null;
797
+ },
798
+ ...process.platform === "linux" || process.platform === "win32" ? { serviceRestartWorkersBusy: () => scanLinuxServiceBlockingWorkers(paths.discoveryDir) } : {},
632
799
  ...process.platform === "win32" ? {
633
800
  preInstallStop: (state) => runWindowsPreInstallStop(state, {
634
801
  scanBlockingPeers: (s) => scanBlockingWindowsPeers(paths.discoveryDir, s.sessionId, s.pid, {
@@ -640,13 +807,14 @@ function cliEffects(paths, log) {
640
807
  residentStatus: (s) => effects.residentStatus(s),
641
808
  terminateResident: (s) => effects.terminateResident(s),
642
809
  endServiceTask: () => {
643
- const r = spawnSync("schtasks", ["/End", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4, windowsHide: true });
810
+ const r = spawnSync2("schtasks", ["/End", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4, windowsHide: true });
644
811
  return {
645
812
  status: r.status,
646
813
  detail: `${r.stdout ?? ""} ${r.stderr ?? ""}`.trim().slice(0, 200),
647
814
  ...r.error ? { spawnError: r.error.message } : {}
648
815
  };
649
816
  },
817
+ isServiceTaskRunning: () => queryWindowsServiceTaskState(),
650
818
  waitExit: (pid, timeoutMs) => effects.waitExit(pid, timeoutMs),
651
819
  isPidAlive: (pid) => {
652
820
  try {
@@ -672,18 +840,25 @@ function parseTarget(raw) {
672
840
  return /^\d+\.\d+\.\d+(-[\w.-]+)?$/.test(raw.trim()) ? raw.trim() : void 0;
673
841
  }
674
842
  export {
843
+ acquireUpgradeLock,
675
844
  cliEffects,
676
845
  findManagerResident,
677
846
  isDistInstall,
847
+ parseLaunchctlServiceState,
848
+ parseSystemctlServiceState,
678
849
  parseTarget,
679
850
  parseViewVersion,
851
+ parseWindowsTaskNumericState,
680
852
  partitionWorkers,
681
853
  performUpgrade,
682
854
  processStartedAt,
855
+ queryPlatformServiceState,
856
+ queryWindowsServiceTaskState,
683
857
  readUpgradeResult,
684
858
  residentCommandLineLooksLikePie,
685
859
  resolveNpm,
686
860
  runNpm,
861
+ scanLinuxServiceBlockingWorkers,
687
862
  scanWorkers,
688
863
  upgradePaths,
689
864
  versionDiffers
@@ -0,0 +1,19 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ commitCuratedMemoryBestEffort,
4
+ ensureMemoryGitIgnore,
5
+ isMemoryGitInitialized,
6
+ readCuratedMemoryGitLog
7
+ } from "./chunk-26ILLZKQ.js";
8
+ import "./chunk-KW46ND3S.js";
9
+ import "./chunk-SXBX2P5R.js";
10
+ import "./chunk-BQWHLYYZ.js";
11
+ import "./chunk-G2K4GY6N.js";
12
+ import "./chunk-XXGYUYXI.js";
13
+ import "./chunk-LZQXQOPJ.js";
14
+ export {
15
+ commitCuratedMemoryBestEffort,
16
+ ensureMemoryGitIgnore,
17
+ isMemoryGitInitialized,
18
+ readCuratedMemoryGitLog
19
+ };