@cydm/pie 4.4.3 → 4.5.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.
@@ -27,7 +27,7 @@ import {
27
27
  takeDispatchFrame,
28
28
  wrapInboundText,
29
29
  wrappedMessageMarker
30
- } from "../../../chunks/chunk-JMKLTTZQ.js";
30
+ } from "../../../chunks/chunk-2CJIENLY.js";
31
31
  import "../../../chunks/chunk-ZPJ3BNQB.js";
32
32
  import "../../../chunks/chunk-LZQXQOPJ.js";
33
33
 
@@ -276,6 +276,7 @@ function windowsSecurity() {
276
276
  // builtin/extensions/pie-ipc/discovery.ts
277
277
  import * as path3 from "node:path";
278
278
  import { randomBytes as randomBytes2 } from "node:crypto";
279
+ import { fileURLToPath } from "node:url";
279
280
  function ipcDiscoveryDir(configDir) {
280
281
  return process.platform === "win32" ? `${canonicalWindowsDirectory(configDir)}\\run\\ipc` : path3.join(configDir, "run", "ipc");
281
282
  }
@@ -451,9 +452,32 @@ function buildStatusFile(input) {
451
452
  state: "idle",
452
453
  undeliveredInjections: 0,
453
454
  port: input.port,
454
- ...input.unattended === true ? { unattended: true } : {}
455
+ ...input.unattended === true ? { unattended: true } : {},
456
+ // 4.4.4: the running pie's version (upgrade visibility — the panel
457
+ // shows which peers are on stale code). Additive: old peers simply
458
+ // omit it and readers render "—".
459
+ ...piePackageVersion() ? { version: piePackageVersion() } : {}
455
460
  };
456
461
  }
462
+ function piePackageVersion() {
463
+ if (cachedVersion !== void 0) return cachedVersion || void 0;
464
+ try {
465
+ const here = path3.dirname(fileURLToPath(import.meta.url));
466
+ for (const up of [3, 4, 5]) {
467
+ const pkgPath = path3.resolve(here, ...Array(up).fill(".."), "package.json");
468
+ if (!fs2.existsSync(pkgPath)) continue;
469
+ const parsed = JSON.parse(fs2.readFileSync(pkgPath, "utf8"));
470
+ if (parsed.name === "@cydm/pie" && typeof parsed.version === "string") {
471
+ cachedVersion = parsed.version;
472
+ return parsed.version;
473
+ }
474
+ }
475
+ } catch {
476
+ }
477
+ cachedVersion = "";
478
+ return void 0;
479
+ }
480
+ var cachedVersion;
457
481
 
458
482
  // builtin/extensions/pie-ipc/delivery.ts
459
483
  var AllowPolicy = class {
@@ -556,7 +556,15 @@ function pieProc(ctx) {
556
556
  PIE_IPC_CONFIG_DIR: inheritedIpcRoot,
557
557
  PIE_IPC_DISPLAY_NAME: params.kind === "resident" ? params.name : process.env.PIE_IPC_DISPLAY_NAME
558
558
  };
559
- if (params.kind === "oneshot") childEnv[ONESHOT_TASK_ENV] = params.task ?? "";
559
+ if (params.kind === "oneshot") {
560
+ childEnv[ONESHOT_TASK_ENV] = params.task ?? "";
561
+ const explicitTimeout = Number(childEnv.PIE_PRINT_TURN_TIMEOUT_MS);
562
+ const validOverride = Number.isFinite(explicitTimeout) && explicitTimeout > 0 && String(explicitTimeout) === String(childEnv.PIE_PRINT_TURN_TIMEOUT_MS).trim();
563
+ if (childEnv.PIE_PRINT_TURN_TIMEOUT_MS === "0") {
564
+ } else if (!validOverride) {
565
+ childEnv.PIE_PRINT_TURN_TIMEOUT_MS = "1800000";
566
+ }
567
+ }
560
568
  if (resumeSessionId && resumeSessionsDir !== void 0) childEnv.PIE_SESSIONS_DIR = resumeSessionsDir;
561
569
  try {
562
570
  child = spawn(process.execPath, args, {
@@ -776,6 +776,7 @@ function parseStatusFile(raw) {
776
776
  };
777
777
  if (typeof record.unattended === "boolean") file.unattended = record.unattended;
778
778
  if (typeof record.isManager === "boolean") file.isManager = record.isManager;
779
+ if (typeof record.version === "string" && record.version.length <= 64 && !hasControlChars(record.version)) file.version = record.version;
779
780
  if (typeof record.imBinding === "string" && record.imBinding.length <= 512 && !hasControlChars(record.imBinding)) file.imBinding = record.imBinding;
780
781
  if (Array.isArray(record.allowPeers) && record.allowPeers.length <= 1e3 && record.allowPeers.every((id) => typeof id === "string" && (id === "*" || isValidInstanceId(id)))) file.allowPeers = record.allowPeers;
781
782
  if (typeof record.secret === "string" && /^[a-f0-9]{64}$/.test(record.secret)) file.secret = record.secret;
@@ -774,6 +774,34 @@ function withStartLock(dir, fn) {
774
774
  }
775
775
  });
776
776
  }
777
+ async function runUpgradeCommand(args) {
778
+ const { upgradePaths, performUpgrade, cliEffects, parseTarget } = await import("./manager-upgrade-5CPKTRJ7.js");
779
+ const targetIdx = args.indexOf("--target");
780
+ if (targetIdx >= 0 && typeof args[targetIdx + 1] !== "string") {
781
+ console.error('--target expects "latest" or an x.y.z version (no value given)');
782
+ process.exitCode = 2;
783
+ return;
784
+ }
785
+ const target = parseTarget(targetIdx >= 0 ? args[targetIdx + 1] : void 0);
786
+ if (target === void 0) {
787
+ const given = targetIdx >= 0 ? args[targetIdx + 1] : void 0;
788
+ console.error(`--target expects "latest" or an x.y.z version (got ${JSON.stringify(given)})`);
789
+ process.exitCode = 2;
790
+ return;
791
+ }
792
+ const force = args.includes("--force");
793
+ const paths = upgradePaths(process.argv[1] ?? "");
794
+ console.log(`Upgrading @cydm/pie \u2192 ${target} (this may take a minute)\u2026`);
795
+ const result = await performUpgrade(paths, cliEffects(paths, (m) => console.log(m)), { target, force });
796
+ if (result.ok) {
797
+ console.log(`\u2713 Upgraded ${result.fromVersion} \u2192 ${result.toVersion}`);
798
+ if (result.workersRecycled?.length) console.log(` recycled idle workers: ${result.workersRecycled.map((w) => `${w.name}(${w.pid})`).join(", ")}`);
799
+ if (result.workersSkipped?.length) console.log(` busy workers left as-is: ${result.workersSkipped.map((w) => `${w.name}(${w.pid})`).join(", ")}`);
800
+ } else {
801
+ console.error(`\u2717 Upgrade stopped at "${result.stage}": ${result.detail ?? "unknown"}`);
802
+ process.exitCode = 1;
803
+ }
804
+ }
777
805
  async function runManagerCommand(args) {
778
806
  const sub = args[0] ?? "";
779
807
  const dir = sub === "tail" ? tailWorkspaceDir() : workspaceDir();
@@ -969,6 +997,10 @@ async function runManagerCommand(args) {
969
997
  process.exitCode = 2;
970
998
  return;
971
999
  }
1000
+ if (sub === "upgrade") {
1001
+ await runUpgradeCommand(args.slice(1));
1002
+ return;
1003
+ }
972
1004
  if (sub === "tail") {
973
1005
  const follow = args.includes("-f") || args.includes("--follow");
974
1006
  const jsonOut = args.includes("--json");
@@ -0,0 +1,562 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ readProcessCommandLine
4
+ } from "./chunk-X6LBWHK3.js";
5
+ import {
6
+ VERSION
7
+ } from "./chunk-CBDQJMUI.js";
8
+ import "./chunk-LZQXQOPJ.js";
9
+
10
+ // src/commands/manager-upgrade.ts
11
+ import { spawnSync } from "node:child_process";
12
+ import * as fs from "node:fs";
13
+ import * as os from "node:os";
14
+ import * as path from "node:path";
15
+ function upgradePaths(entryPath) {
16
+ const home = os.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
17
+ const override = process.env.PIE_IPC_CONFIG_DIR;
18
+ const agentDir = process.env.PIE_CODING_AGENT_DIR?.trim();
19
+ const raw = override !== void 0 ? override : agentDir || path.join(home, ".pie");
20
+ const configDir = process.platform === "win32" ? raw : path.resolve(raw === "~" ? home : raw.startsWith("~/") ? path.join(home, raw.slice(2)) : raw);
21
+ return {
22
+ workspaceDir: path.join(configDir, "manager"),
23
+ discoveryDir: path.join(configDir, "run", "ipc"),
24
+ stateFile: path.join(configDir, "manager", "manager.json"),
25
+ resultFile: path.join(configDir, "manager", "upgrade.json"),
26
+ lockFile: path.join(configDir, "manager", "upgrade.lock"),
27
+ entryPath
28
+ };
29
+ }
30
+ function isDistInstall(entryPath) {
31
+ let resolved = path.resolve(entryPath);
32
+ try {
33
+ resolved = fs.realpathSync(resolved);
34
+ } catch {
35
+ }
36
+ return /node_modules[\\/]@cydm[\\/]pie[\\/]dist[\\/]cli\.(js|mjs)$/.test(resolved);
37
+ }
38
+ function versionDiffers(a, b) {
39
+ const canon = (v) => v.trim().replace(/^v/, "").split("+")[0];
40
+ return canon(a) !== canon(b);
41
+ }
42
+ function resolveNpm(nodePath) {
43
+ const prefix = path.dirname(path.dirname(nodePath));
44
+ for (const npmCli of [
45
+ path.join(prefix, "lib", "node_modules", "npm", "bin", "npm-cli.js"),
46
+ path.join(prefix, "node_modules", "npm", "bin", "npm-cli.js")
47
+ ]) {
48
+ if (fs.existsSync(npmCli)) return { command: nodePath, prefixArgs: [npmCli], reason: `node + ${npmCli}` };
49
+ }
50
+ const sibling = path.join(path.dirname(nodePath), "npm");
51
+ if (fs.existsSync(sibling)) return { command: sibling, prefixArgs: [], reason: `sibling ${sibling}` };
52
+ return { command: "npm", prefixArgs: [], reason: "PATH npm" };
53
+ }
54
+ function runNpm(plan, args, timeoutMs) {
55
+ const child = spawnSync(plan.command, [...plan.prefixArgs, ...args], {
56
+ encoding: "utf8",
57
+ timeout: timeoutMs,
58
+ windowsHide: true,
59
+ cwd: os.tmpdir(),
60
+ maxBuffer: 8 * 1024 * 1024
61
+ });
62
+ const sanitize = (text) => text.replace(/[^\x20-\x7e\n\t]/g, "?").trim();
63
+ const stdout = sanitize(child.stdout ?? "");
64
+ const stderr = sanitize(child.stderr ?? "");
65
+ const lines = [stdout, stderr].join("\n").split("\n").filter(Boolean);
66
+ return { code: child.status, stdout, stderr, tail: lines.slice(-8).join("\n").slice(0, 1200) };
67
+ }
68
+ var STRICT_VERSION = /^\d+\.\d+\.\d+(?:[-+][\w.+-]+)?$/;
69
+ function parseViewVersion(stdout) {
70
+ const trimmed = stdout.trim();
71
+ if (!trimmed) return void 0;
72
+ try {
73
+ const parsed = JSON.parse(trimmed);
74
+ if (typeof parsed === "string" && STRICT_VERSION.test(parsed)) return parsed;
75
+ return void 0;
76
+ } catch {
77
+ }
78
+ for (const line of trimmed.split("\n").reverse()) {
79
+ const bare = line.trim().replace(/^"|"$/g, "");
80
+ if (STRICT_VERSION.test(bare)) return bare;
81
+ }
82
+ return void 0;
83
+ }
84
+ function readDiscoveryEntry(discoveryDir, file) {
85
+ try {
86
+ const parsed = JSON.parse(fs.readFileSync(path.join(discoveryDir, file), "utf8"));
87
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
88
+ return parsed;
89
+ } catch {
90
+ return void 0;
91
+ }
92
+ }
93
+ function scanWorkers(discoveryDir) {
94
+ const out = [];
95
+ try {
96
+ const files = fs.readdirSync(discoveryDir).filter((f) => f.endsWith(".json"));
97
+ for (const file of files.slice(0, 256)) {
98
+ const parsed = readDiscoveryEntry(discoveryDir, file);
99
+ if (!parsed) continue;
100
+ if (typeof parsed.pid !== "number" || !Number.isInteger(parsed.pid) || parsed.pid <= 0) continue;
101
+ if (parsed.pid === process.pid) continue;
102
+ if (parsed.unattended !== true || parsed.isManager === true) continue;
103
+ try {
104
+ process.kill(parsed.pid, 0);
105
+ } catch {
106
+ continue;
107
+ }
108
+ out.push({
109
+ pid: parsed.pid,
110
+ name: typeof parsed.displayName === "string" && parsed.displayName ? parsed.displayName : String(parsed.pid),
111
+ state: typeof parsed.state === "string" ? parsed.state : "?",
112
+ unattended: true,
113
+ file,
114
+ updatedAt: typeof parsed.updatedAt === "number" ? parsed.updatedAt : void 0
115
+ });
116
+ }
117
+ } catch {
118
+ }
119
+ return out;
120
+ }
121
+ function partitionWorkers(peers) {
122
+ const recycle = [];
123
+ const skip = [];
124
+ for (const peer of peers) {
125
+ (peer.state === "idle" ? recycle : skip).push(peer);
126
+ }
127
+ return { recycle, skip };
128
+ }
129
+ function findManagerResident(discoveryDir, sessionId) {
130
+ try {
131
+ const files = fs.readdirSync(discoveryDir).filter((f) => f.endsWith(".json"));
132
+ for (const file of files.slice(0, 256)) {
133
+ const parsed = readDiscoveryEntry(discoveryDir, file);
134
+ if (!parsed || parsed.isManager !== true || typeof parsed.pid !== "number" || !Number.isInteger(parsed.pid) || parsed.pid <= 0) continue;
135
+ if (sessionId !== void 0 && typeof parsed.sessionId === "string" && parsed.sessionId !== sessionId) continue;
136
+ try {
137
+ process.kill(parsed.pid, 0);
138
+ } catch {
139
+ continue;
140
+ }
141
+ return {
142
+ pid: parsed.pid,
143
+ state: typeof parsed.state === "string" ? parsed.state : void 0,
144
+ startedAt: typeof parsed.startedAt === "number" ? parsed.startedAt : void 0,
145
+ version: typeof parsed.version === "string" ? parsed.version : void 0
146
+ };
147
+ }
148
+ } catch {
149
+ }
150
+ return void 0;
151
+ }
152
+ function residentCommandLineLooksLikePie(pid, sessionToken) {
153
+ const cmdline = readProcessCommandLine(pid);
154
+ if (cmdline === void 0 || cmdline === "") return void 0;
155
+ if (!/json-events/.test(cmdline) || !/--idle/.test(cmdline)) return void 0;
156
+ if (sessionToken !== void 0 && !cmdline.includes(sessionToken)) return void 0;
157
+ return cmdline;
158
+ }
159
+ function processStartedAt(pid) {
160
+ if (process.platform !== "darwin" && process.platform !== "linux") return void 0;
161
+ try {
162
+ const out = spawnSync("ps", ["-p", String(pid), "-o", "lstart="], { encoding: "utf8", timeout: 5e3 });
163
+ const parsed = out.status === 0 ? Date.parse((out.stdout ?? "").trim()) : NaN;
164
+ return Number.isFinite(parsed) ? parsed : void 0;
165
+ } catch {
166
+ return void 0;
167
+ }
168
+ }
169
+ async function performUpgrade(paths, effects, options) {
170
+ const fromVersion = VERSION;
171
+ const build = (stage2, detail, extra = {}) => ({
172
+ ok: false,
173
+ stage: stage2,
174
+ fromVersion,
175
+ detail,
176
+ at: Date.now(),
177
+ ...extra
178
+ });
179
+ const fail = (stage2, detail, extra = {}) => {
180
+ const result = build(stage2, detail, extra);
181
+ effects.writeResult(result);
182
+ return result;
183
+ };
184
+ if (!isDistInstall(paths.entryPath)) {
185
+ return fail("guard", "refused: the running pie is not a dist install (source/tsx runs do not upgrade via npm)");
186
+ }
187
+ if (!effects.tryLock()) {
188
+ return build("guard", "refused: another upgrade is already in progress (upgrade.lock held)");
189
+ }
190
+ let settled = false;
191
+ const finish = (result) => {
192
+ if (settled) return result;
193
+ settled = true;
194
+ effects.writeResult(result);
195
+ effects.unlock();
196
+ return result;
197
+ };
198
+ let stage = "guard";
199
+ try {
200
+ const state = effects.readState();
201
+ if (!state || typeof state.sessionId !== "string" || !state.sessionId) {
202
+ return finish(build("guard", "refused: no manager state found (run pie manager first)"));
203
+ }
204
+ const busy = effects.managerBusy();
205
+ if (busy.busy) {
206
+ return finish(build("guard", `refused: the manager is ${busy.state ?? "busy"} (an active turn would be cancelled); retry when idle`));
207
+ }
208
+ stage = "install";
209
+ const view = options.target === "latest" ? effects.npmViewLatest() : { version: options.target, tail: "" };
210
+ const toVersion = view.version;
211
+ if (!toVersion) {
212
+ return finish(build("install", `could not resolve the target version (${options.target}): ${view.tail || "npm view returned nothing usable"}`));
213
+ }
214
+ const differs = versionDiffers(fromVersion, toVersion);
215
+ const residency = effects.residentStatus(state);
216
+ if (!differs && !options.force) {
217
+ if (residency === "alive") {
218
+ return finish(build("guard", `already on ${toVersion} and the resident is running; use --force to reinstall`));
219
+ }
220
+ if (residency === "foreign" || residency === "unknown") {
221
+ return finish(build("guard", `the recorded resident pid cannot be verified (${residency}); refusing to restart blindly. Check pie manager status, then retry.`));
222
+ }
223
+ effects.log(`repair run: version ${toVersion} already installed but the resident is ${residency}; restarting without reinstall`);
224
+ return finish(await restartAndRecycle(effects, state, fromVersion, toVersion, (s) => {
225
+ stage = s;
226
+ }, build));
227
+ }
228
+ const install = effects.npmInstall(toVersion);
229
+ if (install.code !== 0) {
230
+ return finish(build("install", `npm install @cydm/pie@${toVersion} failed (exit ${install.code}):
231
+ ${install.tail}`));
232
+ }
233
+ return finish(await restartAndRecycle(effects, state, fromVersion, toVersion, (s) => {
234
+ stage = s;
235
+ }, build));
236
+ } catch (error) {
237
+ return finish(build(stage, `unexpected error: ${error instanceof Error ? error.message : String(error)}`));
238
+ }
239
+ }
240
+ async function restartAndRecycle(effects, state, fromVersion, toVersion, setStage, build) {
241
+ setStage("restart");
242
+ let successorPid;
243
+ if (state.service === true) {
244
+ const restarted = effects.serviceRestart(state, toVersion);
245
+ if (!restarted.ok) {
246
+ return build("restart", `service restart not verified: ${restarted.detail ?? "unknown"}. The install succeeded; run pie manager upgrade again (repair) or restart the service manually.`);
247
+ }
248
+ successorPid = restarted.pid;
249
+ effects.log(`service mode: resident restarted via the service manager (pid ${successorPid ?? "?"})`);
250
+ } else {
251
+ const stopped = effects.terminateResident(state);
252
+ if (stopped === "foreign" || stopped === "unknown") {
253
+ return build("restart", `refused to signal the recorded pid (identity ${stopped} \u2014 pid reuse or unreadable process table); the install succeeded. Verify pie manager status and run pie manager upgrade again (repair).`);
254
+ }
255
+ if (stopped === "terminated" && typeof state.pid === "number") {
256
+ const exited = effects.waitExit(state.pid, 2e4);
257
+ if (!exited) effects.log(`old resident pid ${state.pid} did not exit within 20s; the successor spawn continues (pie manager start arbitrates duplicates)`);
258
+ }
259
+ const started = effects.startSuccessor();
260
+ if (!started.pid) {
261
+ return build("restart", `successor did not become ready: ${started.detail ?? "unknown"}. The old resident is gone and the install succeeded; run pie manager upgrade again (repair path restarts without reinstalling), or pie manager start manually.`);
262
+ }
263
+ successorPid = started.pid;
264
+ effects.log(`manual mode: successor resident verified (pid ${successorPid})`);
265
+ }
266
+ setStage("workers");
267
+ const { recycle, skip } = partitionWorkers(effects.scanWorkers());
268
+ const recycled = [];
269
+ const skipped = skip.map((w) => ({ pid: w.pid, name: w.name }));
270
+ for (const worker of recycle) {
271
+ const outcome = effects.retireWorkerIfStillIdle(worker);
272
+ if (outcome === "retired") recycled.push({ pid: worker.pid, name: worker.name });
273
+ else if (outcome === "busy") skipped.push({ pid: worker.pid, name: worker.name });
274
+ }
275
+ return {
276
+ ok: true,
277
+ stage: "workers",
278
+ fromVersion,
279
+ toVersion,
280
+ workersRecycled: recycled,
281
+ workersSkipped: skipped,
282
+ at: Date.now()
283
+ };
284
+ }
285
+ function readUpgradeResult(resultFile) {
286
+ try {
287
+ return JSON.parse(fs.readFileSync(resultFile, "utf8"));
288
+ } catch {
289
+ return void 0;
290
+ }
291
+ }
292
+ function writeResultAtomic(resultFile, result, log) {
293
+ try {
294
+ fs.mkdirSync(path.dirname(resultFile), { recursive: true });
295
+ const tmp = `${resultFile}.${process.pid}.tmp`;
296
+ fs.writeFileSync(tmp, `${JSON.stringify(result, null, " ")}
297
+ `);
298
+ fs.renameSync(tmp, resultFile);
299
+ } catch (error) {
300
+ log(`upgrade: could not write the result file: ${error instanceof Error ? error.message : String(error)}`);
301
+ }
302
+ }
303
+ function tryLockWithReclamation(lockFile) {
304
+ const attempt = () => {
305
+ try {
306
+ fs.mkdirSync(path.dirname(lockFile), { recursive: true });
307
+ const tmp = `${lockFile}.${process.pid}.tmp`;
308
+ fs.writeFileSync(tmp, JSON.stringify({ pid: process.pid, at: Date.now() }));
309
+ fs.linkSync(tmp, lockFile);
310
+ try {
311
+ fs.rmSync(tmp, { force: true });
312
+ } catch {
313
+ }
314
+ return true;
315
+ } catch {
316
+ try {
317
+ fs.rmSync(`${lockFile}.${process.pid}.tmp`, { force: true });
318
+ } catch {
319
+ }
320
+ return false;
321
+ }
322
+ };
323
+ if (attempt()) return true;
324
+ let holderPid;
325
+ try {
326
+ const holder = JSON.parse(fs.readFileSync(lockFile, "utf8"));
327
+ if (typeof holder.pid === "number" && Number.isInteger(holder.pid) && holder.pid > 0) holderPid = holder.pid;
328
+ } catch {
329
+ }
330
+ if (holderPid === void 0) return false;
331
+ try {
332
+ process.kill(holderPid, 0);
333
+ return false;
334
+ } catch (error) {
335
+ if (error.code !== "ESRCH") return false;
336
+ }
337
+ try {
338
+ fs.rmSync(lockFile, { force: true });
339
+ } catch {
340
+ }
341
+ if (!attempt()) return false;
342
+ try {
343
+ const verify = JSON.parse(fs.readFileSync(lockFile, "utf8"));
344
+ return verify.pid === process.pid;
345
+ } catch {
346
+ return false;
347
+ }
348
+ }
349
+ function unlockOwned(lockFile) {
350
+ try {
351
+ const holder = JSON.parse(fs.readFileSync(lockFile, "utf8"));
352
+ if (holder.pid !== process.pid) return;
353
+ } catch {
354
+ }
355
+ try {
356
+ fs.rmSync(lockFile, { force: true });
357
+ } catch {
358
+ }
359
+ }
360
+ function insideServiceCgroup() {
361
+ if (process.platform !== "linux") return false;
362
+ try {
363
+ return fs.readFileSync("/proc/self/cgroup", "utf8").includes("dev.pie.manager");
364
+ } catch {
365
+ return false;
366
+ }
367
+ }
368
+ function cliEffects(paths, log) {
369
+ const npm = resolveNpm(process.execPath);
370
+ const effects = {
371
+ npmInstall: (target) => runNpm(npm, ["install", "-g", `@cydm/pie@${target}`], 5 * 6e4),
372
+ npmViewLatest: () => {
373
+ const out = runNpm(npm, ["view", "@cydm/pie", "version", "--json"], 3e4);
374
+ if (out.code !== 0) return { tail: out.tail || `npm view exited ${out.code}` };
375
+ return { version: parseViewVersion(out.stdout), tail: out.tail };
376
+ },
377
+ readState: () => {
378
+ try {
379
+ return JSON.parse(fs.readFileSync(paths.stateFile, "utf8"));
380
+ } catch {
381
+ return void 0;
382
+ }
383
+ },
384
+ residentStatus: (state) => {
385
+ if (typeof state.pid === "number" && state.pid > 0) {
386
+ try {
387
+ process.kill(state.pid, 0);
388
+ } catch (error) {
389
+ return error.code === "ESRCH" ? "dead" : "unknown";
390
+ }
391
+ return residentCommandLineLooksLikePie(state.pid, state.sessionId) !== void 0 ? "alive" : "foreign";
392
+ }
393
+ const resident = findManagerResident(paths.discoveryDir, state.sessionId);
394
+ if (!resident) return "dead";
395
+ return residentCommandLineLooksLikePie(resident.pid, state.sessionId) !== void 0 ? "alive" : "unknown";
396
+ },
397
+ managerBusy: () => {
398
+ const state = effects.readState();
399
+ const resident = findManagerResident(paths.discoveryDir, state?.sessionId);
400
+ if (!resident) return { busy: false };
401
+ if (resident.state === "working" || resident.state === "blocked") return { busy: true, state: resident.state };
402
+ return { busy: false };
403
+ },
404
+ terminateResident: (state) => {
405
+ if (typeof state.pid === "number" && state.pid > 0) {
406
+ const status = effects.residentStatus(state);
407
+ if (status === "dead") return "dead";
408
+ if (status !== "alive") return status;
409
+ try {
410
+ process.kill(state.pid, process.platform === "win32" ? void 0 : "SIGTERM");
411
+ return "terminated";
412
+ } catch {
413
+ return "failed";
414
+ }
415
+ }
416
+ const resident = findManagerResident(paths.discoveryDir, state.sessionId);
417
+ if (!resident) return "dead";
418
+ if (residentCommandLineLooksLikePie(resident.pid, state.sessionId) === void 0) return "unknown";
419
+ try {
420
+ process.kill(resident.pid, process.platform === "win32" ? void 0 : "SIGTERM");
421
+ return "terminated";
422
+ } catch {
423
+ return "failed";
424
+ }
425
+ },
426
+ waitExit: (pid, timeoutMs) => {
427
+ const deadline = Date.now() + timeoutMs;
428
+ while (Date.now() < deadline) {
429
+ try {
430
+ process.kill(pid, 0);
431
+ } catch {
432
+ return true;
433
+ }
434
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200);
435
+ }
436
+ try {
437
+ process.kill(pid, 0);
438
+ return false;
439
+ } catch {
440
+ return true;
441
+ }
442
+ },
443
+ startSuccessor: () => {
444
+ const child = spawnSync(
445
+ process.execPath,
446
+ [paths.entryPath, "manager", "start"],
447
+ { encoding: "utf8", timeout: 9e4, windowsHide: true, cwd: paths.workspaceDir, env: process.env }
448
+ );
449
+ const out = `${child.stdout ?? ""}${child.stderr ?? ""}`.trim();
450
+ if (child.status !== 0) {
451
+ return { detail: out.slice(-400) || `pie manager start exited ${child.status}` };
452
+ }
453
+ const pidMatch = /Starting \(pid (\d+),/.exec(out);
454
+ if (!pidMatch) {
455
+ return { detail: out.slice(-400) || "pie manager start printed no pid line" };
456
+ }
457
+ const pid = Number(pidMatch[1]);
458
+ if (!/✓ Concierge ready/.test(out)) {
459
+ return { pid: void 0, detail: `pie manager start reported pid ${pid} but no readiness marker: ${out.slice(-300)}` };
460
+ }
461
+ try {
462
+ const recorded = JSON.parse(fs.readFileSync(paths.stateFile, "utf8"));
463
+ if (recorded.pid !== pid) return { pid: void 0, detail: `recorded state pid ${String(recorded.pid)} \u2260 started pid ${pid} (replaced or stopped concurrently)` };
464
+ process.kill(pid, 0);
465
+ } catch (error) {
466
+ return { pid: void 0, detail: `started pid ${pid} did not survive: ${error instanceof Error ? error.message : String(error)}` };
467
+ }
468
+ return { pid, detail: out.slice(-200) };
469
+ },
470
+ serviceRestart: (state, toVersion) => {
471
+ if (insideServiceCgroup()) {
472
+ try {
473
+ const unit = `dev.pie.manager-upgrade-${process.pid}`;
474
+ const delegated = spawnSync("systemd-run", ["--user", "--unit", unit, "--collect", "systemctl", "--user", "restart", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4 });
475
+ 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` };
476
+ } catch (error) {
477
+ return { ok: false, detail: `could not delegate the service restart: ${error instanceof Error ? error.message : String(error)}` };
478
+ }
479
+ }
480
+ const before = Date.now();
481
+ let restartDetail = "";
482
+ let restartFailed = false;
483
+ try {
484
+ if (process.platform === "darwin") {
485
+ const uid = process.getuid?.() ?? 501;
486
+ const r = spawnSync("launchctl", ["kickstart", "-k", `gui/${uid}/dev.pie.manager`], { encoding: "utf8", timeout: 2e4 });
487
+ restartDetail = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
488
+ restartFailed = r.status !== 0;
489
+ } else if (process.platform === "linux") {
490
+ const r = spawnSync("systemctl", ["--user", "restart", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4 });
491
+ restartDetail = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
492
+ restartFailed = r.status !== 0;
493
+ } else if (process.platform === "win32") {
494
+ spawnSync("schtasks", ["/End", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4 });
495
+ const r = spawnSync("schtasks", ["/Run", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4 });
496
+ restartDetail = `${r.stdout ?? ""}${r.stderr ?? ""}`.trim();
497
+ restartFailed = r.status !== 0;
498
+ } else {
499
+ return { ok: false, detail: `unsupported platform ${process.platform}` };
500
+ }
501
+ } catch (error) {
502
+ return { ok: false, detail: `service restart command failed: ${error instanceof Error ? error.message : String(error)}` };
503
+ }
504
+ if (restartFailed) {
505
+ return { ok: false, detail: `service restart command failed: ${restartDetail.slice(0, 200) || "no output"}` };
506
+ }
507
+ const deadline = Date.now() + 3e4;
508
+ while (Date.now() < deadline) {
509
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1e3);
510
+ const resident = findManagerResident(paths.discoveryDir, state.sessionId);
511
+ if (resident && resident.startedAt !== void 0 && resident.startedAt >= before && resident.version === toVersion && residentCommandLineLooksLikePie(resident.pid, state.sessionId) !== void 0) {
512
+ return { ok: true, pid: resident.pid, detail: restartDetail.slice(0, 200) };
513
+ }
514
+ }
515
+ return { ok: false, detail: `no fresh manager resident on ${toVersion} observed within 30s after the service restart (${restartDetail.slice(0, 200) || "no command output"})` };
516
+ },
517
+ scanWorkers: () => scanWorkers(paths.discoveryDir),
518
+ retireWorkerIfStillIdle: (peer) => {
519
+ const fresh = readDiscoveryEntry(paths.discoveryDir, peer.file);
520
+ if (!fresh || fresh.pid !== peer.pid) return "gone";
521
+ if (fresh.unattended !== true || fresh.isManager === true) return "foreign";
522
+ if (fresh.state !== "idle") return "busy";
523
+ if (residentCommandLineLooksLikePie(peer.pid) === void 0) return "foreign";
524
+ const updatedAt = typeof fresh.updatedAt === "number" ? fresh.updatedAt : peer.updatedAt;
525
+ const startedAt = processStartedAt(peer.pid);
526
+ if (updatedAt !== void 0 && startedAt !== void 0 && startedAt > updatedAt + 1e4) return "foreign";
527
+ try {
528
+ process.kill(peer.pid, process.platform === "win32" ? void 0 : "SIGTERM");
529
+ return "retired";
530
+ } catch {
531
+ return "gone";
532
+ }
533
+ },
534
+ writeResult: (result) => writeResultAtomic(paths.resultFile, result, log),
535
+ tryLock: () => tryLockWithReclamation(paths.lockFile),
536
+ unlock: () => unlockOwned(paths.lockFile),
537
+ log
538
+ };
539
+ return effects;
540
+ }
541
+ function parseTarget(raw) {
542
+ if (raw === void 0) return "latest";
543
+ if (raw === "latest") return raw;
544
+ return /^\d+\.\d+\.\d+(-[\w.-]+)?$/.test(raw.trim()) ? raw.trim() : void 0;
545
+ }
546
+ export {
547
+ cliEffects,
548
+ findManagerResident,
549
+ isDistInstall,
550
+ parseTarget,
551
+ parseViewVersion,
552
+ partitionWorkers,
553
+ performUpgrade,
554
+ processStartedAt,
555
+ readUpgradeResult,
556
+ residentCommandLineLooksLikePie,
557
+ resolveNpm,
558
+ runNpm,
559
+ scanWorkers,
560
+ upgradePaths,
561
+ versionDiffers
562
+ };