@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.
@@ -0,0 +1,618 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ isWindowsTaskAlreadyStoppedDetail,
4
+ isWindowsTaskNotFoundDetail,
5
+ queryWindowsServiceTaskState
6
+ } from "./chunk-Y6AVNVOD.js";
7
+ import {
8
+ isPositivelyDeadHolder,
9
+ withOwnershipMutex
10
+ } from "./chunk-Q4NJEPIZ.js";
11
+
12
+ // src/commands/manager-service-windows.ts
13
+ import * as fs from "node:fs";
14
+ import * as os from "node:os";
15
+ import * as path from "node:path";
16
+ import { execFileSync, spawnSync } from "node:child_process";
17
+ function xmlEscapeText(value) {
18
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
19
+ }
20
+ function resolveWindowsCurrentUser(env = process.env, fallbackUsername) {
21
+ const clean = (value) => {
22
+ if (typeof value !== "string") return "";
23
+ const trimmed = value.trim();
24
+ if (!trimmed || /[\r\n\t\u0000-\u001f]/.test(trimmed)) return "";
25
+ return trimmed;
26
+ };
27
+ const username = clean(env.USERNAME) || clean(fallbackUsername) || clean((() => {
28
+ try {
29
+ return os.userInfo().username;
30
+ } catch {
31
+ return "";
32
+ }
33
+ })());
34
+ if (!username) return void 0;
35
+ if (username.includes("\\") || username.includes("@")) return username;
36
+ const domain = clean(env.USERDOMAIN);
37
+ return domain ? `${domain}\\${username}` : username;
38
+ }
39
+ function buildWindowsManagerServiceTaskXml(params) {
40
+ const userId = params.userId?.trim();
41
+ const delay = params.logonDelay ?? "PT15S";
42
+ const triggerLines = [
43
+ " <Enabled>true</Enabled>",
44
+ ...userId ? [` <UserId>${xmlEscapeText(userId)}</UserId>`] : [],
45
+ ...delay ? [` <Delay>${xmlEscapeText(delay)}</Delay>`] : []
46
+ ];
47
+ const principalLines = [
48
+ ...userId ? [` <UserId>${xmlEscapeText(userId)}</UserId>`] : [],
49
+ " <LogonType>InteractiveToken</LogonType>",
50
+ " <RunLevel>LeastPrivilege</RunLevel>"
51
+ ];
52
+ return [
53
+ '<?xml version="1.0" encoding="UTF-16"?>',
54
+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
55
+ " <RegistrationInfo>",
56
+ " <Description>Pie manager (resident im-forward host)</Description>",
57
+ " </RegistrationInfo>",
58
+ " <Triggers>",
59
+ " <LogonTrigger>",
60
+ ...triggerLines,
61
+ " </LogonTrigger>",
62
+ " </Triggers>",
63
+ " <Principals>",
64
+ ' <Principal id="Author">',
65
+ ...principalLines,
66
+ " </Principal>",
67
+ " </Principals>",
68
+ " <Settings>",
69
+ " <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>",
70
+ " <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>",
71
+ " <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>",
72
+ " <AllowHardTerminate>true</AllowHardTerminate>",
73
+ " <StartWhenAvailable>true</StartWhenAvailable>",
74
+ " <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>",
75
+ " <IdleSettings>",
76
+ " <StopOnIdleEnd>false</StopOnIdleEnd>",
77
+ " <RestartOnIdle>false</RestartOnIdle>",
78
+ " </IdleSettings>",
79
+ " <AllowStartOnDemand>true</AllowStartOnDemand>",
80
+ " <Enabled>true</Enabled>",
81
+ " <Hidden>true</Hidden>",
82
+ " <RunOnlyIfIdle>false</RunOnlyIfIdle>",
83
+ " <WakeToRun>false</WakeToRun>",
84
+ " <ExecutionTimeLimit>PT0S</ExecutionTimeLimit>",
85
+ " <Priority>7</Priority>",
86
+ " <RestartOnFailure>",
87
+ " <Interval>PT1M</Interval>",
88
+ " <Count>255</Count>",
89
+ " </RestartOnFailure>",
90
+ " </Settings>",
91
+ ' <Actions Context="Author">',
92
+ " <Exec>",
93
+ ` <Command>${xmlEscapeText(params.launcherPath)}</Command>`,
94
+ ` <WorkingDirectory>${xmlEscapeText(params.workingDir)}</WorkingDirectory>`,
95
+ " </Exec>",
96
+ " </Actions>",
97
+ "</Task>",
98
+ ""
99
+ ].join("\r\n");
100
+ }
101
+ function installWindowsManagerScheduledTask(params, runSchtasks = (args) => {
102
+ execFileSync("schtasks", args, {
103
+ stdio: ["ignore", "pipe", "pipe"],
104
+ windowsHide: true,
105
+ timeout: 2e4
106
+ });
107
+ }) {
108
+ const userId = params.userId !== void 0 ? params.userId : resolveWindowsCurrentUser();
109
+ const xml = buildWindowsManagerServiceTaskXml({
110
+ launcherPath: params.launcherPath,
111
+ workingDir: params.workingDir,
112
+ userId,
113
+ logonDelay: params.logonDelay
114
+ });
115
+ const xmlPath = path.join(params.workingDir, `service-task.${process.pid}.xml`);
116
+ const xmlBytes = Buffer.concat([Buffer.from([255, 254]), Buffer.from(xml, "utf16le")]);
117
+ fs.writeFileSync(xmlPath, xmlBytes, { mode: 384 });
118
+ try {
119
+ runSchtasks(["/Create", "/TN", params.taskName, "/XML", xmlPath, "/F"]);
120
+ } finally {
121
+ fs.rmSync(xmlPath, { force: true });
122
+ }
123
+ if (params.runNow === false) return { started: false };
124
+ try {
125
+ runSchtasks(["/Run", "/TN", params.taskName]);
126
+ return { started: true };
127
+ } catch (error) {
128
+ return { started: false, startError: error instanceof Error ? error.message : String(error) };
129
+ }
130
+ }
131
+ var TRANSIENT_REPLACE_ERROR_CODES = /* @__PURE__ */ new Set(["EACCES", "EPERM", "EBUSY"]);
132
+ function replaceFileWithRetry(src, dest, options) {
133
+ const rename = options?.renameFn ?? fs.renameSync;
134
+ const now = options?.nowFn ?? Date.now;
135
+ const sleep = options?.sleepFn ?? ((ms) => {
136
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
137
+ });
138
+ const intervalMs = Math.max(10, options?.intervalMs ?? 150);
139
+ const endAt = now() + Math.max(0, options?.deadlineMs ?? 3e3);
140
+ for (; ; ) {
141
+ try {
142
+ rename(src, dest);
143
+ return;
144
+ } catch (error) {
145
+ const code = error?.code ?? "";
146
+ if (!TRANSIENT_REPLACE_ERROR_CODES.has(code) || now() >= endAt) throw error;
147
+ sleep(intervalMs);
148
+ }
149
+ }
150
+ }
151
+ function stopAndRefreshWindowsServiceForUpgrade(params, deps) {
152
+ const run = deps?.runSchtasks ?? ((args) => {
153
+ const r = spawnSync("schtasks", args, { encoding: "utf8", timeout: 2e4, windowsHide: true });
154
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "", error: r.error };
155
+ });
156
+ const queryState = deps?.queryTaskState ?? (() => queryWindowsServiceTaskState());
157
+ const refresh = deps?.refreshService ?? refreshWindowsManagerServiceOnUpgrade;
158
+ const now = deps?.nowFn ?? Date.now;
159
+ const sleep = deps?.sleepFn ?? ((ms) => {
160
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
161
+ });
162
+ const endRes = run(["/End", "/TN", params.taskName]);
163
+ const endDetail = endRes.error?.message || `${endRes.stdout ?? ""} ${endRes.stderr ?? ""}`.trim();
164
+ const endOk = !endRes.error && (endRes.status === 0 || isWindowsTaskAlreadyStoppedDetail(endDetail) || isWindowsTaskNotFoundDetail(endDetail));
165
+ if (!endOk) {
166
+ return {
167
+ ok: false,
168
+ stopped: false,
169
+ refreshed: false,
170
+ detail: `schtasks /End failed for ${params.taskName}: ${endDetail || `exit ${endRes.status}`}`
171
+ };
172
+ }
173
+ const stopEndAt = now() + Math.max(0, params.stopDeadlineMs ?? 5e3);
174
+ const pollIntervalMs = Math.max(20, params.pollIntervalMs ?? 200);
175
+ let state = queryState(params.taskName);
176
+ while (state !== "stopped" && now() < stopEndAt) {
177
+ sleep(pollIntervalMs);
178
+ state = queryState(params.taskName);
179
+ }
180
+ if (state !== "stopped") {
181
+ return {
182
+ ok: false,
183
+ stopped: false,
184
+ refreshed: false,
185
+ detail: `Windows task ${params.taskName} did not reach stopped state before upgrade refresh (state=${state})`
186
+ };
187
+ }
188
+ if (!params.sessionId) {
189
+ return { ok: true, stopped: true, refreshed: false, refreshDetail: "missing sessionId" };
190
+ }
191
+ const refreshed = refresh({
192
+ taskName: params.taskName,
193
+ workingDir: params.workingDir,
194
+ nodePath: params.nodePath,
195
+ entryPath: params.entryPath,
196
+ sessionId: params.sessionId,
197
+ env: params.env
198
+ });
199
+ return {
200
+ ok: true,
201
+ stopped: true,
202
+ refreshed: refreshed.ok,
203
+ refreshDetail: refreshed.detail
204
+ };
205
+ }
206
+ function refreshWindowsManagerServiceOnUpgrade(params) {
207
+ try {
208
+ const normalizeRoot = (value) => {
209
+ if (typeof value !== "string" || value.length === 0) return void 0;
210
+ const home = os.homedir() || params.env.HOME || params.env.USERPROFILE || "/tmp";
211
+ if (value === "~") return home;
212
+ if (value.startsWith("~/")) return path.resolve(path.join(home, value.slice(2)));
213
+ return path.isAbsolute(value) ? value : path.resolve(value);
214
+ };
215
+ const serviceEnv = [
216
+ ["PIE_PROC_CURATED_NAME", "manager"],
217
+ ["PIE_CODING_AGENT_DIR", normalizeRoot(params.env.PIE_CODING_AGENT_DIR)],
218
+ ["PIE_IPC_CONFIG_DIR", normalizeRoot(params.env.PIE_IPC_CONFIG_DIR)],
219
+ ["PATH", params.env.PATH ?? params.env.Path]
220
+ ];
221
+ const launcherPath = installWindowsManagerLauncher(
222
+ params.workingDir,
223
+ params.nodePath,
224
+ params.entryPath,
225
+ params.sessionId,
226
+ serviceEnv,
227
+ { keepAlive: true }
228
+ );
229
+ installWindowsManagerScheduledTask({
230
+ taskName: params.taskName,
231
+ launcherPath,
232
+ workingDir: params.workingDir,
233
+ userId: resolveWindowsCurrentUser(params.env),
234
+ runNow: false
235
+ });
236
+ return { ok: true };
237
+ } catch (error) {
238
+ return { ok: false, detail: error instanceof Error ? error.message : String(error) };
239
+ }
240
+ }
241
+ function installWindowsManagerLauncher(dir, node, entry, sessionId, env, options = {}) {
242
+ const systemRoot = process.env.SystemRoot || "C:\\Windows";
243
+ const compiler = ["Framework64", "Framework"].map((folder) => path.join(systemRoot, "Microsoft.NET", folder, "v4.0.30319", "csc.exe")).find((file) => fs.existsSync(file));
244
+ if (!compiler) throw new Error("Windows .NET Framework compiler is unavailable; manager service was not changed.");
245
+ const cs = (value) => `@"${value.replace(/"/g, '""')}"`;
246
+ const launcher = path.join(dir, "service-launcher.exe");
247
+ const source = path.join(dir, "service-launcher.cs");
248
+ const output = path.join(dir, `service-launcher.${process.pid}.exe`);
249
+ const command = `"${node}" "${entry}" --json-events --idle --session-id "${sessionId}"`;
250
+ const keepAlive = options.keepAlive === true;
251
+ const restartDelayMs = Math.max(50, Math.min(6e4, Math.floor(options.restartDelayMs ?? 3e3)));
252
+ const pathEntry = env.find(([key, value]) => key.toUpperCase() === "PATH" && typeof value === "string" && value.length > 0)?.[1];
253
+ const assignments = env.filter(([key, value]) => key.toUpperCase() !== "PATH" && typeof value === "string" && value.length > 0).map(([key, value]) => `Environment.SetEnvironmentVariable(${cs(key)}, ${cs(value)});`).join("\n ");
254
+ const mergePathCall = pathEntry ? `MergePath(${cs(pathEntry)});` : "";
255
+ fs.writeFileSync(source, `// Generated by Pie. Reinstall the service to refresh this launcher.
256
+ using System;
257
+ using System.Collections.Generic;
258
+ using System.ComponentModel;
259
+ using System.Diagnostics;
260
+ using System.IO;
261
+ using System.Runtime.InteropServices;
262
+ using System.Text;
263
+ using System.Threading;
264
+
265
+ internal static class PieManagerService {
266
+ [StructLayout(LayoutKind.Sequential)] struct SECURITY_ATTRIBUTES { public int Length; public IntPtr Descriptor; public int Inherit; }
267
+ [StructLayout(LayoutKind.Sequential)] struct STARTUPINFO {
268
+ public int Size; public string Reserved, Desktop, Title;
269
+ public int X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags;
270
+ public short ShowWindow, ReservedSize; public IntPtr Reserved2, Input, Output, Error;
271
+ }
272
+ [StructLayout(LayoutKind.Sequential)] struct PROCESS_INFORMATION { public IntPtr Process, Thread; public uint ProcessId, ThreadId; }
273
+ [StructLayout(LayoutKind.Sequential)] struct BASIC_LIMITS {
274
+ public long ProcessTime, JobTime; public uint Flags; public UIntPtr MinWorkingSet, MaxWorkingSet;
275
+ public uint ActiveProcesses; public UIntPtr Affinity; public uint PriorityClass, SchedulingClass;
276
+ }
277
+ [StructLayout(LayoutKind.Sequential)] struct IO_COUNTERS { public ulong ReadOps, WriteOps, OtherOps, ReadBytes, WriteBytes, OtherBytes; }
278
+ [StructLayout(LayoutKind.Sequential)] struct EXTENDED_LIMITS {
279
+ public BASIC_LIMITS Basic; public IO_COUNTERS Io; public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
280
+ }
281
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateJobObject(IntPtr attributes, string name);
282
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool SetInformationJobObject(IntPtr job, int type, ref EXTENDED_LIMITS limits, uint size);
283
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
284
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern bool CreateProcess(string app, StringBuilder command, IntPtr pa, IntPtr ta, bool inherit, uint flags, IntPtr env, string cwd, ref STARTUPINFO startup, out PROCESS_INFORMATION process);
285
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateFile(string name, uint access, uint share, ref SECURITY_ATTRIBUTES attributes, uint disposition, uint flags, IntPtr template);
286
+ [DllImport("kernel32.dll", SetLastError=true)] static extern uint ResumeThread(IntPtr thread);
287
+ [DllImport("kernel32.dll", SetLastError=true)] static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
288
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process, out uint code);
289
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateProcess(IntPtr process, uint code);
290
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
291
+ static void Check(bool ok) { if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error()); }
292
+ static void Close(IntPtr handle) { if (handle != IntPtr.Zero && handle != new IntPtr(-1)) CloseHandle(handle); }
293
+ static void LogLauncher(string message) {
294
+ try { File.AppendAllText(${cs(path.join(dir, "service-launcher.log"))}, DateTime.UtcNow.ToString("o") + " " + message + Environment.NewLine); } catch {}
295
+ }
296
+ static void MergePath(string installerPath) {
297
+ string current = Environment.GetEnvironmentVariable("PATH") ?? "";
298
+ var seen = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);
299
+ var merged = new List<string>();
300
+ foreach (string source in new[] { installerPath, current }) {
301
+ foreach (string raw in source.Split(';')) {
302
+ string entry = raw.Trim();
303
+ if (entry.Length > 0 && !seen.ContainsKey(entry)) {
304
+ seen[entry] = true;
305
+ merged.Add(entry);
306
+ }
307
+ }
308
+ }
309
+ if (merged.Count > 0) Environment.SetEnvironmentVariable("PATH", string.Join(";", merged.ToArray()));
310
+ }
311
+
312
+ static int RunOnce() {
313
+ IntPtr job = IntPtr.Zero, input = IntPtr.Zero, output = IntPtr.Zero;
314
+ PROCESS_INFORMATION child = new PROCESS_INFORMATION();
315
+ bool assigned = false;
316
+ try {
317
+ job = CreateJobObject(IntPtr.Zero, null);
318
+ Check(job != IntPtr.Zero);
319
+ EXTENDED_LIMITS limits = new EXTENDED_LIMITS();
320
+ limits.Basic.Flags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
321
+ Check(SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(EXTENDED_LIMITS))));
322
+ SECURITY_ATTRIBUTES inherit = new SECURITY_ATTRIBUTES();
323
+ inherit.Length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)); inherit.Inherit = 1;
324
+ input = CreateFile("NUL", 0x80000000, 3, ref inherit, 3, 0, IntPtr.Zero);
325
+ Check(input != new IntPtr(-1));
326
+ output = CreateFile(${cs(path.join(dir, "log.jsonl"))}, 4, 3, ref inherit, 4, 0, IntPtr.Zero); // FILE_APPEND_DATA, OPEN_ALWAYS
327
+ Check(output != new IntPtr(-1));
328
+ STARTUPINFO startup = new STARTUPINFO();
329
+ startup.Size = Marshal.SizeOf(typeof(STARTUPINFO)); startup.Flags = 0x100; // USESTDHANDLES
330
+ startup.Input = input; startup.Output = output; startup.Error = output;
331
+ // CREATE_NO_WINDOW | CREATE_SUSPENDED. The job handle is NOT inheritable.
332
+ Check(CreateProcess(${cs(node)}, new StringBuilder(${cs(command)}), IntPtr.Zero, IntPtr.Zero, true, 0x08000004, IntPtr.Zero, ${cs(dir)}, ref startup, out child));
333
+ Check(AssignProcessToJobObject(job, child.Process)); assigned = true;
334
+ Check(ResumeThread(child.Thread) != UInt32.MaxValue);
335
+ Check(WaitForSingleObject(child.Process, UInt32.MaxValue) == 0);
336
+ uint code; Check(GetExitCodeProcess(child.Process, out code));
337
+ return unchecked((int)code);
338
+ } finally {
339
+ if (!assigned && child.Process != IntPtr.Zero) TerminateProcess(child.Process, 1);
340
+ Close(job); Close(child.Thread); Close(child.Process); Close(input); Close(output);
341
+ }
342
+ }
343
+
344
+ static int Main() {
345
+ bool keepAlive = ${keepAlive ? "true" : "false"};
346
+ int baseDelayMs = ${restartDelayMs};
347
+ int delayMs = baseDelayMs;
348
+ try {
349
+ ${assignments}
350
+ ${mergePathCall}
351
+ while (true) {
352
+ Stopwatch watch = Stopwatch.StartNew();
353
+ int code;
354
+ try {
355
+ code = RunOnce();
356
+ } catch (Exception error) {
357
+ LogLauncher(error.ToString());
358
+ if (!keepAlive) return 1;
359
+ Thread.Sleep(delayMs);
360
+ delayMs = Math.Min(delayMs * 2, 30000);
361
+ continue;
362
+ }
363
+ if (!keepAlive) return code;
364
+ if (watch.ElapsedMilliseconds >= 60000) delayMs = baseDelayMs;
365
+ LogLauncher("resident exited with code " + code + " after " + watch.ElapsedMilliseconds + "ms; restarting in " + delayMs + "ms");
366
+ Thread.Sleep(delayMs);
367
+ delayMs = Math.Min(delayMs * 2, 30000);
368
+ }
369
+ } catch (Exception error) {
370
+ LogLauncher(error.ToString());
371
+ return 1;
372
+ }
373
+ }
374
+ }
375
+ `, { encoding: "utf8", mode: 384 });
376
+ try {
377
+ execFileSync(compiler, ["/nologo", "/target:winexe", "/platform:anycpu", "/optimize+", `/out:${output}`, source], {
378
+ windowsHide: true,
379
+ stdio: ["ignore", "pipe", "pipe"],
380
+ timeout: 3e4
381
+ });
382
+ replaceFileWithRetry(output, launcher);
383
+ } finally {
384
+ fs.rmSync(output, { force: true });
385
+ }
386
+ return launcher;
387
+ }
388
+
389
+ // src/commands/manager-upgrade-service.ts
390
+ import { spawnSync as spawnSync2 } from "node:child_process";
391
+ import { randomUUID } from "node:crypto";
392
+ import * as fs2 from "node:fs";
393
+ import * as path2 from "node:path";
394
+ function acquireUpgradeLock(lockFile) {
395
+ const mutexDir = `${lockFile}.mutex`;
396
+ const token = randomUUID();
397
+ let acquired = false;
398
+ try {
399
+ acquired = withOwnershipMutex(mutexDir, () => {
400
+ fs2.mkdirSync(path2.dirname(lockFile), { recursive: true });
401
+ if (fs2.existsSync(lockFile)) {
402
+ let holderPid;
403
+ let holderAt;
404
+ try {
405
+ const holder = JSON.parse(fs2.readFileSync(lockFile, "utf8"));
406
+ if (typeof holder.pid === "number" && Number.isInteger(holder.pid) && holder.pid > 0) {
407
+ holderPid = holder.pid;
408
+ }
409
+ if (typeof holder.at === "number" && Number.isFinite(holder.at)) {
410
+ holderAt = holder.at;
411
+ }
412
+ } catch {
413
+ return false;
414
+ }
415
+ if (holderPid === void 0 || !isPositivelyDeadHolder(holderPid, holderAt)) {
416
+ return false;
417
+ }
418
+ }
419
+ const tmp = `${lockFile}.${process.pid}.${token}.tmp`;
420
+ try {
421
+ fs2.writeFileSync(tmp, JSON.stringify({ pid: process.pid, token, at: Date.now() }), { flag: "wx", mode: 384 });
422
+ fs2.renameSync(tmp, lockFile);
423
+ return true;
424
+ } finally {
425
+ try {
426
+ fs2.rmSync(tmp, { force: true });
427
+ } catch {
428
+ }
429
+ }
430
+ });
431
+ } catch {
432
+ return null;
433
+ }
434
+ if (!acquired) return null;
435
+ let released = false;
436
+ return {
437
+ release: () => {
438
+ if (released) return;
439
+ released = true;
440
+ try {
441
+ withOwnershipMutex(mutexDir, () => {
442
+ try {
443
+ const holder = JSON.parse(fs2.readFileSync(lockFile, "utf8"));
444
+ if (holder.pid !== process.pid || holder.token !== token) return;
445
+ } catch {
446
+ return;
447
+ }
448
+ try {
449
+ fs2.rmSync(lockFile, { force: true });
450
+ } catch {
451
+ }
452
+ });
453
+ } catch {
454
+ }
455
+ }
456
+ };
457
+ }
458
+ function parseLaunchctlServicePresence(status, stdout, stderr) {
459
+ if (status === 0) return "present";
460
+ const combined = `${stdout}
461
+ ${stderr}`;
462
+ if (/could not find service|service not found/i.test(combined)) return "not-found";
463
+ return "unknown";
464
+ }
465
+ function queryLaunchdServicePresence(label = "dev.pie.manager", deps) {
466
+ const uid = deps?.uid ?? process.getuid?.() ?? 501;
467
+ const run = deps?.runLaunchctl ?? ((args) => {
468
+ const r = spawnSync2("launchctl", args, { encoding: "utf8", timeout: 1e4 });
469
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "", error: r.error };
470
+ });
471
+ try {
472
+ const r = run(["print", `gui/${uid}/${label}`]);
473
+ if (r.error) return "unknown";
474
+ return parseLaunchctlServicePresence(r.status, r.stdout ?? "", r.stderr ?? "");
475
+ } catch {
476
+ return "unknown";
477
+ }
478
+ }
479
+ function uninstallMacosLaunchdService(plistPath, label = "dev.pie.manager", deps) {
480
+ const uid = deps?.uid ?? process.getuid?.() ?? 501;
481
+ const exists = deps?.existsSync ?? fs2.existsSync;
482
+ const rm = deps?.rmSync ?? ((p) => fs2.rmSync(p));
483
+ const run = deps?.runLaunchctl ?? ((args) => {
484
+ const r = spawnSync2("launchctl", args, { encoding: "utf8", timeout: 2e4 });
485
+ return { status: r.status, stdout: r.stdout ?? "", stderr: r.stderr ?? "", error: r.error };
486
+ });
487
+ const checkPresence = () => queryLaunchdServicePresence(label, { uid, runLaunchctl: run });
488
+ const plistExists = exists(plistPath);
489
+ if (plistExists) {
490
+ run(["unload", plistPath]);
491
+ }
492
+ let presence = checkPresence();
493
+ if (presence === "present") {
494
+ run(["bootout", `gui/${uid}/${label}`]);
495
+ presence = checkPresence();
496
+ }
497
+ if (presence !== "not-found") return { ok: false, removedPlist: false, presence };
498
+ let removedPlist = false;
499
+ if (plistExists) {
500
+ try {
501
+ rm(plistPath);
502
+ removedPlist = true;
503
+ } catch (error) {
504
+ if (error?.code !== "ENOENT") {
505
+ return { ok: false, removedPlist: false, presence };
506
+ }
507
+ }
508
+ }
509
+ return { ok: true, removedPlist, presence };
510
+ }
511
+ function parseLaunchctlServiceState(status, stdout, stderr) {
512
+ const combined = `${stdout}
513
+ ${stderr}`;
514
+ if (status !== 0) {
515
+ return /could not find service|service not found/i.test(combined) ? "stopped" : "unknown";
516
+ }
517
+ const pidMatch = /^\s*pid\s*=\s*(\d+)\s*$/im.exec(combined);
518
+ if (pidMatch && Number.parseInt(pidMatch[1], 10) > 0) return "running";
519
+ const stateMatch = /^\s*state\s*=\s*(.+)$/im.exec(combined)?.[1]?.trim().toLowerCase();
520
+ if (!stateMatch) return "unknown";
521
+ if (stateMatch === "running") return "running";
522
+ if (stateMatch === "not running" || stateMatch === "waiting" || stateMatch === "spawn scheduled") return "stopped";
523
+ return "unknown";
524
+ }
525
+ function parseSystemctlServiceState(status, stdout, stderr) {
526
+ const combined = `${stdout}
527
+ ${stderr}`;
528
+ if (status !== 0) {
529
+ return /not found|could not be found|no such unit/i.test(combined) ? "stopped" : "unknown";
530
+ }
531
+ const mainPid = Number.parseInt(/^\s*MainPID=(\d+)\s*$/im.exec(combined)?.[1] ?? "0", 10);
532
+ if (Number.isInteger(mainPid) && mainPid > 0) return "running";
533
+ const active = /^\s*ActiveState=([^\r\n]+)$/im.exec(combined)?.[1]?.trim().toLowerCase();
534
+ if (!active) return "unknown";
535
+ if (active === "active" || active === "activating" || active === "reloading") return "running";
536
+ if (active === "inactive" || active === "failed" || active === "deactivating") return "stopped";
537
+ return "unknown";
538
+ }
539
+ function queryPlatformServiceState() {
540
+ try {
541
+ if (process.platform === "win32") return queryWindowsServiceTaskState();
542
+ if (process.platform === "darwin") {
543
+ const uid = process.getuid?.() ?? 501;
544
+ const r = spawnSync2("launchctl", ["print", `gui/${uid}/dev.pie.manager`], { encoding: "utf8", timeout: 1e4 });
545
+ if (r.error) return "unknown";
546
+ return parseLaunchctlServiceState(r.status, r.stdout ?? "", r.stderr ?? "");
547
+ }
548
+ if (process.platform === "linux") {
549
+ const r = spawnSync2("systemctl", ["--user", "show", "-p", "ActiveState", "-p", "MainPID", "dev.pie.manager"], { encoding: "utf8", timeout: 1e4 });
550
+ if (r.error) return "unknown";
551
+ return parseSystemctlServiceState(r.status, r.stdout ?? "", r.stderr ?? "");
552
+ }
553
+ return "unknown";
554
+ } catch {
555
+ return "unknown";
556
+ }
557
+ }
558
+ function scanLinuxServiceBlockingWorkers(discoveryDir) {
559
+ let files;
560
+ try {
561
+ files = fs2.readdirSync(discoveryDir).filter((f) => f.endsWith(".json"));
562
+ } catch (error) {
563
+ if (error.code === "ENOENT") return { busy: false };
564
+ return { busy: true, detail: "discovery directory unreadable" };
565
+ }
566
+ if (files.length > 256) {
567
+ return { busy: true, detail: `too many discovery entries (${files.length}) to verify worker safety` };
568
+ }
569
+ const blocking = [];
570
+ for (const file of files) {
571
+ let raw;
572
+ try {
573
+ raw = fs2.readFileSync(path2.join(discoveryDir, file), "utf8");
574
+ } catch (error) {
575
+ if (error.code === "ENOENT") continue;
576
+ return { busy: true, detail: `unreadable discovery entry (${file})` };
577
+ }
578
+ let parsed;
579
+ try {
580
+ const decoded = JSON.parse(raw);
581
+ if (decoded === null || typeof decoded !== "object" || Array.isArray(decoded)) {
582
+ return { busy: true, detail: `malformed discovery entry (${file})` };
583
+ }
584
+ parsed = decoded;
585
+ } catch {
586
+ return { busy: true, detail: `malformed discovery entry (${file})` };
587
+ }
588
+ if (parsed.isManager === true) continue;
589
+ if (parsed.unattended !== true) continue;
590
+ const pid = parsed.pid;
591
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
592
+ blocking.push(`${file}(invalid-pid)`);
593
+ continue;
594
+ }
595
+ if (pid === process.pid) continue;
596
+ const startedAt = typeof parsed.startedAt === "number" ? parsed.startedAt : void 0;
597
+ if (isPositivelyDeadHolder(pid, startedAt)) continue;
598
+ const state = typeof parsed.state === "string" && parsed.state ? parsed.state : "unknown";
599
+ if (state !== "idle") {
600
+ const name = typeof parsed.displayName === "string" && parsed.displayName ? parsed.displayName : String(pid);
601
+ blocking.push(`${name}(${state})`);
602
+ }
603
+ }
604
+ return blocking.length > 0 ? { busy: true, detail: blocking.join(", ") } : { busy: false };
605
+ }
606
+
607
+ export {
608
+ installWindowsManagerScheduledTask,
609
+ stopAndRefreshWindowsServiceForUpgrade,
610
+ installWindowsManagerLauncher,
611
+ acquireUpgradeLock,
612
+ queryLaunchdServicePresence,
613
+ uninstallMacosLaunchdService,
614
+ parseLaunchctlServiceState,
615
+ parseSystemctlServiceState,
616
+ queryPlatformServiceState,
617
+ scanLinuxServiceBlockingWorkers
618
+ };