@cydm/pie 4.12.0 → 4.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,120 +3,32 @@ import {
3
3
  isTooBroadForWorkerSandbox,
4
4
  seedProcConfig
5
5
  } from "./chunk-Z2RT3P4F.js";
6
+ import {
7
+ installWindowsManagerLauncher,
8
+ installWindowsManagerScheduledTask,
9
+ queryLaunchdServicePresence,
10
+ queryPlatformServiceState,
11
+ uninstallMacosLaunchdService
12
+ } from "./chunk-ZB5FVHI7.js";
13
+ import {
14
+ isWindowsTaskAlreadyStoppedDetail,
15
+ isWindowsTaskNotFoundDetail,
16
+ queryWindowsServiceTaskPresence,
17
+ queryWindowsServiceTaskState
18
+ } from "./chunk-Y6AVNVOD.js";
6
19
  import {
7
20
  readProcessCommandLine
8
21
  } from "./chunk-7RJXKN7N.js";
22
+ import "./chunk-Q4NJEPIZ.js";
9
23
  import "./chunk-CBDQJMUI.js";
10
24
  import "./chunk-LZQXQOPJ.js";
11
25
 
12
26
  // src/commands/manager-cli.ts
13
- import { spawn, execFileSync as execFileSync2 } from "node:child_process";
27
+ import { spawn, execFileSync } from "node:child_process";
14
28
  import { createRequire } from "node:module";
15
- import * as fs2 from "node:fs";
16
- import * as os from "node:os";
17
- import * as path2 from "node:path";
18
-
19
- // src/commands/manager-service-windows.ts
20
29
  import * as fs from "node:fs";
30
+ import * as os from "node:os";
21
31
  import * as path from "node:path";
22
- import { execFileSync } from "node:child_process";
23
- function installWindowsManagerLauncher(dir, node, entry, sessionId, env) {
24
- const systemRoot = process.env.SystemRoot || "C:\\Windows";
25
- const compiler = ["Framework64", "Framework"].map((folder) => path.join(systemRoot, "Microsoft.NET", folder, "v4.0.30319", "csc.exe")).find((file) => fs.existsSync(file));
26
- if (!compiler) throw new Error("Windows .NET Framework compiler is unavailable; manager service was not changed.");
27
- const cs = (value) => `@"${value.replace(/"/g, '""')}"`;
28
- const launcher = path.join(dir, "service-launcher.exe");
29
- const source = path.join(dir, "service-launcher.cs");
30
- const output = path.join(dir, `service-launcher.${process.pid}.exe`);
31
- const command = `"${node}" "${entry}" --json-events --idle --session-id "${sessionId}"`;
32
- const assignments = env.filter(([, value]) => typeof value === "string" && value.length > 0).map(([key, value]) => `Environment.SetEnvironmentVariable(${cs(key)}, ${cs(value)});`).join("\n ");
33
- fs.writeFileSync(source, `// Generated by Pie. Reinstall the service to refresh this launcher.
34
- using System;
35
- using System.ComponentModel;
36
- using System.IO;
37
- using System.Runtime.InteropServices;
38
- using System.Text;
39
-
40
- internal static class PieManagerService {
41
- [StructLayout(LayoutKind.Sequential)] struct SECURITY_ATTRIBUTES { public int Length; public IntPtr Descriptor; public int Inherit; }
42
- [StructLayout(LayoutKind.Sequential)] struct STARTUPINFO {
43
- public int Size; public string Reserved, Desktop, Title;
44
- public int X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags;
45
- public short ShowWindow, ReservedSize; public IntPtr Reserved2, Input, Output, Error;
46
- }
47
- [StructLayout(LayoutKind.Sequential)] struct PROCESS_INFORMATION { public IntPtr Process, Thread; public uint ProcessId, ThreadId; }
48
- [StructLayout(LayoutKind.Sequential)] struct BASIC_LIMITS {
49
- public long ProcessTime, JobTime; public uint Flags; public UIntPtr MinWorkingSet, MaxWorkingSet;
50
- public uint ActiveProcesses; public UIntPtr Affinity; public uint PriorityClass, SchedulingClass;
51
- }
52
- [StructLayout(LayoutKind.Sequential)] struct IO_COUNTERS { public ulong ReadOps, WriteOps, OtherOps, ReadBytes, WriteBytes, OtherBytes; }
53
- [StructLayout(LayoutKind.Sequential)] struct EXTENDED_LIMITS {
54
- public BASIC_LIMITS Basic; public IO_COUNTERS Io; public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
55
- }
56
- [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateJobObject(IntPtr attributes, string name);
57
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool SetInformationJobObject(IntPtr job, int type, ref EXTENDED_LIMITS limits, uint size);
58
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
59
- [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);
60
- [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);
61
- [DllImport("kernel32.dll", SetLastError=true)] static extern uint ResumeThread(IntPtr thread);
62
- [DllImport("kernel32.dll", SetLastError=true)] static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
63
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process, out uint code);
64
- [DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateProcess(IntPtr process, uint code);
65
- [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
66
- static void Check(bool ok) { if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error()); }
67
- static void Close(IntPtr handle) { if (handle != IntPtr.Zero && handle != new IntPtr(-1)) CloseHandle(handle); }
68
-
69
- static int Main() {
70
- IntPtr job = IntPtr.Zero, input = IntPtr.Zero, output = IntPtr.Zero;
71
- PROCESS_INFORMATION child = new PROCESS_INFORMATION();
72
- bool assigned = false;
73
- try {
74
- ${assignments}
75
- job = CreateJobObject(IntPtr.Zero, null);
76
- Check(job != IntPtr.Zero);
77
- EXTENDED_LIMITS limits = new EXTENDED_LIMITS();
78
- limits.Basic.Flags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
79
- Check(SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(EXTENDED_LIMITS))));
80
- SECURITY_ATTRIBUTES inherit = new SECURITY_ATTRIBUTES();
81
- inherit.Length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)); inherit.Inherit = 1;
82
- input = CreateFile("NUL", 0x80000000, 3, ref inherit, 3, 0, IntPtr.Zero);
83
- Check(input != new IntPtr(-1));
84
- output = CreateFile(${cs(path.join(dir, "log.jsonl"))}, 4, 3, ref inherit, 4, 0, IntPtr.Zero); // FILE_APPEND_DATA, OPEN_ALWAYS
85
- Check(output != new IntPtr(-1));
86
- STARTUPINFO startup = new STARTUPINFO();
87
- startup.Size = Marshal.SizeOf(typeof(STARTUPINFO)); startup.Flags = 0x100; // USESTDHANDLES
88
- startup.Input = input; startup.Output = output; startup.Error = output;
89
- // CREATE_NO_WINDOW | CREATE_SUSPENDED. The job handle is NOT inheritable.
90
- Check(CreateProcess(${cs(node)}, new StringBuilder(${cs(command)}), IntPtr.Zero, IntPtr.Zero, true, 0x08000004, IntPtr.Zero, ${cs(dir)}, ref startup, out child));
91
- Check(AssignProcessToJobObject(job, child.Process)); assigned = true;
92
- Check(ResumeThread(child.Thread) != UInt32.MaxValue);
93
- Check(WaitForSingleObject(child.Process, UInt32.MaxValue) == 0);
94
- uint code; Check(GetExitCodeProcess(child.Process, out code));
95
- return unchecked((int)code);
96
- } catch (Exception error) {
97
- try { File.AppendAllText(${cs(path.join(dir, "service-launcher.log"))}, DateTime.UtcNow.ToString("o") + " " + error + Environment.NewLine); } catch {}
98
- return 1;
99
- } finally {
100
- if (!assigned && child.Process != IntPtr.Zero) TerminateProcess(child.Process, 1);
101
- Close(job); Close(child.Thread); Close(child.Process); Close(input); Close(output);
102
- }
103
- }
104
- }
105
- `, { encoding: "utf8", mode: 384 });
106
- try {
107
- execFileSync(compiler, ["/nologo", "/target:winexe", "/platform:anycpu", "/optimize+", `/out:${output}`, source], {
108
- windowsHide: true,
109
- stdio: ["ignore", "pipe", "pipe"],
110
- timeout: 3e4
111
- });
112
- fs.renameSync(output, launcher);
113
- } finally {
114
- fs.rmSync(output, { force: true });
115
- }
116
- return launcher;
117
- }
118
-
119
- // src/commands/manager-cli.ts
120
32
  var require_ = createRequire(import.meta.url);
121
33
  var CRON_SECTION_MARKER = "## \u5B9A\u65F6\u4EFB\u52A1";
122
34
  var CRON_SECTION = `
@@ -164,33 +76,33 @@ var SEED_AGENTS_MD = `# Pie Manager (manager)
164
76
  - \u6D88\u606F\u6CA1\u6536\u5230 reaction \u65F6\u4E0D\u8981\u8BA9\u5B83\u60AC\u7740\uFF1A\u540C\u4E00\u4EFD\u6B63\u6587\u518D\u53D1\u4E00\u6B21\u5373\u53EF\uFF08\u4E0D\u5E26\u5F15\u7528\uFF09\uFF0C\u6216\u52A0 \`\u4F1A\u8BDD\u540D:\` \u6307\u5B9A\u76EE\u6807\u3002
165
77
  ${CRON_SECTION}${PANEL_ACTIONS_SECTION}`;
166
78
  function workspaceDir() {
167
- const dir = path2.join(os.homedir(), ".pie", "manager");
79
+ const dir = path.join(os.homedir(), ".pie", "manager");
168
80
  migrateLegacyWorkspace(dir);
169
81
  return dir;
170
82
  }
171
83
  function tailWorkspaceDir() {
172
- const dir = path2.join(os.homedir(), ".pie", "manager");
173
- if (fs2.existsSync(dir)) return dir;
174
- const legacy = path2.join(os.homedir(), ".pie", "concierge");
175
- return fs2.existsSync(legacy) ? legacy : dir;
84
+ const dir = path.join(os.homedir(), ".pie", "manager");
85
+ if (fs.existsSync(dir)) return dir;
86
+ const legacy = path.join(os.homedir(), ".pie", "concierge");
87
+ return fs.existsSync(legacy) ? legacy : dir;
176
88
  }
177
89
  var migrationChecked = false;
178
90
  function migrateLegacyWorkspace(newDir) {
179
91
  if (migrationChecked) return;
180
92
  migrationChecked = true;
181
- const legacy = path2.join(os.homedir(), ".pie", "concierge");
182
- if (!fs2.existsSync(legacy)) return;
183
- if (fs2.existsSync(newDir)) {
93
+ const legacy = path.join(os.homedir(), ".pie", "concierge");
94
+ if (!fs.existsSync(legacy)) return;
95
+ if (fs.existsSync(newDir)) {
184
96
  console.warn(`Both ~/.pie/manager and the legacy ~/.pie/concierge exist; leaving the legacy directory untouched. Merge manually if needed.`);
185
97
  return;
186
98
  }
187
99
  try {
188
- fs2.mkdirSync(path2.dirname(newDir), { recursive: true });
189
- fs2.renameSync(legacy, newDir);
190
- const legacyState = path2.join(newDir, "concierge.json");
191
- if (fs2.existsSync(legacyState)) {
100
+ fs.mkdirSync(path.dirname(newDir), { recursive: true });
101
+ fs.renameSync(legacy, newDir);
102
+ const legacyState = path.join(newDir, "concierge.json");
103
+ if (fs.existsSync(legacyState)) {
192
104
  try {
193
- fs2.renameSync(legacyState, path2.join(newDir, "manager.json"));
105
+ fs.renameSync(legacyState, path.join(newDir, "manager.json"));
194
106
  } catch {
195
107
  }
196
108
  }
@@ -200,17 +112,17 @@ function migrateLegacyWorkspace(newDir) {
200
112
  }
201
113
  }
202
114
  function ensureSessionToken(dir) {
203
- const tokenFile = path2.join(dir, "session-token");
115
+ const tokenFile = path.join(dir, "session-token");
204
116
  for (let attempt = 0; attempt < 5; attempt += 1) {
205
117
  const mine = `manager-${os.hostname().split(".")[0]}-${Math.random().toString(36).slice(2, 8)}`;
206
118
  const tmp = `${tokenFile}.${process.pid}.${attempt}.tmp`;
207
119
  let tmpKept = false;
208
120
  try {
209
- fs2.writeFileSync(tmp, mine);
121
+ fs.writeFileSync(tmp, mine);
210
122
  tmpKept = true;
211
- fs2.linkSync(tmp, tokenFile);
123
+ fs.linkSync(tmp, tokenFile);
212
124
  try {
213
- fs2.rmSync(tmp, { force: true });
125
+ fs.rmSync(tmp, { force: true });
214
126
  tmpKept = false;
215
127
  } catch {
216
128
  }
@@ -218,7 +130,7 @@ function ensureSessionToken(dir) {
218
130
  if (error.code !== "EEXIST") {
219
131
  if (tmpKept) {
220
132
  try {
221
- fs2.rmSync(tmp, { force: true });
133
+ fs.rmSync(tmp, { force: true });
222
134
  } catch {
223
135
  }
224
136
  }
@@ -226,7 +138,7 @@ function ensureSessionToken(dir) {
226
138
  }
227
139
  const existing = (() => {
228
140
  try {
229
- return fs2.readFileSync(tokenFile, "utf8").trim();
141
+ return fs.readFileSync(tokenFile, "utf8").trim();
230
142
  } catch {
231
143
  return "";
232
144
  }
@@ -234,21 +146,21 @@ function ensureSessionToken(dir) {
234
146
  if (existing) {
235
147
  if (tmpKept) {
236
148
  try {
237
- fs2.rmSync(tmp, { force: true });
149
+ fs.rmSync(tmp, { force: true });
238
150
  } catch {
239
151
  }
240
152
  }
241
153
  return existing;
242
154
  }
243
155
  try {
244
- fs2.renameSync(tmp, tokenFile);
156
+ fs.renameSync(tmp, tokenFile);
245
157
  tmpKept = false;
246
158
  } catch {
247
159
  }
248
160
  }
249
161
  const settled = (() => {
250
162
  try {
251
- return fs2.readFileSync(tokenFile, "utf8").trim();
163
+ return fs.readFileSync(tokenFile, "utf8").trim();
252
164
  } catch {
253
165
  return "";
254
166
  }
@@ -256,7 +168,7 @@ function ensureSessionToken(dir) {
256
168
  if (settled) return settled;
257
169
  if (tmpKept) {
258
170
  try {
259
- fs2.rmSync(tmp, { force: true });
171
+ fs.rmSync(tmp, { force: true });
260
172
  } catch {
261
173
  }
262
174
  }
@@ -264,20 +176,20 @@ function ensureSessionToken(dir) {
264
176
  throw new Error("cannot establish the manager workspace token; retry");
265
177
  }
266
178
  function statePath(dir = workspaceDir()) {
267
- const current = path2.join(dir, "manager.json");
268
- if (!fs2.existsSync(current)) {
269
- const legacy = path2.join(dir, "concierge.json");
270
- if (fs2.existsSync(legacy)) return legacy;
179
+ const current = path.join(dir, "manager.json");
180
+ if (!fs.existsSync(current)) {
181
+ const legacy = path.join(dir, "concierge.json");
182
+ if (fs.existsSync(legacy)) return legacy;
271
183
  }
272
184
  return current;
273
185
  }
274
186
  function logPath(dir = workspaceDir()) {
275
- return path2.join(dir, "log.jsonl");
187
+ return path.join(dir, "log.jsonl");
276
188
  }
277
189
  function readState(dir = workspaceDir()) {
278
190
  try {
279
191
  const raw = JSON.parse(
280
- fs2.readFileSync(statePath(dir), "utf8")
192
+ fs.readFileSync(statePath(dir), "utf8")
281
193
  );
282
194
  return typeof raw.sessionId === "string" && raw.sessionId ? raw : void 0;
283
195
  } catch {
@@ -285,10 +197,10 @@ function readState(dir = workspaceDir()) {
285
197
  }
286
198
  }
287
199
  function writeState(state, dir = workspaceDir()) {
288
- fs2.mkdirSync(dir, { recursive: true });
200
+ fs.mkdirSync(dir, { recursive: true });
289
201
  const tmp = `${statePath(dir)}.${process.pid}.tmp`;
290
- fs2.writeFileSync(tmp, JSON.stringify(state, null, " "));
291
- fs2.renameSync(tmp, statePath(dir));
202
+ fs.writeFileSync(tmp, JSON.stringify(state, null, " "));
203
+ fs.renameSync(tmp, statePath(dir));
292
204
  }
293
205
  function managerLiveness(pid, state) {
294
206
  if (!pid || pid <= 0) return "dead";
@@ -312,43 +224,43 @@ function isConciergeAlive(pid, state) {
312
224
  return managerLiveness(pid, state) === "alive";
313
225
  }
314
226
  function seedWorkspace(dir) {
315
- fs2.mkdirSync(path2.join(dir, ".pie"), { recursive: true });
316
- const agents = path2.join(dir, "AGENTS.md");
317
- if (!fs2.existsSync(agents)) {
318
- fs2.writeFileSync(agents, SEED_AGENTS_MD);
227
+ fs.mkdirSync(path.join(dir, ".pie"), { recursive: true });
228
+ const agents = path.join(dir, "AGENTS.md");
229
+ if (!fs.existsSync(agents)) {
230
+ fs.writeFileSync(agents, SEED_AGENTS_MD);
319
231
  return;
320
232
  }
321
233
  let current;
322
234
  try {
323
- current = fs2.readFileSync(agents, "utf8");
235
+ current = fs.readFileSync(agents, "utf8");
324
236
  } catch {
325
237
  return;
326
238
  }
327
- if (!current.includes(CRON_SECTION_MARKER)) fs2.appendFileSync(agents, CRON_SECTION);
328
- if (!current.includes(PANEL_ACTIONS_SECTION_MARKER)) fs2.appendFileSync(agents, PANEL_ACTIONS_SECTION);
239
+ if (!current.includes(CRON_SECTION_MARKER)) fs.appendFileSync(agents, CRON_SECTION);
240
+ if (!current.includes(PANEL_ACTIONS_SECTION_MARKER)) fs.appendFileSync(agents, PANEL_ACTIONS_SECTION);
329
241
  const v1Marker = "\u4F60\u662F\u7528\u6237\u5728 IM \u4E0A\u7684\u552F\u4E00\u8054\u7EDC\u70B9\u3002\u9ED8\u8BA4\u6D3E\u6D3B";
330
242
  const v2Marker = "\u4F60\u662F\u88AB\u52A8\u8D77\u6B65\u7684";
331
243
  if (current.includes(v1Marker) && !current.includes(v2Marker)) {
332
- fs2.writeFileSync(agents, SEED_AGENTS_MD);
244
+ fs.writeFileSync(agents, SEED_AGENTS_MD);
333
245
  }
334
246
  const oldV2Intro = "\u4F60\u662F\u7528\u6237\u7684\u5E38\u9A7B\u7BA1\u5BB6 pie";
335
247
  const newV2Intro = "\u4F60\u662F\u7528\u6237\u7684\u5E38\u9A7B manager pie";
336
248
  if (current.includes(oldV2Intro) && !current.includes(newV2Intro)) {
337
- fs2.writeFileSync(agents, SEED_AGENTS_MD);
249
+ fs.writeFileSync(agents, SEED_AGENTS_MD);
338
250
  } else if (current.includes("\u7BA1\u5BB6") && current.includes(v2Marker) && !current.includes(newV2Intro)) {
339
- fs2.appendFileSync(agents, "\n> Note: the resident role is now named manager. Update the role card manually if you want the latest template.\n");
251
+ fs.appendFileSync(agents, "\n> Note: the resident role is now named manager. Update the role card manually if you want the latest template.\n");
340
252
  }
341
253
  }
342
254
  function cliEntry() {
343
- return process.argv[1] ? path2.resolve(process.argv[1]) : "";
255
+ return process.argv[1] ? path.resolve(process.argv[1]) : "";
344
256
  }
345
257
  function resolveTsxLoaderUrl() {
346
258
  for (let i = 0; i < process.execArgv.length - 1; i += 1) {
347
259
  if (process.execArgv[i] === "--import") {
348
260
  const target = process.execArgv[i + 1];
349
- if (target && !path2.isAbsolute(target) && !target.startsWith("file:")) {
261
+ if (target && !path.isAbsolute(target) && !target.startsWith("file:")) {
350
262
  try {
351
- return require_.resolve(target, { paths: [path2.dirname(cliEntry())] }) ? pathToFileURLResolved(target) : target;
263
+ return require_.resolve(target, { paths: [path.dirname(cliEntry())] }) ? pathToFileURLResolved(target) : target;
352
264
  } catch {
353
265
  return target;
354
266
  }
@@ -360,12 +272,12 @@ function resolveTsxLoaderUrl() {
360
272
  }
361
273
  function pathToFileURLResolved(spec) {
362
274
  try {
363
- const pkgRoot = path2.dirname(
275
+ const pkgRoot = path.dirname(
364
276
  require_.resolve(`${spec}/package.json`, {
365
- paths: [path2.dirname(cliEntry())]
277
+ paths: [path.dirname(cliEntry())]
366
278
  })
367
279
  );
368
- return path2.join(pkgRoot, "dist", "loader.mjs");
280
+ return path.join(pkgRoot, "dist", "loader.mjs");
369
281
  } catch {
370
282
  return spec;
371
283
  }
@@ -373,7 +285,7 @@ function pathToFileURLResolved(spec) {
373
285
  function spawnResident(state, dir) {
374
286
  const entry = cliEntry();
375
287
  if (!entry) throw new Error("cannot resolve the pie entry point");
376
- const out = fs2.openSync(logPath(dir), "a");
288
+ const out = fs.openSync(logPath(dir), "a");
377
289
  const loaderAbs = resolveTsxLoaderUrl();
378
290
  const passthrough = loaderAbs ? ["--import", loaderAbs] : process.execArgv.filter(
379
291
  (a) => a !== "--import" && !a.startsWith("--import=")
@@ -404,13 +316,13 @@ async function waitForAgentReady(dir, timeoutMs, sinceOffset, expectedSessionId)
404
316
  const deadline = Date.now() + timeoutMs;
405
317
  while (Date.now() < deadline) {
406
318
  try {
407
- const size = fs2.statSync(logPath(dir)).size;
319
+ const size = fs.statSync(logPath(dir)).size;
408
320
  if (size > sinceOffset) {
409
- const fd = fs2.openSync(logPath(dir), "r");
321
+ const fd = fs.openSync(logPath(dir), "r");
410
322
  try {
411
323
  const length = Math.min(size - sinceOffset, 65536);
412
324
  const buffer = Buffer.alloc(length);
413
- fs2.readSync(
325
+ fs.readSync(
414
326
  fd,
415
327
  buffer,
416
328
  0,
@@ -421,7 +333,7 @@ async function waitForAgentReady(dir, timeoutMs, sinceOffset, expectedSessionId)
421
333
  if (slice.includes('"type":"agent.ready"') && slice.includes(expectedSessionId))
422
334
  return true;
423
335
  } finally {
424
- fs2.closeSync(fd);
336
+ fs.closeSync(fd);
425
337
  }
426
338
  }
427
339
  } catch {
@@ -432,12 +344,12 @@ async function waitForAgentReady(dir, timeoutMs, sinceOffset, expectedSessionId)
432
344
  }
433
345
  function imForwardConfigured(dir) {
434
346
  const layers = [
435
- path2.join(dir, ".pie", "im-forward.json"),
436
- path2.join(os.homedir(), ".pie", "im-forward.json")
347
+ path.join(dir, ".pie", "im-forward.json"),
348
+ path.join(os.homedir(), ".pie", "im-forward.json")
437
349
  ];
438
350
  for (const layer of layers) {
439
351
  try {
440
- const parsed = JSON.parse(fs2.readFileSync(layer, "utf8"));
352
+ const parsed = JSON.parse(fs.readFileSync(layer, "utf8"));
441
353
  if (typeof parsed.provider === "string") return true;
442
354
  } catch {
443
355
  }
@@ -459,8 +371,8 @@ To bind a separate app for the manager only, put a project-layer config at ~/.pi
459
371
  function managerSpawnEnv() {
460
372
  const env = { ...process.env, PIE_PROC_CURATED_NAME: "manager" };
461
373
  try {
462
- const configPath = path2.join(workspaceDir(), "config.json");
463
- const parsed = JSON.parse(fs2.readFileSync(configPath, "utf8"));
374
+ const configPath = path.join(workspaceDir(), "config.json");
375
+ const parsed = JSON.parse(fs.readFileSync(configPath, "utf8"));
464
376
  const provider = typeof parsed.provider === "string" ? parsed.provider.trim() : "";
465
377
  const modelId = typeof parsed.modelId === "string" ? parsed.modelId.trim() : "";
466
378
  if (provider && modelId) {
@@ -475,13 +387,52 @@ function managerSpawnEnv() {
475
387
  function platformServiceName() {
476
388
  return "dev.pie.manager";
477
389
  }
478
- function requestWindowsServiceStart(dir) {
479
- execFileSync2("schtasks", ["/Run", "/TN", platformServiceName()], {
480
- stdio: ["ignore", "pipe", "pipe"],
481
- windowsHide: true,
482
- timeout: 2e4
483
- });
484
- console.log(`Manager service start requested (schtasks /Run). Log: ${logPath(dir)}`);
390
+ function requestPlatformServiceStart(dir) {
391
+ if (process.platform === "win32") {
392
+ execFileSync("schtasks", ["/Run", "/TN", platformServiceName()], {
393
+ stdio: ["ignore", "pipe", "pipe"],
394
+ windowsHide: true,
395
+ timeout: 2e4
396
+ });
397
+ console.log(`Manager service start requested (schtasks /Run). Log: ${logPath(dir)}`);
398
+ return;
399
+ }
400
+ if (process.platform === "darwin") {
401
+ const plist = path.join(os.homedir(), "Library", "LaunchAgents", `${platformServiceName()}.plist`);
402
+ if (!fs.existsSync(plist)) {
403
+ console.error(`Service plist missing (${plist}); run pie manager --uninstall-service then --install-service.`);
404
+ process.exitCode = 1;
405
+ return;
406
+ }
407
+ if (queryPlatformServiceState() === "running") {
408
+ console.log(`Manager service is already running (launchd). Log: ${logPath(dir)}`);
409
+ return;
410
+ }
411
+ const uid = process.getuid?.() ?? 501;
412
+ const presence = queryLaunchdServicePresence(platformServiceName());
413
+ if (presence === "present") {
414
+ execFileSync("launchctl", ["kickstart", `gui/${uid}/${platformServiceName()}`], { stdio: ["ignore", "pipe", "pipe"], timeout: 2e4 });
415
+ } else if (presence === "not-found") {
416
+ execFileSync("launchctl", ["load", plist], { stdio: ["ignore", "pipe", "pipe"], timeout: 2e4 });
417
+ } else {
418
+ console.error("Could not determine launchd registration state; run launchctl print to inspect the service.");
419
+ process.exitCode = 1;
420
+ return;
421
+ }
422
+ console.log(`Manager service start requested (launchd). Log: ${logPath(dir)}`);
423
+ return;
424
+ }
425
+ if (process.platform === "linux") {
426
+ execFileSync("systemctl", ["--user", "start", platformServiceName()], {
427
+ stdio: ["ignore", "pipe", "pipe"],
428
+ timeout: 2e4
429
+ });
430
+ console.log(`Manager service start requested (systemctl --user start). Log: ${logPath(dir)}`);
431
+ return;
432
+ }
433
+ console.log(
434
+ "The manager is managed by a system service (launchd/systemd/scheduled task). To take over manually, run --uninstall-service first."
435
+ );
485
436
  }
486
437
  function xmlEscape(value) {
487
438
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
@@ -508,9 +459,9 @@ function installService(dir, state) {
508
459
  if (typeof value !== "string" || value.length === 0) return void 0;
509
460
  const home = os.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
510
461
  if (value === "~") return home;
511
- if (value.startsWith("~/")) return path2.resolve(path2.join(home, value.slice(2)));
512
- if (path2.isAbsolute(value)) return value;
513
- return path2.resolve(value);
462
+ if (value.startsWith("~/")) return path.resolve(path.join(home, value.slice(2)));
463
+ if (path.isAbsolute(value)) return value;
464
+ return path.resolve(value);
514
465
  };
515
466
  const serviceEnv = [
516
467
  ["PIE_PROC_CURATED_NAME", "manager"],
@@ -539,28 +490,29 @@ ${envPlist}
539
490
  <key>StandardOutPath</key><string>${xmlEscape(logFile)}</string>
540
491
  <key>StandardErrorPath</key><string>${xmlEscape(logFile)}</string>
541
492
  </dict></plist>`;
542
- const target = path2.join(
493
+ const target = path.join(
543
494
  os.homedir(),
544
495
  "Library",
545
496
  "LaunchAgents",
546
497
  `${platformServiceName()}.plist`
547
498
  );
548
- fs2.mkdirSync(path2.dirname(target), { recursive: true });
549
- fs2.writeFileSync(target, plist);
499
+ fs.mkdirSync(path.dirname(target), { recursive: true });
500
+ fs.writeFileSync(target, plist);
550
501
  try {
551
- execFileSync2("launchctl", ["unload", target], { stdio: "ignore" });
502
+ execFileSync("launchctl", ["unload", target], { stdio: "ignore" });
552
503
  } catch {
553
504
  }
554
- execFileSync2("launchctl", ["load", target]);
505
+ execFileSync("launchctl", ["load", target]);
555
506
  console.log(`Installed launchd service: ${target} (RunAtLoad + KeepAlive)`);
556
507
  return;
557
508
  }
558
509
  if (process.platform === "linux") {
559
- const unitDir = path2.join(os.homedir(), ".config", "systemd", "user");
560
- fs2.mkdirSync(unitDir, { recursive: true });
510
+ const unitDir = path.join(os.homedir(), ".config", "systemd", "user");
511
+ fs.mkdirSync(unitDir, { recursive: true });
561
512
  const unit = `[Unit]
562
513
  Description=Pie manager (resident im-forward host)
563
514
  After=network-online.target
515
+ StartLimitIntervalSec=0
564
516
 
565
517
  [Service]
566
518
  Environment=${systemdEnvironmentToken(`PATH=${servicePath}`)}
@@ -571,45 +523,57 @@ ${serviceEnv.filter(([, v]) => typeof v === "string" && v.length > 0).map(([k, v
571
523
  ExecStart=:${systemdEscape(process.execPath)} ${systemdEscape(entry)} --json-events --idle --session-id ${systemdEscape(state.sessionId)}
572
524
  WorkingDirectory=${systemdScalarPath(dir)}
573
525
  Restart=always
574
- RestartSec=3
526
+ RestartSec=5
575
527
  StandardOutput=append:${systemdScalarPath(logFile)}
576
528
  StandardError=append:${systemdScalarPath(logFile)}
577
529
 
578
530
  [Install]
579
531
  WantedBy=default.target`;
580
- const unitPath = path2.join(unitDir, `${platformServiceName()}.service`);
581
- fs2.writeFileSync(unitPath, unit);
582
- execFileSync2("systemctl", ["--user", "daemon-reload"]);
583
- execFileSync2("systemctl", [
532
+ const unitPath = path.join(unitDir, `${platformServiceName()}.service`);
533
+ fs.writeFileSync(unitPath, unit);
534
+ execFileSync("systemctl", ["--user", "daemon-reload"]);
535
+ execFileSync("systemctl", [
584
536
  "--user",
585
537
  "enable",
586
538
  "--now",
587
539
  platformServiceName()
588
540
  ]);
589
541
  console.log(`Installed systemd user service: ${unitPath} (Restart=always)`);
542
+ try {
543
+ const user = os.userInfo().username;
544
+ const linger = execFileSync("loginctl", ["show-user", user, "-p", "Linger", "--value"], {
545
+ encoding: "utf8",
546
+ stdio: ["ignore", "pipe", "ignore"],
547
+ timeout: 5e3
548
+ }).trim().toLowerCase();
549
+ if (linger !== "yes") {
550
+ console.warn(
551
+ `Note: user lingering is disabled (Linger=${linger || "no"}). For auto-start after reboot without login and surviving SSH logout, run: sudo loginctl enable-linger ${user}`
552
+ );
553
+ }
554
+ } catch {
555
+ }
590
556
  return;
591
557
  }
592
558
  if (process.platform === "win32") {
593
559
  const silentLauncher = installWindowsManagerLauncher(dir, process.execPath, entry, state.sessionId, [
594
560
  ...serviceEnv,
595
561
  ["PATH", servicePath]
596
- ]);
597
- const taskCmd = '"%USERPROFILE%\\.pie\\manager\\service-launcher.exe"';
598
- execFileSync2("schtasks", [
599
- "/Create",
600
- "/TN",
601
- platformServiceName(),
602
- "/TR",
603
- taskCmd,
604
- "/SC",
605
- "ONLOGON",
606
- "/RL",
607
- "LIMITED",
608
- "/F"
609
- ], { windowsHide: true });
610
- console.log(
611
- `Installed scheduled task: ${platformServiceName()} (runs at logon without a console via ${silentLauncher}; set restart-on-failure in Task Scheduler)`
612
- );
562
+ ], { keepAlive: true });
563
+ const startResult = installWindowsManagerScheduledTask({
564
+ taskName: platformServiceName(),
565
+ launcherPath: silentLauncher,
566
+ workingDir: dir
567
+ });
568
+ if (startResult.started) {
569
+ console.log(
570
+ `Installed and started scheduled task: ${platformServiceName()} (runs at logon without a console via ${silentLauncher}; KeepAlive + battery-safe + unlimited runtime)`
571
+ );
572
+ } else {
573
+ console.warn(
574
+ `Installed scheduled task ${platformServiceName()} via ${silentLauncher}, but immediate start failed (${startResult.startError ?? "unknown"}); run 'pie manager start' to start it now.`
575
+ );
576
+ }
613
577
  return;
614
578
  }
615
579
  throw new Error(
@@ -618,51 +582,41 @@ WantedBy=default.target`;
618
582
  }
619
583
  function uninstallService() {
620
584
  if (process.platform === "darwin") {
621
- const target = path2.join(
585
+ const target = path.join(
622
586
  os.homedir(),
623
587
  "Library",
624
588
  "LaunchAgents",
625
589
  `${platformServiceName()}.plist`
626
590
  );
627
- let unloaded = false;
628
- try {
629
- execFileSync2("launchctl", ["unload", target], { stdio: "ignore" });
630
- unloaded = true;
631
- } catch {
632
- unloaded = !fs2.existsSync(target);
633
- }
634
- if (unloaded) {
635
- try {
636
- fs2.rmSync(target);
637
- console.log(`Uninstalled launchd service: ${target}`);
638
- } catch {
639
- console.log("No installed service found (the plist is already gone).");
640
- }
591
+ const result = uninstallMacosLaunchdService(target, platformServiceName());
592
+ if (result.ok) {
593
+ if (result.removedPlist) console.log(`Uninstalled launchd service: ${target}`);
594
+ else console.log("No installed service found (the plist is already gone).");
641
595
  return true;
642
596
  }
643
597
  console.error(
644
- "launchctl unload failed; the service may still be loaded, so the plist and its ownership are kept."
598
+ "launchctl unload failed; the service may still be registered, so the plist and its ownership are kept."
645
599
  );
646
600
  return false;
647
601
  }
648
602
  if (process.platform === "linux") {
649
603
  let ok = true;
650
604
  try {
651
- execFileSync2("systemctl", [
605
+ execFileSync("systemctl", [
652
606
  "--user",
653
607
  "disable",
654
608
  "--now",
655
609
  platformServiceName()
656
610
  ]);
657
611
  } catch {
658
- const unitPath2 = path2.join(
612
+ const unitPath2 = path.join(
659
613
  os.homedir(),
660
614
  ".config",
661
615
  "systemd",
662
616
  "user",
663
617
  `${platformServiceName()}.service`
664
618
  );
665
- ok = !fs2.existsSync(unitPath2);
619
+ ok = !fs.existsSync(unitPath2);
666
620
  if (!ok) {
667
621
  console.error(
668
622
  "systemctl disable failed; the service may still be running, so the unit file and its ownership are kept."
@@ -670,7 +624,7 @@ function uninstallService() {
670
624
  return false;
671
625
  }
672
626
  }
673
- const unitPath = path2.join(
627
+ const unitPath = path.join(
674
628
  os.homedir(),
675
629
  ".config",
676
630
  "systemd",
@@ -678,8 +632,8 @@ function uninstallService() {
678
632
  `${platformServiceName()}.service`
679
633
  );
680
634
  try {
681
- fs2.rmSync(unitPath);
682
- execFileSync2("systemctl", ["--user", "daemon-reload"]);
635
+ fs.rmSync(unitPath);
636
+ execFileSync("systemctl", ["--user", "daemon-reload"]);
683
637
  console.log(`Uninstalled systemd service.`);
684
638
  } catch {
685
639
  }
@@ -688,14 +642,14 @@ function uninstallService() {
688
642
  if (process.platform === "win32") {
689
643
  let endOutcome = "ended";
690
644
  try {
691
- execFileSync2("schtasks", ["/End", "/TN", platformServiceName()], {
645
+ execFileSync("schtasks", ["/End", "/TN", platformServiceName()], {
692
646
  stdio: ["ignore", "pipe", "pipe"],
693
647
  windowsHide: true
694
648
  });
695
649
  } catch (endError) {
696
650
  const err = endError;
697
651
  const text = `${String(err.stderr ?? "")} ${String(err.stdout ?? "")} ${String(err.message ?? "")}`;
698
- endOutcome = /cannot find|does not exist|not found/i.test(text) ? "not-found" : "error";
652
+ endOutcome = isWindowsTaskAlreadyStoppedDetail(text) || queryWindowsServiceTaskState() === "stopped" ? "not-found" : "error";
699
653
  }
700
654
  if (endOutcome === "error") {
701
655
  console.error(
@@ -705,20 +659,25 @@ function uninstallService() {
705
659
  }
706
660
  let registrationGone = false;
707
661
  try {
708
- execFileSync2("schtasks", ["/Delete", "/TN", platformServiceName(), "/F"], { windowsHide: true });
662
+ execFileSync("schtasks", ["/Delete", "/TN", platformServiceName(), "/F"], { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
709
663
  registrationGone = true;
710
664
  console.log("Uninstalled scheduled task.");
711
665
  } catch {
712
- try {
713
- const probe = execFileSync2(
714
- "schtasks",
715
- ["/Query", "/TN", platformServiceName()],
716
- { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
717
- ).toString();
718
- registrationGone = /cannot find|does not exist|not found/i.test(probe) || probe.trim().length === 0;
719
- } catch (queryError) {
720
- const text = String(queryError.stderr ?? "");
721
- registrationGone = /cannot find the file|cannot find|does not exist/i.test(text);
666
+ if (queryWindowsServiceTaskPresence() === "not-found") {
667
+ registrationGone = true;
668
+ } else {
669
+ try {
670
+ const probe = execFileSync(
671
+ "schtasks",
672
+ ["/Query", "/TN", platformServiceName()],
673
+ { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
674
+ ).toString();
675
+ registrationGone = isWindowsTaskNotFoundDetail(probe) || probe.trim().length === 0;
676
+ } catch (queryError) {
677
+ const err = queryError;
678
+ const text = `${String(err.stderr ?? "")} ${String(err.stdout ?? "")} ${String(err.message ?? "")}`;
679
+ registrationGone = isWindowsTaskNotFoundDetail(text);
680
+ }
722
681
  }
723
682
  }
724
683
  if (!registrationGone) {
@@ -770,11 +729,11 @@ async function stopConcierge(state) {
770
729
  return 0;
771
730
  }
772
731
  function startLockDir(dir) {
773
- return path2.join(dir, "start-locks");
732
+ return path.join(dir, "start-locks");
774
733
  }
775
734
  function withStartLock(dir, fn) {
776
735
  const locks = startLockDir(dir);
777
- fs2.mkdirSync(locks, { recursive: true });
736
+ fs.mkdirSync(locks, { recursive: true });
778
737
  const deadline = Date.now() + 9e4;
779
738
  let mine;
780
739
  for (; ; ) {
@@ -784,7 +743,7 @@ function withStartLock(dir, fn) {
784
743
  );
785
744
  let latest = 0;
786
745
  try {
787
- for (const entry of fs2.readdirSync(locks)) {
746
+ for (const entry of fs.readdirSync(locks)) {
788
747
  const m = /^start\.r(\d+)\.json$/.exec(entry);
789
748
  if (m) latest = Math.max(latest, Number(m[1]));
790
749
  }
@@ -792,11 +751,11 @@ function withStartLock(dir, fn) {
792
751
  }
793
752
  if (latest > 0) {
794
753
  let holderBlocking = false;
795
- const latestPath = path2.join(locks, `start.r${latest}.json`);
754
+ const latestPath = path.join(locks, `start.r${latest}.json`);
796
755
  try {
797
- if (fs2.existsSync(`${latestPath}.released`)) holderBlocking = false;
756
+ if (fs.existsSync(`${latestPath}.released`)) holderBlocking = false;
798
757
  else {
799
- const content = JSON.parse(fs2.readFileSync(latestPath, "utf8"));
758
+ const content = JSON.parse(fs.readFileSync(latestPath, "utf8"));
800
759
  if (typeof content.pid === "number" && content.pid > 0) {
801
760
  try {
802
761
  process.kill(content.pid, 0);
@@ -814,26 +773,26 @@ function withStartLock(dir, fn) {
814
773
  }
815
774
  }
816
775
  const next = latest + 1;
817
- const target = path2.join(locks, `start.r${next}.json`);
776
+ const target = path.join(locks, `start.r${next}.json`);
818
777
  const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
819
778
  try {
820
- fs2.writeFileSync(
779
+ fs.writeFileSync(
821
780
  tmp,
822
781
  JSON.stringify({ pid: process.pid, at: Date.now() })
823
782
  );
824
- fs2.linkSync(tmp, target);
783
+ fs.linkSync(tmp, target);
825
784
  mine = target;
826
785
  break;
827
786
  } catch (error) {
828
787
  try {
829
- fs2.rmSync(tmp, { force: true });
788
+ fs.rmSync(tmp, { force: true });
830
789
  } catch {
831
790
  }
832
791
  if (error.code === "EEXIST") continue;
833
792
  throw error;
834
793
  } finally {
835
794
  try {
836
- if (mine) fs2.rmSync(tmp, { force: true });
795
+ if (mine) fs.rmSync(tmp, { force: true });
837
796
  } catch {
838
797
  }
839
798
  }
@@ -841,16 +800,16 @@ function withStartLock(dir, fn) {
841
800
  return Promise.resolve(fn()).finally(() => {
842
801
  if (!mine) return;
843
802
  try {
844
- const content = JSON.parse(fs2.readFileSync(mine, "utf8"));
803
+ const content = JSON.parse(fs.readFileSync(mine, "utf8"));
845
804
  if (content.pid === process.pid) {
846
805
  const tmp = `${mine}.released.${process.pid}.tmp`;
847
- fs2.writeFileSync(tmp, String(Date.now()));
806
+ fs.writeFileSync(tmp, String(Date.now()));
848
807
  try {
849
- fs2.linkSync(tmp, `${mine}.released`);
808
+ fs.linkSync(tmp, `${mine}.released`);
850
809
  } catch {
851
810
  }
852
811
  try {
853
- fs2.rmSync(tmp, { force: true });
812
+ fs.rmSync(tmp, { force: true });
854
813
  } catch {
855
814
  }
856
815
  }
@@ -863,7 +822,7 @@ async function runUpgradeCommand(args) {
863
822
  console.log("Usage: pie manager upgrade [--target <latest|x.y.z>] [--force]");
864
823
  return;
865
824
  }
866
- const { upgradePaths, performUpgrade, cliEffects, parseTarget } = await import("./manager-upgrade-WHER3WTJ.js");
825
+ const { upgradePaths, performUpgrade, cliEffects, parseTarget } = await import("./manager-upgrade-DYRQ7YZ5.js");
867
826
  let targetRaw;
868
827
  let force = false;
869
828
  for (let i = 0; i < args.length; i++) {
@@ -926,7 +885,7 @@ async function runManagerCommand(args) {
926
885
  let running = false;
927
886
  try {
928
887
  if (process.platform === "darwin") {
929
- const listing = execFileSync2("launchctl", ["list"], {
888
+ const listing = execFileSync("launchctl", ["list"], {
930
889
  encoding: "utf8",
931
890
  stdio: ["ignore", "pipe", "ignore"]
932
891
  });
@@ -943,17 +902,26 @@ async function runManagerCommand(args) {
943
902
  );
944
903
  }
945
904
  } else if (process.platform === "linux") {
946
- execFileSync2("systemctl", [
905
+ execFileSync("systemctl", [
947
906
  "--user",
948
907
  "is-active",
949
908
  "--quiet",
950
909
  platformServiceName()
951
910
  ]);
952
911
  running = true;
912
+ } else if (process.platform === "win32") {
913
+ const winState = queryWindowsServiceTaskState();
914
+ if (winState === "unknown") {
915
+ console.log(`service: ${platformServiceName()} (unknown)`);
916
+ console.log(`workspace: ${dir}`);
917
+ console.log(`log: ${logPath(dir)}`);
918
+ return;
919
+ }
920
+ running = winState === "running";
953
921
  } else {
954
- console.log(
955
- `service: ${platformServiceName()} (unknown \u2014 Windows status query not implemented)`
956
- );
922
+ console.log(`service: ${platformServiceName()} (unknown)`);
923
+ console.log(`workspace: ${dir}`);
924
+ console.log(`log: ${logPath(dir)}`);
957
925
  return;
958
926
  }
959
927
  } catch {
@@ -981,11 +949,11 @@ async function runManagerCommand(args) {
981
949
  if (state.service) {
982
950
  if (process.platform === "darwin") {
983
951
  try {
984
- execFileSync2(
952
+ execFileSync(
985
953
  "launchctl",
986
954
  [
987
955
  "unload",
988
- path2.join(
956
+ path.join(
989
957
  os.homedir(),
990
958
  "Library",
991
959
  "LaunchAgents",
@@ -1013,7 +981,7 @@ async function runManagerCommand(args) {
1013
981
  }
1014
982
  } else if (process.platform === "linux") {
1015
983
  try {
1016
- execFileSync2("systemctl", [
984
+ execFileSync("systemctl", [
1017
985
  "--user",
1018
986
  "stop",
1019
987
  platformServiceName()
@@ -1030,7 +998,7 @@ async function runManagerCommand(args) {
1030
998
  }
1031
999
  } else if (process.platform === "win32") {
1032
1000
  try {
1033
- execFileSync2("schtasks", ["/End", "/TN", platformServiceName()], {
1001
+ execFileSync("schtasks", ["/End", "/TN", platformServiceName()], {
1034
1002
  stdio: ["ignore", "pipe", "pipe"],
1035
1003
  windowsHide: true
1036
1004
  });
@@ -1038,8 +1006,8 @@ async function runManagerCommand(args) {
1038
1006
  } catch (endError) {
1039
1007
  const err = endError;
1040
1008
  const text = `${String(err.stderr ?? "")} ${String(err.stdout ?? "")} ${String(err.message ?? "")}`;
1041
- if (/cannot find|does not exist|not found/i.test(text)) {
1042
- console.log("The service is not running (task not registered).");
1009
+ if (isWindowsTaskAlreadyStoppedDetail(text) || queryWindowsServiceTaskState() === "stopped") {
1010
+ console.log("The service is not running.");
1043
1011
  } else {
1044
1012
  console.error(
1045
1013
  "Stopping the service failed (schtasks /End); the stop is unconfirmed, so ownership is kept."
@@ -1134,7 +1102,7 @@ async function runManagerCommand(args) {
1134
1102
  tailN = Math.min(n, 1e4);
1135
1103
  }
1136
1104
  const file = logPath(dir);
1137
- if (!fs2.existsSync(file)) {
1105
+ if (!fs.existsSync(file)) {
1138
1106
  console.error(`No manager log yet (${file}). Run pie manager start first.`);
1139
1107
  process.exitCode = 2;
1140
1108
  return;
@@ -1167,21 +1135,21 @@ async function runManagerCommand(args) {
1167
1135
  const readFrom = (offset2) => {
1168
1136
  let fd;
1169
1137
  try {
1170
- fd = fs2.openSync(file, "r");
1138
+ fd = fs.openSync(file, "r");
1171
1139
  } catch {
1172
1140
  return { buf: Buffer.alloc(0), truncated: true, identity: void 0 };
1173
1141
  }
1174
1142
  try {
1175
- const st = fs2.fstatSync(fd);
1143
+ const st = fs.fstatSync(fd);
1176
1144
  const identity = { ino: st.ino, dev: st.dev };
1177
1145
  const size = st.size;
1178
1146
  if (size < offset2) return { buf: Buffer.alloc(0), truncated: true, identity };
1179
1147
  const len = Math.min(size - offset2, READ_CHUNK_BYTES);
1180
1148
  const buf = Buffer.alloc(len);
1181
- const bytesRead = fs2.readSync(fd, buf, 0, len, offset2);
1149
+ const bytesRead = fs.readSync(fd, buf, 0, len, offset2);
1182
1150
  return { buf: buf.subarray(0, bytesRead), truncated: false, identity };
1183
1151
  } finally {
1184
- fs2.closeSync(fd);
1152
+ fs.closeSync(fd);
1185
1153
  }
1186
1154
  };
1187
1155
  const emit = (buf, from) => {
@@ -1252,7 +1220,7 @@ async function runManagerCommand(args) {
1252
1220
  let carriedBuf = Buffer.alloc(0);
1253
1221
  const pump = () => {
1254
1222
  for (; ; ) {
1255
- if (fs2.existsSync(file)) {
1223
+ if (fs.existsSync(file)) {
1256
1224
  const { buf, truncated, identity } = readFrom(offset + carriedBuf.length);
1257
1225
  if (identity && lastInode && (identity.ino !== lastInode.ino || identity.dev !== lastInode.dev)) {
1258
1226
  offset = 0;
@@ -1283,8 +1251,8 @@ async function runManagerCommand(args) {
1283
1251
  };
1284
1252
  const startWatch = () => {
1285
1253
  try {
1286
- watcher = fs2.watch(path2.dirname(file), (event, filename) => {
1287
- if (!filename || filename === path2.basename(file)) pump();
1254
+ watcher = fs.watch(path.dirname(file), (event, filename) => {
1255
+ if (!filename || filename === path.basename(file)) pump();
1288
1256
  });
1289
1257
  watcher.on("error", () => {
1290
1258
  watcher?.close();
@@ -1312,21 +1280,15 @@ async function runManagerCommand(args) {
1312
1280
  return;
1313
1281
  }
1314
1282
  let existing = readState();
1315
- if (existing?.service && process.platform === "win32") {
1283
+ if (existing?.service) {
1316
1284
  const handled = await withStartLock(dir, async () => {
1317
1285
  existing = readState();
1318
1286
  if (!existing?.service) return false;
1319
- requestWindowsServiceStart(dir);
1287
+ requestPlatformServiceStart(dir);
1320
1288
  return true;
1321
1289
  });
1322
1290
  if (handled) return;
1323
1291
  }
1324
- if (existing?.service) {
1325
- console.log(
1326
- "The manager is managed by a system service (launchd/systemd/scheduled task). To take over manually, run --uninstall-service first."
1327
- );
1328
- return;
1329
- }
1330
1292
  const startLiveness = existing ? managerLiveness(existing.pid, existing) : "dead";
1331
1293
  if (existing && (startLiveness === "alive" || startLiveness === "unknown")) {
1332
1294
  console.log(
@@ -1350,7 +1312,7 @@ async function runManagerCommand(args) {
1350
1312
  const procSeed = seedProcConfig(process.cwd());
1351
1313
  if (procSeed.state === "seeded") {
1352
1314
  console.log(
1353
- `Seeded pie-proc config: allowCwd = ${path2.resolve(process.cwd())} (dispatching works now; edit ${procSeed.file} to add roots \u2014 it applies on the next spawn)`
1315
+ `Seeded pie-proc config: allowCwd = ${path.resolve(process.cwd())} (dispatching works now; edit ${procSeed.file} to add roots \u2014 it applies on the next spawn)`
1354
1316
  );
1355
1317
  } else if (procSeed.state === "user-layer") {
1356
1318
  console.log(
@@ -1358,17 +1320,14 @@ async function runManagerCommand(args) {
1358
1320
  );
1359
1321
  } else if (procSeed.state === "too-broad") {
1360
1322
  console.log(
1361
- `Did not seed pie-proc config (the current directory ${path2.resolve(process.cwd())} is too broad). To dispatch work, run: pie manager allow /your/project (writes ${procSeed.file})`
1323
+ `Did not seed pie-proc config (the current directory ${path.resolve(process.cwd())} is too broad). To dispatch work, run: pie manager allow /your/project (writes ${procSeed.file})`
1362
1324
  );
1363
1325
  }
1364
1326
  let readinessReport;
1365
1327
  await withStartLock(dir, async () => {
1366
1328
  const lockedState = readState();
1367
1329
  if (lockedState?.service) {
1368
- if (process.platform === "win32") requestWindowsServiceStart(dir);
1369
- else console.log(
1370
- "The manager is managed by a system service (launchd/systemd/scheduled task). To take over manually, run --uninstall-service first."
1371
- );
1330
+ requestPlatformServiceStart(dir);
1372
1331
  return;
1373
1332
  }
1374
1333
  const lockedLiveness = lockedState ? managerLiveness(lockedState.pid, lockedState) : "dead";
@@ -1382,12 +1341,12 @@ async function runManagerCommand(args) {
1382
1341
  const state = lockedState ?? { sessionId: token };
1383
1342
  let sinceOffset = 0;
1384
1343
  try {
1385
- sinceOffset = fs2.statSync(logPath(dir)).size;
1344
+ sinceOffset = fs.statSync(logPath(dir)).size;
1386
1345
  } catch {
1387
1346
  }
1388
1347
  const pid = spawnResident(state, dir);
1389
1348
  try {
1390
- const listing = execFileSync2("ps", ["-eo", "pid,command"], {
1349
+ const listing = execFileSync("ps", ["-eo", "pid,command"], {
1391
1350
  encoding: "utf8",
1392
1351
  timeout: 3e3,
1393
1352
  windowsHide: true