@cydm/pie 4.4.3 → 4.5.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.
@@ -1,18 +1,120 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
2
  import {
3
3
  readProcessCommandLine
4
- } from "./chunk-X6LBWHK3.js";
4
+ } from "./chunk-7RJXKN7N.js";
5
5
  import {
6
6
  getConfigDir
7
7
  } from "./chunk-CBDQJMUI.js";
8
8
  import "./chunk-LZQXQOPJ.js";
9
9
 
10
10
  // src/commands/manager-cli.ts
11
- import { spawn, execFileSync } from "node:child_process";
11
+ import { spawn, execFileSync as execFileSync2 } from "node:child_process";
12
12
  import { createRequire } from "node:module";
13
- import * as fs from "node:fs";
13
+ import * as fs2 from "node:fs";
14
14
  import * as os from "node:os";
15
+ import * as path2 from "node:path";
16
+
17
+ // src/commands/manager-service-windows.ts
18
+ import * as fs from "node:fs";
15
19
  import * as path from "node:path";
20
+ import { execFileSync } from "node:child_process";
21
+ function installWindowsManagerLauncher(dir, node, entry, sessionId, env) {
22
+ const systemRoot = process.env.SystemRoot || "C:\\Windows";
23
+ const compiler = ["Framework64", "Framework"].map((folder) => path.join(systemRoot, "Microsoft.NET", folder, "v4.0.30319", "csc.exe")).find((file) => fs.existsSync(file));
24
+ if (!compiler) throw new Error("Windows .NET Framework compiler is unavailable; manager service was not changed.");
25
+ const cs = (value) => `@"${value.replace(/"/g, '""')}"`;
26
+ const launcher = path.join(dir, "service-launcher.exe");
27
+ const source = path.join(dir, "service-launcher.cs");
28
+ const output = path.join(dir, `service-launcher.${process.pid}.exe`);
29
+ const command = `"${node}" "${entry}" --json-events --idle --session-id "${sessionId}"`;
30
+ const assignments = env.filter(([, value]) => typeof value === "string" && value.length > 0).map(([key, value]) => `Environment.SetEnvironmentVariable(${cs(key)}, ${cs(value)});`).join("\n ");
31
+ fs.writeFileSync(source, `// Generated by Pie. Reinstall the service to refresh this launcher.
32
+ using System;
33
+ using System.ComponentModel;
34
+ using System.IO;
35
+ using System.Runtime.InteropServices;
36
+ using System.Text;
37
+
38
+ internal static class PieManagerService {
39
+ [StructLayout(LayoutKind.Sequential)] struct SECURITY_ATTRIBUTES { public int Length; public IntPtr Descriptor; public int Inherit; }
40
+ [StructLayout(LayoutKind.Sequential)] struct STARTUPINFO {
41
+ public int Size; public string Reserved, Desktop, Title;
42
+ public int X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags;
43
+ public short ShowWindow, ReservedSize; public IntPtr Reserved2, Input, Output, Error;
44
+ }
45
+ [StructLayout(LayoutKind.Sequential)] struct PROCESS_INFORMATION { public IntPtr Process, Thread; public uint ProcessId, ThreadId; }
46
+ [StructLayout(LayoutKind.Sequential)] struct BASIC_LIMITS {
47
+ public long ProcessTime, JobTime; public uint Flags; public UIntPtr MinWorkingSet, MaxWorkingSet;
48
+ public uint ActiveProcesses; public UIntPtr Affinity; public uint PriorityClass, SchedulingClass;
49
+ }
50
+ [StructLayout(LayoutKind.Sequential)] struct IO_COUNTERS { public ulong ReadOps, WriteOps, OtherOps, ReadBytes, WriteBytes, OtherBytes; }
51
+ [StructLayout(LayoutKind.Sequential)] struct EXTENDED_LIMITS {
52
+ public BASIC_LIMITS Basic; public IO_COUNTERS Io; public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
53
+ }
54
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateJobObject(IntPtr attributes, string name);
55
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool SetInformationJobObject(IntPtr job, int type, ref EXTENDED_LIMITS limits, uint size);
56
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
57
+ [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);
58
+ [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);
59
+ [DllImport("kernel32.dll", SetLastError=true)] static extern uint ResumeThread(IntPtr thread);
60
+ [DllImport("kernel32.dll", SetLastError=true)] static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
61
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process, out uint code);
62
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateProcess(IntPtr process, uint code);
63
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
64
+ static void Check(bool ok) { if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error()); }
65
+ static void Close(IntPtr handle) { if (handle != IntPtr.Zero && handle != new IntPtr(-1)) CloseHandle(handle); }
66
+
67
+ static int Main() {
68
+ IntPtr job = IntPtr.Zero, input = IntPtr.Zero, output = IntPtr.Zero;
69
+ PROCESS_INFORMATION child = new PROCESS_INFORMATION();
70
+ bool assigned = false;
71
+ try {
72
+ ${assignments}
73
+ job = CreateJobObject(IntPtr.Zero, null);
74
+ Check(job != IntPtr.Zero);
75
+ EXTENDED_LIMITS limits = new EXTENDED_LIMITS();
76
+ limits.Basic.Flags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
77
+ Check(SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(EXTENDED_LIMITS))));
78
+ SECURITY_ATTRIBUTES inherit = new SECURITY_ATTRIBUTES();
79
+ inherit.Length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES)); inherit.Inherit = 1;
80
+ input = CreateFile("NUL", 0x80000000, 3, ref inherit, 3, 0, IntPtr.Zero);
81
+ Check(input != new IntPtr(-1));
82
+ output = CreateFile(${cs(path.join(dir, "log.jsonl"))}, 4, 3, ref inherit, 4, 0, IntPtr.Zero); // FILE_APPEND_DATA, OPEN_ALWAYS
83
+ Check(output != new IntPtr(-1));
84
+ STARTUPINFO startup = new STARTUPINFO();
85
+ startup.Size = Marshal.SizeOf(typeof(STARTUPINFO)); startup.Flags = 0x100; // USESTDHANDLES
86
+ startup.Input = input; startup.Output = output; startup.Error = output;
87
+ // CREATE_NO_WINDOW | CREATE_SUSPENDED. The job handle is NOT inheritable.
88
+ Check(CreateProcess(${cs(node)}, new StringBuilder(${cs(command)}), IntPtr.Zero, IntPtr.Zero, true, 0x08000004, IntPtr.Zero, ${cs(dir)}, ref startup, out child));
89
+ Check(AssignProcessToJobObject(job, child.Process)); assigned = true;
90
+ Check(ResumeThread(child.Thread) != UInt32.MaxValue);
91
+ Check(WaitForSingleObject(child.Process, UInt32.MaxValue) == 0);
92
+ uint code; Check(GetExitCodeProcess(child.Process, out code));
93
+ return unchecked((int)code);
94
+ } catch (Exception error) {
95
+ try { File.AppendAllText(${cs(path.join(dir, "service-launcher.log"))}, DateTime.UtcNow.ToString("o") + " " + error + Environment.NewLine); } catch {}
96
+ return 1;
97
+ } finally {
98
+ if (!assigned && child.Process != IntPtr.Zero) TerminateProcess(child.Process, 1);
99
+ Close(job); Close(child.Thread); Close(child.Process); Close(input); Close(output);
100
+ }
101
+ }
102
+ }
103
+ `, { encoding: "utf8", mode: 384 });
104
+ try {
105
+ execFileSync(compiler, ["/nologo", "/target:winexe", "/platform:anycpu", "/optimize+", `/out:${output}`, source], {
106
+ windowsHide: true,
107
+ stdio: ["ignore", "pipe", "pipe"],
108
+ timeout: 3e4
109
+ });
110
+ fs.renameSync(output, launcher);
111
+ } finally {
112
+ fs.rmSync(output, { force: true });
113
+ }
114
+ return launcher;
115
+ }
116
+
117
+ // src/commands/manager-cli.ts
16
118
  var require_ = createRequire(import.meta.url);
17
119
  var CRON_SECTION_MARKER = "## \u5B9A\u65F6\u4EFB\u52A1";
18
120
  var CRON_SECTION = `
@@ -48,33 +150,33 @@ var SEED_AGENTS_MD = `# Pie Manager (manager)
48
150
  - \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
49
151
  ${CRON_SECTION}`;
50
152
  function workspaceDir() {
51
- const dir = path.join(os.homedir(), ".pie", "manager");
153
+ const dir = path2.join(os.homedir(), ".pie", "manager");
52
154
  migrateLegacyWorkspace(dir);
53
155
  return dir;
54
156
  }
55
157
  function tailWorkspaceDir() {
56
- const dir = path.join(os.homedir(), ".pie", "manager");
57
- if (fs.existsSync(dir)) return dir;
58
- const legacy = path.join(os.homedir(), ".pie", "concierge");
59
- return fs.existsSync(legacy) ? legacy : dir;
158
+ const dir = path2.join(os.homedir(), ".pie", "manager");
159
+ if (fs2.existsSync(dir)) return dir;
160
+ const legacy = path2.join(os.homedir(), ".pie", "concierge");
161
+ return fs2.existsSync(legacy) ? legacy : dir;
60
162
  }
61
163
  var migrationChecked = false;
62
164
  function migrateLegacyWorkspace(newDir) {
63
165
  if (migrationChecked) return;
64
166
  migrationChecked = true;
65
- const legacy = path.join(os.homedir(), ".pie", "concierge");
66
- if (!fs.existsSync(legacy)) return;
67
- if (fs.existsSync(newDir)) {
167
+ const legacy = path2.join(os.homedir(), ".pie", "concierge");
168
+ if (!fs2.existsSync(legacy)) return;
169
+ if (fs2.existsSync(newDir)) {
68
170
  console.warn(`Both ~/.pie/manager and the legacy ~/.pie/concierge exist; leaving the legacy directory untouched. Merge manually if needed.`);
69
171
  return;
70
172
  }
71
173
  try {
72
- fs.mkdirSync(path.dirname(newDir), { recursive: true });
73
- fs.renameSync(legacy, newDir);
74
- const legacyState = path.join(newDir, "concierge.json");
75
- if (fs.existsSync(legacyState)) {
174
+ fs2.mkdirSync(path2.dirname(newDir), { recursive: true });
175
+ fs2.renameSync(legacy, newDir);
176
+ const legacyState = path2.join(newDir, "concierge.json");
177
+ if (fs2.existsSync(legacyState)) {
76
178
  try {
77
- fs.renameSync(legacyState, path.join(newDir, "manager.json"));
179
+ fs2.renameSync(legacyState, path2.join(newDir, "manager.json"));
78
180
  } catch {
79
181
  }
80
182
  }
@@ -84,17 +186,17 @@ function migrateLegacyWorkspace(newDir) {
84
186
  }
85
187
  }
86
188
  function ensureSessionToken(dir) {
87
- const tokenFile = path.join(dir, "session-token");
189
+ const tokenFile = path2.join(dir, "session-token");
88
190
  for (let attempt = 0; attempt < 5; attempt += 1) {
89
191
  const mine = `manager-${os.hostname().split(".")[0]}-${Math.random().toString(36).slice(2, 8)}`;
90
192
  const tmp = `${tokenFile}.${process.pid}.${attempt}.tmp`;
91
193
  let tmpKept = false;
92
194
  try {
93
- fs.writeFileSync(tmp, mine);
195
+ fs2.writeFileSync(tmp, mine);
94
196
  tmpKept = true;
95
- fs.linkSync(tmp, tokenFile);
197
+ fs2.linkSync(tmp, tokenFile);
96
198
  try {
97
- fs.rmSync(tmp, { force: true });
199
+ fs2.rmSync(tmp, { force: true });
98
200
  tmpKept = false;
99
201
  } catch {
100
202
  }
@@ -102,7 +204,7 @@ function ensureSessionToken(dir) {
102
204
  if (error.code !== "EEXIST") {
103
205
  if (tmpKept) {
104
206
  try {
105
- fs.rmSync(tmp, { force: true });
207
+ fs2.rmSync(tmp, { force: true });
106
208
  } catch {
107
209
  }
108
210
  }
@@ -110,7 +212,7 @@ function ensureSessionToken(dir) {
110
212
  }
111
213
  const existing = (() => {
112
214
  try {
113
- return fs.readFileSync(tokenFile, "utf8").trim();
215
+ return fs2.readFileSync(tokenFile, "utf8").trim();
114
216
  } catch {
115
217
  return "";
116
218
  }
@@ -118,21 +220,21 @@ function ensureSessionToken(dir) {
118
220
  if (existing) {
119
221
  if (tmpKept) {
120
222
  try {
121
- fs.rmSync(tmp, { force: true });
223
+ fs2.rmSync(tmp, { force: true });
122
224
  } catch {
123
225
  }
124
226
  }
125
227
  return existing;
126
228
  }
127
229
  try {
128
- fs.renameSync(tmp, tokenFile);
230
+ fs2.renameSync(tmp, tokenFile);
129
231
  tmpKept = false;
130
232
  } catch {
131
233
  }
132
234
  }
133
235
  const settled = (() => {
134
236
  try {
135
- return fs.readFileSync(tokenFile, "utf8").trim();
237
+ return fs2.readFileSync(tokenFile, "utf8").trim();
136
238
  } catch {
137
239
  return "";
138
240
  }
@@ -140,7 +242,7 @@ function ensureSessionToken(dir) {
140
242
  if (settled) return settled;
141
243
  if (tmpKept) {
142
244
  try {
143
- fs.rmSync(tmp, { force: true });
245
+ fs2.rmSync(tmp, { force: true });
144
246
  } catch {
145
247
  }
146
248
  }
@@ -148,20 +250,20 @@ function ensureSessionToken(dir) {
148
250
  throw new Error("cannot establish the manager workspace token; retry");
149
251
  }
150
252
  function statePath(dir = workspaceDir()) {
151
- const current = path.join(dir, "manager.json");
152
- if (!fs.existsSync(current)) {
153
- const legacy = path.join(dir, "concierge.json");
154
- if (fs.existsSync(legacy)) return legacy;
253
+ const current = path2.join(dir, "manager.json");
254
+ if (!fs2.existsSync(current)) {
255
+ const legacy = path2.join(dir, "concierge.json");
256
+ if (fs2.existsSync(legacy)) return legacy;
155
257
  }
156
258
  return current;
157
259
  }
158
260
  function logPath(dir = workspaceDir()) {
159
- return path.join(dir, "log.jsonl");
261
+ return path2.join(dir, "log.jsonl");
160
262
  }
161
263
  function readState(dir = workspaceDir()) {
162
264
  try {
163
265
  const raw = JSON.parse(
164
- fs.readFileSync(statePath(dir), "utf8")
266
+ fs2.readFileSync(statePath(dir), "utf8")
165
267
  );
166
268
  return typeof raw.sessionId === "string" && raw.sessionId ? raw : void 0;
167
269
  } catch {
@@ -169,10 +271,10 @@ function readState(dir = workspaceDir()) {
169
271
  }
170
272
  }
171
273
  function writeState(state, dir = workspaceDir()) {
172
- fs.mkdirSync(dir, { recursive: true });
274
+ fs2.mkdirSync(dir, { recursive: true });
173
275
  const tmp = `${statePath(dir)}.${process.pid}.tmp`;
174
- fs.writeFileSync(tmp, JSON.stringify(state, null, " "));
175
- fs.renameSync(tmp, statePath(dir));
276
+ fs2.writeFileSync(tmp, JSON.stringify(state, null, " "));
277
+ fs2.renameSync(tmp, statePath(dir));
176
278
  }
177
279
  function managerLiveness(pid, state) {
178
280
  if (!pid || pid <= 0) return "dead";
@@ -196,51 +298,51 @@ function isConciergeAlive(pid, state) {
196
298
  return managerLiveness(pid, state) === "alive";
197
299
  }
198
300
  function seedWorkspace(dir) {
199
- fs.mkdirSync(path.join(dir, ".pie"), { recursive: true });
200
- const agents = path.join(dir, "AGENTS.md");
201
- if (!fs.existsSync(agents)) {
202
- fs.writeFileSync(agents, SEED_AGENTS_MD);
301
+ fs2.mkdirSync(path2.join(dir, ".pie"), { recursive: true });
302
+ const agents = path2.join(dir, "AGENTS.md");
303
+ if (!fs2.existsSync(agents)) {
304
+ fs2.writeFileSync(agents, SEED_AGENTS_MD);
203
305
  return;
204
306
  }
205
307
  let current;
206
308
  try {
207
- current = fs.readFileSync(agents, "utf8");
309
+ current = fs2.readFileSync(agents, "utf8");
208
310
  } catch {
209
311
  return;
210
312
  }
211
- if (!current.includes(CRON_SECTION_MARKER)) fs.appendFileSync(agents, CRON_SECTION);
313
+ if (!current.includes(CRON_SECTION_MARKER)) fs2.appendFileSync(agents, CRON_SECTION);
212
314
  const v1Marker = "\u4F60\u662F\u7528\u6237\u5728 IM \u4E0A\u7684\u552F\u4E00\u8054\u7EDC\u70B9\u3002\u9ED8\u8BA4\u6D3E\u6D3B";
213
315
  const v2Marker = "\u4F60\u662F\u88AB\u52A8\u8D77\u6B65\u7684";
214
316
  if (current.includes(v1Marker) && !current.includes(v2Marker)) {
215
- fs.writeFileSync(agents, SEED_AGENTS_MD);
317
+ fs2.writeFileSync(agents, SEED_AGENTS_MD);
216
318
  }
217
319
  const oldV2Intro = "\u4F60\u662F\u7528\u6237\u7684\u5E38\u9A7B\u7BA1\u5BB6 pie";
218
320
  const newV2Intro = "\u4F60\u662F\u7528\u6237\u7684\u5E38\u9A7B manager pie";
219
321
  if (current.includes(oldV2Intro) && !current.includes(newV2Intro)) {
220
- fs.writeFileSync(agents, SEED_AGENTS_MD);
322
+ fs2.writeFileSync(agents, SEED_AGENTS_MD);
221
323
  } else if (current.includes("\u7BA1\u5BB6") && current.includes(v2Marker) && !current.includes(newV2Intro)) {
222
- fs.appendFileSync(agents, "\n> \u6CE8\u610F\uFF1A\u5E38\u9A7B\u89D2\u8272\u5DF2\u66F4\u540D manager\uFF08\u539F\u300C\u7BA1\u5BB6\u300D\uFF09\u3002\u5982\u9700\u65B0\u7248\u89D2\u8272\u5361\u53EF\u624B\u52A8\u66F4\u65B0\u3002\n");
324
+ fs2.appendFileSync(agents, "\n> Note: the resident role is now named manager. Update the role card manually if you want the latest template.\n");
223
325
  }
224
326
  }
225
327
  function isTooBroadForWorkerSandbox(input) {
226
328
  let resolved;
227
329
  try {
228
- resolved = fs.realpathSync(input);
330
+ resolved = fs2.realpathSync(input);
229
331
  } catch {
230
332
  return true;
231
333
  }
232
- const root = path.parse(resolved).root;
334
+ const root = path2.parse(resolved).root;
233
335
  if (resolved === root || resolved === os.homedir()) return true;
234
336
  const forbidden = [os.tmpdir(), "/tmp", "/var/tmp", "/private/tmp", "/private/var/tmp"];
235
337
  for (const candidate of forbidden) {
236
338
  try {
237
- const real = fs.realpathSync(candidate);
339
+ const real = fs2.realpathSync(candidate);
238
340
  if (resolved === real) return true;
239
341
  } catch {
240
342
  }
241
343
  }
242
344
  try {
243
- const stat = fs.statSync(resolved);
345
+ const stat = fs2.statSync(resolved);
244
346
  if ((stat.mode & 2) !== 0 && (stat.mode & 512) === 0) return true;
245
347
  } catch {
246
348
  return true;
@@ -249,18 +351,18 @@ function isTooBroadForWorkerSandbox(input) {
249
351
  }
250
352
  function seedProcConfig(launchCwd) {
251
353
  const root = getConfigDir();
252
- const file = path.join(root, "pie-proc.json");
253
- const resolved = path.resolve(launchCwd);
354
+ const file = path2.join(root, "pie-proc.json");
355
+ const resolved = path2.resolve(launchCwd);
254
356
  try {
255
- if (fs.existsSync(file)) return { state: "exists", file, root };
357
+ if (fs2.existsSync(file)) return { state: "exists", file, root };
256
358
  } catch {
257
359
  return { state: "exists", file, root };
258
360
  }
259
361
  if (isTooBroadForWorkerSandbox(resolved)) {
260
362
  return { state: "too-broad", file, root };
261
363
  }
262
- fs.mkdirSync(root, { recursive: true });
263
- fs.writeFileSync(
364
+ fs2.mkdirSync(root, { recursive: true });
365
+ fs2.writeFileSync(
264
366
  file,
265
367
  `${JSON.stringify({ allowCwd: [resolved] }, null, " ")}
266
368
  `
@@ -268,15 +370,15 @@ function seedProcConfig(launchCwd) {
268
370
  return { state: "seeded", file, root };
269
371
  }
270
372
  function cliEntry() {
271
- return process.argv[1] ? path.resolve(process.argv[1]) : "";
373
+ return process.argv[1] ? path2.resolve(process.argv[1]) : "";
272
374
  }
273
375
  function resolveTsxLoaderUrl() {
274
376
  for (let i = 0; i < process.execArgv.length - 1; i += 1) {
275
377
  if (process.execArgv[i] === "--import") {
276
378
  const target = process.execArgv[i + 1];
277
- if (target && !path.isAbsolute(target) && !target.startsWith("file:")) {
379
+ if (target && !path2.isAbsolute(target) && !target.startsWith("file:")) {
278
380
  try {
279
- return require_.resolve(target, { paths: [path.dirname(cliEntry())] }) ? pathToFileURLResolved(target) : target;
381
+ return require_.resolve(target, { paths: [path2.dirname(cliEntry())] }) ? pathToFileURLResolved(target) : target;
280
382
  } catch {
281
383
  return target;
282
384
  }
@@ -288,12 +390,12 @@ function resolveTsxLoaderUrl() {
288
390
  }
289
391
  function pathToFileURLResolved(spec) {
290
392
  try {
291
- const pkgRoot = path.dirname(
393
+ const pkgRoot = path2.dirname(
292
394
  require_.resolve(`${spec}/package.json`, {
293
- paths: [path.dirname(cliEntry())]
395
+ paths: [path2.dirname(cliEntry())]
294
396
  })
295
397
  );
296
- return path.join(pkgRoot, "dist", "loader.mjs");
398
+ return path2.join(pkgRoot, "dist", "loader.mjs");
297
399
  } catch {
298
400
  return spec;
299
401
  }
@@ -301,7 +403,7 @@ function pathToFileURLResolved(spec) {
301
403
  function spawnResident(state, dir) {
302
404
  const entry = cliEntry();
303
405
  if (!entry) throw new Error("cannot resolve the pie entry point");
304
- const out = fs.openSync(logPath(dir), "a");
406
+ const out = fs2.openSync(logPath(dir), "a");
305
407
  const loaderAbs = resolveTsxLoaderUrl();
306
408
  const passthrough = loaderAbs ? ["--import", loaderAbs] : process.execArgv.filter(
307
409
  (a) => a !== "--import" && !a.startsWith("--import=")
@@ -332,13 +434,13 @@ async function waitForAgentReady(dir, timeoutMs, sinceOffset, expectedSessionId)
332
434
  const deadline = Date.now() + timeoutMs;
333
435
  while (Date.now() < deadline) {
334
436
  try {
335
- const size = fs.statSync(logPath(dir)).size;
437
+ const size = fs2.statSync(logPath(dir)).size;
336
438
  if (size > sinceOffset) {
337
- const fd = fs.openSync(logPath(dir), "r");
439
+ const fd = fs2.openSync(logPath(dir), "r");
338
440
  try {
339
441
  const length = Math.min(size - sinceOffset, 65536);
340
442
  const buffer = Buffer.alloc(length);
341
- fs.readSync(
443
+ fs2.readSync(
342
444
  fd,
343
445
  buffer,
344
446
  0,
@@ -349,7 +451,7 @@ async function waitForAgentReady(dir, timeoutMs, sinceOffset, expectedSessionId)
349
451
  if (slice.includes('"type":"agent.ready"') && slice.includes(expectedSessionId))
350
452
  return true;
351
453
  } finally {
352
- fs.closeSync(fd);
454
+ fs2.closeSync(fd);
353
455
  }
354
456
  }
355
457
  } catch {
@@ -360,12 +462,12 @@ async function waitForAgentReady(dir, timeoutMs, sinceOffset, expectedSessionId)
360
462
  }
361
463
  function imForwardConfigured(dir) {
362
464
  const layers = [
363
- path.join(dir, ".pie", "im-forward.json"),
364
- path.join(os.homedir(), ".pie", "im-forward.json")
465
+ path2.join(dir, ".pie", "im-forward.json"),
466
+ path2.join(os.homedir(), ".pie", "im-forward.json")
365
467
  ];
366
468
  for (const layer of layers) {
367
469
  try {
368
- const parsed = JSON.parse(fs.readFileSync(layer, "utf8"));
470
+ const parsed = JSON.parse(fs2.readFileSync(layer, "utf8"));
369
471
  if (typeof parsed.provider === "string") return true;
370
472
  } catch {
371
473
  }
@@ -387,8 +489,8 @@ To bind a separate app for the manager only, put a project-layer config at ~/.pi
387
489
  function managerSpawnEnv() {
388
490
  const env = { ...process.env, PIE_PROC_CURATED_NAME: "manager" };
389
491
  try {
390
- const configPath = path.join(workspaceDir(), "config.json");
391
- const parsed = JSON.parse(fs.readFileSync(configPath, "utf8"));
492
+ const configPath = path2.join(workspaceDir(), "config.json");
493
+ const parsed = JSON.parse(fs2.readFileSync(configPath, "utf8"));
392
494
  const provider = typeof parsed.provider === "string" ? parsed.provider.trim() : "";
393
495
  const modelId = typeof parsed.modelId === "string" ? parsed.modelId.trim() : "";
394
496
  if (provider && modelId) {
@@ -403,6 +505,14 @@ function managerSpawnEnv() {
403
505
  function platformServiceName() {
404
506
  return "dev.pie.manager";
405
507
  }
508
+ function requestWindowsServiceStart(dir) {
509
+ execFileSync2("schtasks", ["/Run", "/TN", platformServiceName()], {
510
+ stdio: ["ignore", "pipe", "pipe"],
511
+ windowsHide: true,
512
+ timeout: 2e4
513
+ });
514
+ console.log(`Manager service start requested (schtasks /Run). Log: ${logPath(dir)}`);
515
+ }
406
516
  function xmlEscape(value) {
407
517
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
408
518
  }
@@ -428,9 +538,9 @@ function installService(dir, state) {
428
538
  if (typeof value !== "string" || value.length === 0) return void 0;
429
539
  const home = os.homedir() || process.env.HOME || process.env.USERPROFILE || "/tmp";
430
540
  if (value === "~") return home;
431
- if (value.startsWith("~/")) return path.resolve(path.join(home, value.slice(2)));
432
- if (path.isAbsolute(value)) return value;
433
- return path.resolve(value);
541
+ if (value.startsWith("~/")) return path2.resolve(path2.join(home, value.slice(2)));
542
+ if (path2.isAbsolute(value)) return value;
543
+ return path2.resolve(value);
434
544
  };
435
545
  const serviceEnv = [
436
546
  ["PIE_PROC_CURATED_NAME", "manager"],
@@ -459,25 +569,25 @@ ${envPlist}
459
569
  <key>StandardOutPath</key><string>${xmlEscape(logFile)}</string>
460
570
  <key>StandardErrorPath</key><string>${xmlEscape(logFile)}</string>
461
571
  </dict></plist>`;
462
- const target = path.join(
572
+ const target = path2.join(
463
573
  os.homedir(),
464
574
  "Library",
465
575
  "LaunchAgents",
466
576
  `${platformServiceName()}.plist`
467
577
  );
468
- fs.mkdirSync(path.dirname(target), { recursive: true });
469
- fs.writeFileSync(target, plist);
578
+ fs2.mkdirSync(path2.dirname(target), { recursive: true });
579
+ fs2.writeFileSync(target, plist);
470
580
  try {
471
- execFileSync("launchctl", ["unload", target], { stdio: "ignore" });
581
+ execFileSync2("launchctl", ["unload", target], { stdio: "ignore" });
472
582
  } catch {
473
583
  }
474
- execFileSync("launchctl", ["load", target]);
584
+ execFileSync2("launchctl", ["load", target]);
475
585
  console.log(`Installed launchd service: ${target} (RunAtLoad + KeepAlive)`);
476
586
  return;
477
587
  }
478
588
  if (process.platform === "linux") {
479
- const unitDir = path.join(os.homedir(), ".config", "systemd", "user");
480
- fs.mkdirSync(unitDir, { recursive: true });
589
+ const unitDir = path2.join(os.homedir(), ".config", "systemd", "user");
590
+ fs2.mkdirSync(unitDir, { recursive: true });
481
591
  const unit = `[Unit]
482
592
  Description=Pie manager (resident im-forward host)
483
593
  After=network-online.target
@@ -497,10 +607,10 @@ StandardError=append:${systemdScalarPath(logFile)}
497
607
 
498
608
  [Install]
499
609
  WantedBy=default.target`;
500
- const unitPath = path.join(unitDir, `${platformServiceName()}.service`);
501
- fs.writeFileSync(unitPath, unit);
502
- execFileSync("systemctl", ["--user", "daemon-reload"]);
503
- execFileSync("systemctl", [
610
+ const unitPath = path2.join(unitDir, `${platformServiceName()}.service`);
611
+ fs2.writeFileSync(unitPath, unit);
612
+ execFileSync2("systemctl", ["--user", "daemon-reload"]);
613
+ execFileSync2("systemctl", [
504
614
  "--user",
505
615
  "enable",
506
616
  "--now",
@@ -510,22 +620,25 @@ WantedBy=default.target`;
510
620
  return;
511
621
  }
512
622
  if (process.platform === "win32") {
513
- const envSets = serviceEnv.filter(([, v]) => typeof v === "string" && v.length > 0).map(([k, v]) => `set "${k}=${v}" && `).join("");
514
- const cmd = `cd /d "${dir}" && ${envSets}"${process.execPath}" "${entry}" --json-events --idle --session-id ${state.sessionId} >> "${logFile}" 2>&1`;
515
- execFileSync("schtasks", [
623
+ const silentLauncher = installWindowsManagerLauncher(dir, process.execPath, entry, state.sessionId, [
624
+ ...serviceEnv,
625
+ ["PATH", servicePath]
626
+ ]);
627
+ const taskCmd = '"%USERPROFILE%\\.pie\\manager\\service-launcher.exe"';
628
+ execFileSync2("schtasks", [
516
629
  "/Create",
517
630
  "/TN",
518
631
  platformServiceName(),
519
632
  "/TR",
520
- cmd,
633
+ taskCmd,
521
634
  "/SC",
522
635
  "ONLOGON",
523
636
  "/RL",
524
637
  "LIMITED",
525
638
  "/F"
526
- ]);
639
+ ], { windowsHide: true });
527
640
  console.log(
528
- `Installed scheduled task: ${platformServiceName()} (runs at logon; set restart-on-failure in Task Scheduler)`
641
+ `Installed scheduled task: ${platformServiceName()} (runs at logon without a console via ${silentLauncher}; set restart-on-failure in Task Scheduler)`
529
642
  );
530
643
  return;
531
644
  }
@@ -535,7 +648,7 @@ WantedBy=default.target`;
535
648
  }
536
649
  function uninstallService() {
537
650
  if (process.platform === "darwin") {
538
- const target = path.join(
651
+ const target = path2.join(
539
652
  os.homedir(),
540
653
  "Library",
541
654
  "LaunchAgents",
@@ -543,14 +656,14 @@ function uninstallService() {
543
656
  );
544
657
  let unloaded = false;
545
658
  try {
546
- execFileSync("launchctl", ["unload", target], { stdio: "ignore" });
659
+ execFileSync2("launchctl", ["unload", target], { stdio: "ignore" });
547
660
  unloaded = true;
548
661
  } catch {
549
- unloaded = !fs.existsSync(target);
662
+ unloaded = !fs2.existsSync(target);
550
663
  }
551
664
  if (unloaded) {
552
665
  try {
553
- fs.rmSync(target);
666
+ fs2.rmSync(target);
554
667
  console.log(`Uninstalled launchd service: ${target}`);
555
668
  } catch {
556
669
  console.log("No installed service found (the plist is already gone).");
@@ -565,21 +678,21 @@ function uninstallService() {
565
678
  if (process.platform === "linux") {
566
679
  let ok = true;
567
680
  try {
568
- execFileSync("systemctl", [
681
+ execFileSync2("systemctl", [
569
682
  "--user",
570
683
  "disable",
571
684
  "--now",
572
685
  platformServiceName()
573
686
  ]);
574
687
  } catch {
575
- const unitPath2 = path.join(
688
+ const unitPath2 = path2.join(
576
689
  os.homedir(),
577
690
  ".config",
578
691
  "systemd",
579
692
  "user",
580
693
  `${platformServiceName()}.service`
581
694
  );
582
- ok = !fs.existsSync(unitPath2);
695
+ ok = !fs2.existsSync(unitPath2);
583
696
  if (!ok) {
584
697
  console.error(
585
698
  "systemctl disable failed; the service may still be running, so the unit file and its ownership are kept."
@@ -587,7 +700,7 @@ function uninstallService() {
587
700
  return false;
588
701
  }
589
702
  }
590
- const unitPath = path.join(
703
+ const unitPath = path2.join(
591
704
  os.homedir(),
592
705
  ".config",
593
706
  "systemd",
@@ -595,8 +708,8 @@ function uninstallService() {
595
708
  `${platformServiceName()}.service`
596
709
  );
597
710
  try {
598
- fs.rmSync(unitPath);
599
- execFileSync("systemctl", ["--user", "daemon-reload"]);
711
+ fs2.rmSync(unitPath);
712
+ execFileSync2("systemctl", ["--user", "daemon-reload"]);
600
713
  console.log(`Uninstalled systemd service.`);
601
714
  } catch {
602
715
  }
@@ -605,8 +718,9 @@ function uninstallService() {
605
718
  if (process.platform === "win32") {
606
719
  let endOutcome = "ended";
607
720
  try {
608
- execFileSync("schtasks", ["/End", "/TN", platformServiceName()], {
609
- stdio: ["ignore", "pipe", "pipe"]
721
+ execFileSync2("schtasks", ["/End", "/TN", platformServiceName()], {
722
+ stdio: ["ignore", "pipe", "pipe"],
723
+ windowsHide: true
610
724
  });
611
725
  } catch (endError) {
612
726
  const err = endError;
@@ -621,15 +735,15 @@ function uninstallService() {
621
735
  }
622
736
  let registrationGone = false;
623
737
  try {
624
- execFileSync("schtasks", ["/Delete", "/TN", platformServiceName(), "/F"]);
738
+ execFileSync2("schtasks", ["/Delete", "/TN", platformServiceName(), "/F"], { windowsHide: true });
625
739
  registrationGone = true;
626
740
  console.log("Uninstalled scheduled task.");
627
741
  } catch {
628
742
  try {
629
- const probe = execFileSync(
743
+ const probe = execFileSync2(
630
744
  "schtasks",
631
745
  ["/Query", "/TN", platformServiceName()],
632
- { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }
746
+ { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true }
633
747
  ).toString();
634
748
  registrationGone = /cannot find|does not exist|not found/i.test(probe) || probe.trim().length === 0;
635
749
  } catch (queryError) {
@@ -686,11 +800,11 @@ async function stopConcierge(state) {
686
800
  return 0;
687
801
  }
688
802
  function startLockDir(dir) {
689
- return path.join(dir, "start-locks");
803
+ return path2.join(dir, "start-locks");
690
804
  }
691
805
  function withStartLock(dir, fn) {
692
806
  const locks = startLockDir(dir);
693
- fs.mkdirSync(locks, { recursive: true });
807
+ fs2.mkdirSync(locks, { recursive: true });
694
808
  const deadline = Date.now() + 9e4;
695
809
  let mine;
696
810
  for (; ; ) {
@@ -700,7 +814,7 @@ function withStartLock(dir, fn) {
700
814
  );
701
815
  let latest = 0;
702
816
  try {
703
- for (const entry of fs.readdirSync(locks)) {
817
+ for (const entry of fs2.readdirSync(locks)) {
704
818
  const m = /^start\.r(\d+)\.json$/.exec(entry);
705
819
  if (m) latest = Math.max(latest, Number(m[1]));
706
820
  }
@@ -708,11 +822,11 @@ function withStartLock(dir, fn) {
708
822
  }
709
823
  if (latest > 0) {
710
824
  let holderBlocking = false;
711
- const latestPath = path.join(locks, `start.r${latest}.json`);
825
+ const latestPath = path2.join(locks, `start.r${latest}.json`);
712
826
  try {
713
- if (fs.existsSync(`${latestPath}.released`)) holderBlocking = false;
827
+ if (fs2.existsSync(`${latestPath}.released`)) holderBlocking = false;
714
828
  else {
715
- const content = JSON.parse(fs.readFileSync(latestPath, "utf8"));
829
+ const content = JSON.parse(fs2.readFileSync(latestPath, "utf8"));
716
830
  if (typeof content.pid === "number" && content.pid > 0) {
717
831
  try {
718
832
  process.kill(content.pid, 0);
@@ -730,26 +844,26 @@ function withStartLock(dir, fn) {
730
844
  }
731
845
  }
732
846
  const next = latest + 1;
733
- const target = path.join(locks, `start.r${next}.json`);
847
+ const target = path2.join(locks, `start.r${next}.json`);
734
848
  const tmp = `${target}.${process.pid}.${Date.now().toString(36)}.tmp`;
735
849
  try {
736
- fs.writeFileSync(
850
+ fs2.writeFileSync(
737
851
  tmp,
738
852
  JSON.stringify({ pid: process.pid, at: Date.now() })
739
853
  );
740
- fs.linkSync(tmp, target);
854
+ fs2.linkSync(tmp, target);
741
855
  mine = target;
742
856
  break;
743
857
  } catch (error) {
744
858
  try {
745
- fs.rmSync(tmp, { force: true });
859
+ fs2.rmSync(tmp, { force: true });
746
860
  } catch {
747
861
  }
748
862
  if (error.code === "EEXIST") continue;
749
863
  throw error;
750
864
  } finally {
751
865
  try {
752
- if (mine) fs.rmSync(tmp, { force: true });
866
+ if (mine) fs2.rmSync(tmp, { force: true });
753
867
  } catch {
754
868
  }
755
869
  }
@@ -757,16 +871,16 @@ function withStartLock(dir, fn) {
757
871
  return Promise.resolve(fn()).finally(() => {
758
872
  if (!mine) return;
759
873
  try {
760
- const content = JSON.parse(fs.readFileSync(mine, "utf8"));
874
+ const content = JSON.parse(fs2.readFileSync(mine, "utf8"));
761
875
  if (content.pid === process.pid) {
762
876
  const tmp = `${mine}.released.${process.pid}.tmp`;
763
- fs.writeFileSync(tmp, String(Date.now()));
877
+ fs2.writeFileSync(tmp, String(Date.now()));
764
878
  try {
765
- fs.linkSync(tmp, `${mine}.released`);
879
+ fs2.linkSync(tmp, `${mine}.released`);
766
880
  } catch {
767
881
  }
768
882
  try {
769
- fs.rmSync(tmp, { force: true });
883
+ fs2.rmSync(tmp, { force: true });
770
884
  } catch {
771
885
  }
772
886
  }
@@ -774,6 +888,34 @@ function withStartLock(dir, fn) {
774
888
  }
775
889
  });
776
890
  }
891
+ async function runUpgradeCommand(args) {
892
+ const { upgradePaths, performUpgrade, cliEffects, parseTarget } = await import("./manager-upgrade-YVHK3XZE.js");
893
+ const targetIdx = args.indexOf("--target");
894
+ if (targetIdx >= 0 && typeof args[targetIdx + 1] !== "string") {
895
+ console.error('--target expects "latest" or an x.y.z version (no value given)');
896
+ process.exitCode = 2;
897
+ return;
898
+ }
899
+ const target = parseTarget(targetIdx >= 0 ? args[targetIdx + 1] : void 0);
900
+ if (target === void 0) {
901
+ const given = targetIdx >= 0 ? args[targetIdx + 1] : void 0;
902
+ console.error(`--target expects "latest" or an x.y.z version (got ${JSON.stringify(given)})`);
903
+ process.exitCode = 2;
904
+ return;
905
+ }
906
+ const force = args.includes("--force");
907
+ const paths = upgradePaths(process.argv[1] ?? "");
908
+ console.log(`Upgrading @cydm/pie \u2192 ${target} (this may take a minute)\u2026`);
909
+ const result = await performUpgrade(paths, cliEffects(paths, (m) => console.log(m)), { target, force });
910
+ if (result.ok) {
911
+ console.log(`\u2713 Upgraded ${result.fromVersion} \u2192 ${result.toVersion}`);
912
+ if (result.workersRecycled?.length) console.log(` recycled idle workers: ${result.workersRecycled.map((w) => `${w.name}(${w.pid})`).join(", ")}`);
913
+ if (result.workersSkipped?.length) console.log(` busy workers left as-is: ${result.workersSkipped.map((w) => `${w.name}(${w.pid})`).join(", ")}`);
914
+ } else {
915
+ console.error(`\u2717 Upgrade stopped at "${result.stage}": ${result.detail ?? "unknown"}`);
916
+ process.exitCode = 1;
917
+ }
918
+ }
777
919
  async function runManagerCommand(args) {
778
920
  const sub = args[0] ?? "";
779
921
  const dir = sub === "tail" ? tailWorkspaceDir() : workspaceDir();
@@ -788,7 +930,7 @@ async function runManagerCommand(args) {
788
930
  let running = false;
789
931
  try {
790
932
  if (process.platform === "darwin") {
791
- const listing = execFileSync("launchctl", ["list"], {
933
+ const listing = execFileSync2("launchctl", ["list"], {
792
934
  encoding: "utf8",
793
935
  stdio: ["ignore", "pipe", "ignore"]
794
936
  });
@@ -805,7 +947,7 @@ async function runManagerCommand(args) {
805
947
  );
806
948
  }
807
949
  } else if (process.platform === "linux") {
808
- execFileSync("systemctl", [
950
+ execFileSync2("systemctl", [
809
951
  "--user",
810
952
  "is-active",
811
953
  "--quiet",
@@ -843,11 +985,11 @@ async function runManagerCommand(args) {
843
985
  if (state.service) {
844
986
  if (process.platform === "darwin") {
845
987
  try {
846
- execFileSync(
988
+ execFileSync2(
847
989
  "launchctl",
848
990
  [
849
991
  "unload",
850
- path.join(
992
+ path2.join(
851
993
  os.homedir(),
852
994
  "Library",
853
995
  "LaunchAgents",
@@ -875,7 +1017,7 @@ async function runManagerCommand(args) {
875
1017
  }
876
1018
  } else if (process.platform === "linux") {
877
1019
  try {
878
- execFileSync("systemctl", [
1020
+ execFileSync2("systemctl", [
879
1021
  "--user",
880
1022
  "stop",
881
1023
  platformServiceName()
@@ -892,8 +1034,9 @@ async function runManagerCommand(args) {
892
1034
  }
893
1035
  } else if (process.platform === "win32") {
894
1036
  try {
895
- execFileSync("schtasks", ["/End", "/TN", platformServiceName()], {
896
- stdio: ["ignore", "pipe", "pipe"]
1037
+ execFileSync2("schtasks", ["/End", "/TN", platformServiceName()], {
1038
+ stdio: ["ignore", "pipe", "pipe"],
1039
+ windowsHide: true
897
1040
  });
898
1041
  console.log("Stopped (schtasks /End).");
899
1042
  } catch (endError) {
@@ -969,6 +1112,10 @@ async function runManagerCommand(args) {
969
1112
  process.exitCode = 2;
970
1113
  return;
971
1114
  }
1115
+ if (sub === "upgrade") {
1116
+ await runUpgradeCommand(args.slice(1));
1117
+ return;
1118
+ }
972
1119
  if (sub === "tail") {
973
1120
  const follow = args.includes("-f") || args.includes("--follow");
974
1121
  const jsonOut = args.includes("--json");
@@ -990,7 +1137,7 @@ async function runManagerCommand(args) {
990
1137
  tailN = Math.min(n, 1e4);
991
1138
  }
992
1139
  const file = logPath(dir);
993
- if (!fs.existsSync(file)) {
1140
+ if (!fs2.existsSync(file)) {
994
1141
  console.error(`No manager log yet (${file}). Run pie manager start first.`);
995
1142
  process.exitCode = 2;
996
1143
  return;
@@ -1023,21 +1170,21 @@ async function runManagerCommand(args) {
1023
1170
  const readFrom = (offset2) => {
1024
1171
  let fd;
1025
1172
  try {
1026
- fd = fs.openSync(file, "r");
1173
+ fd = fs2.openSync(file, "r");
1027
1174
  } catch {
1028
1175
  return { buf: Buffer.alloc(0), truncated: true, identity: void 0 };
1029
1176
  }
1030
1177
  try {
1031
- const st = fs.fstatSync(fd);
1178
+ const st = fs2.fstatSync(fd);
1032
1179
  const identity = { ino: st.ino, dev: st.dev };
1033
1180
  const size = st.size;
1034
1181
  if (size < offset2) return { buf: Buffer.alloc(0), truncated: true, identity };
1035
1182
  const len = Math.min(size - offset2, READ_CHUNK_BYTES);
1036
1183
  const buf = Buffer.alloc(len);
1037
- const bytesRead = fs.readSync(fd, buf, 0, len, offset2);
1184
+ const bytesRead = fs2.readSync(fd, buf, 0, len, offset2);
1038
1185
  return { buf: buf.subarray(0, bytesRead), truncated: false, identity };
1039
1186
  } finally {
1040
- fs.closeSync(fd);
1187
+ fs2.closeSync(fd);
1041
1188
  }
1042
1189
  };
1043
1190
  const emit = (buf, from) => {
@@ -1108,7 +1255,7 @@ async function runManagerCommand(args) {
1108
1255
  let carriedBuf = Buffer.alloc(0);
1109
1256
  const pump = () => {
1110
1257
  for (; ; ) {
1111
- if (fs.existsSync(file)) {
1258
+ if (fs2.existsSync(file)) {
1112
1259
  const { buf, truncated, identity } = readFrom(offset + carriedBuf.length);
1113
1260
  if (identity && lastInode && (identity.ino !== lastInode.ino || identity.dev !== lastInode.dev)) {
1114
1261
  offset = 0;
@@ -1139,8 +1286,8 @@ async function runManagerCommand(args) {
1139
1286
  };
1140
1287
  const startWatch = () => {
1141
1288
  try {
1142
- watcher = fs.watch(path.dirname(file), (event, filename) => {
1143
- if (!filename || filename === path.basename(file)) pump();
1289
+ watcher = fs2.watch(path2.dirname(file), (event, filename) => {
1290
+ if (!filename || filename === path2.basename(file)) pump();
1144
1291
  });
1145
1292
  watcher.on("error", () => {
1146
1293
  watcher?.close();
@@ -1167,7 +1314,16 @@ async function runManagerCommand(args) {
1167
1314
  process.exitCode = 2;
1168
1315
  return;
1169
1316
  }
1170
- const existing = readState();
1317
+ let existing = readState();
1318
+ if (existing?.service && process.platform === "win32") {
1319
+ const handled = await withStartLock(dir, async () => {
1320
+ existing = readState();
1321
+ if (!existing?.service) return false;
1322
+ requestWindowsServiceStart(dir);
1323
+ return true;
1324
+ });
1325
+ if (handled) return;
1326
+ }
1171
1327
  if (existing?.service) {
1172
1328
  console.log(
1173
1329
  "The manager is managed by a system service (launchd/systemd/scheduled task). To take over manually, run --uninstall-service first."
@@ -1197,18 +1353,19 @@ async function runManagerCommand(args) {
1197
1353
  const procSeed = seedProcConfig(process.cwd());
1198
1354
  if (procSeed.state === "seeded") {
1199
1355
  console.log(
1200
- `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)`
1356
+ `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)`
1201
1357
  );
1202
1358
  } else if (procSeed.state === "too-broad") {
1203
1359
  console.log(
1204
- `Did not seed pie-proc config (the current directory ${path.resolve(process.cwd())} is too broad). To dispatch work, write ${procSeed.file}: {"allowCwd": ["/your/project"]}`
1360
+ `Did not seed pie-proc config (the current directory ${path2.resolve(process.cwd())} is too broad). To dispatch work, write ${procSeed.file}: {"allowCwd": ["/your/project"]}`
1205
1361
  );
1206
1362
  }
1207
1363
  let readinessReport;
1208
1364
  await withStartLock(dir, async () => {
1209
1365
  const lockedState = readState();
1210
1366
  if (lockedState?.service) {
1211
- console.log(
1367
+ if (process.platform === "win32") requestWindowsServiceStart(dir);
1368
+ else console.log(
1212
1369
  "The manager is managed by a system service (launchd/systemd/scheduled task). To take over manually, run --uninstall-service first."
1213
1370
  );
1214
1371
  return;
@@ -1224,14 +1381,15 @@ async function runManagerCommand(args) {
1224
1381
  const state = lockedState ?? { sessionId: token };
1225
1382
  let sinceOffset = 0;
1226
1383
  try {
1227
- sinceOffset = fs.statSync(logPath(dir)).size;
1384
+ sinceOffset = fs2.statSync(logPath(dir)).size;
1228
1385
  } catch {
1229
1386
  }
1230
1387
  const pid = spawnResident(state, dir);
1231
1388
  try {
1232
- const listing = execFileSync("ps", ["-eo", "pid,command"], {
1389
+ const listing = execFileSync2("ps", ["-eo", "pid,command"], {
1233
1390
  encoding: "utf8",
1234
- timeout: 3e3
1391
+ timeout: 3e3,
1392
+ windowsHide: true
1235
1393
  });
1236
1394
  const token2 = `--session-id ${state.sessionId}`;
1237
1395
  const rivals = String(listing).split("\n").map((line) => line.trim()).filter(