@cydm/pie 4.15.3 → 4.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,10 +3,10 @@ import {
3
3
  distillWorkerLogPath,
4
4
  readDistillWorkerLog,
5
5
  spawnDistillWorker
6
- } from "../../../chunks/chunk-NCO26FXT.js";
6
+ } from "../../../chunks/chunk-MC5ZYWSP.js";
7
7
  import {
8
8
  commitCuratedMemoryBestEffort
9
- } from "../../../chunks/chunk-VWDCKHCC.js";
9
+ } from "../../../chunks/chunk-ZSFE6N5J.js";
10
10
  import {
11
11
  getConfigDir,
12
12
  getSessionsDir,
@@ -25,7 +25,7 @@ import {
25
25
  takeDispatchFrame,
26
26
  wrapInboundText,
27
27
  wrappedMessageMarker
28
- } from "../../../chunks/chunk-TYCKSYUF.js";
28
+ } from "../../../chunks/chunk-XUXKF5ZK.js";
29
29
  import {
30
30
  Type
31
31
  } from "../../../chunks/chunk-XXGYUYXI.js";
@@ -1206,6 +1206,7 @@ var RuntimeBase = class {
1206
1206
  isManager: this.ctx.capabilities?.unattended === true && process.env.PIE_PROC_CURATED_NAME === "manager",
1207
1207
  sessionControls: this.ctx.capabilities?.longLived === true && this.ctx.capabilities.editorInjection === true,
1208
1208
  workerPeek: this.ctx.capabilities?.eventSink === true && this.ctx.capabilities?.longLived === true,
1209
+ yoloMode: Boolean(this.ctx.yoloMode),
1209
1210
  imBinding: currentImBinding()
1210
1211
  });
1211
1212
  return { ...snapshot, allowPeers: [...this.allowPolicy.snapshot()], undeliveredInjections: this.delivery?.undeliveredInjections ?? snapshot.undeliveredInjections ?? 0 };
@@ -1263,7 +1264,7 @@ var RuntimeBase = class {
1263
1264
  return;
1264
1265
  }
1265
1266
  const receipt = await applier(parsed.control, parsed.payload);
1266
- if (receipt?.ok && (parsed.control === "model.set" || parsed.control === "thinking.set")) this.writeStatus();
1267
+ if (receipt?.ok && (parsed.control === "model.set" || parsed.control === "thinking.set" || parsed.control === "yolo.set")) this.writeStatus();
1267
1268
  try {
1268
1269
  this.ctx.appendEntry?.("pie.ipc.control", {
1269
1270
  from: envelope.from,
@@ -26,8 +26,10 @@ background registry sweeps.
26
26
  - `kind:"oneshot"`: the task travels in the `PIE_PROC_ONESHOT_TASK` env
27
27
  var; argv carries only `--session-id <token>` (the CLI entry routes the
28
28
  child role into print mode). Process exit IS the completion.
29
- - `cwd` must CANONICALLY resolve (realpath, symlink-safe) inside an
30
- `allowCwd` root.
29
+ - `cwd` works out of the box for standard user/project directories (filesystem
30
+ and OS system roots are blocked by default); if `~/.pie/pie-proc.json`
31
+ explicitly configures `allowCwd`, `cwd` must CANONICALLY resolve (realpath,
32
+ symlink-safe) inside one of those roots.
31
33
  - `ttlMs` retires an idle RESIDENT automatically (graceful SIGTERM; busy
32
34
  state is read from the worker's pie-ipc status — a "working" worker is
33
35
  never reaped; the entry is retained until death is confirmed).
@@ -42,7 +44,7 @@ background registry sweeps.
42
44
  - **list**: workers with pid / session token / cwd / kind / liveness
43
45
  (alive/dead/unknown) / idle seconds / TTL / IM binding.
44
46
 
45
- ## Configuration `~/.pie/pie-proc.json`
47
+ ## Optional Configuration `~/.pie/pie-proc.json`
46
48
 
47
49
  ```json
48
50
  {
@@ -53,24 +55,20 @@ background registry sweeps.
53
55
  }
54
56
  ```
55
57
 
56
- - `allowCwd` (REQUIRED for spawn; everything else defaults): absolute or `~/`
57
- roots; a spawn cwd must canonically equal or live under one of them.
58
+ - `allowCwd` (OPTIONAL): omit `pie-proc.json` (or omit `allowCwd`) to allow
59
+ standard working directories out of the box while still blocking filesystem
60
+ roots (`/` / `C:\`), OS system directories, and non-sticky world-writable
61
+ directories. Configure `allowCwd` (absolute or `~/` roots, or via
62
+ `pie manager allow <dir>`) only when you want strict allowlist narrowing;
63
+ an explicit empty array `[]` fails closed.
58
64
  - `maxWorkers`: simultaneous alive-worker cap (spawn refuses beyond).
59
65
  - `killGraceMs`: force-kill escalation window after SIGTERM.
60
66
  - `defaultTtlMs`: idle TTL applied when a spawn omits `ttlMs` (0 = never).
61
67
 
62
68
  **The file is re-read on every use (spawn, sweep, kill), so edits take effect
63
- without restarting the host.** That matters on a fresh machine: the config is
64
- usually written *after* a resident host booted, and a load-time snapshot would
65
- make it permanently invisible. A missing or unreadable file means an empty
66
- `allowCwd` — every spawn is refused (fail-closed) with a message that says
67
- whether the file is missing or simply lacks the cwd, and how to write it.
68
-
69
- `pie manager` seeds this file on first run when it is absent, with
70
- `allowCwd` set to the directory `pie manager` was launched from — otherwise
71
- a new machine can chat with the manager but never dispatch a worker. It
72
- never seeds `$HOME` or `/` (that is a security decision for the operator) and
73
- never overwrites an existing file.
69
+ without restarting the host.** A corrupt or unreadable `pie-proc.json` still
70
+ fails closed rather than silently falling back to open mode. `pie manager` no
71
+ longer auto-seeds a launch-directory `pie-proc.json` on first run.
74
72
 
75
73
  ## Registry v2 & audit
76
74
 
@@ -577,7 +577,6 @@ import * as os2 from "node:os";
577
577
  import * as path2 from "node:path";
578
578
  var DEFAULT_MAX_WORKERS = 50;
579
579
  var DEFAULT_CONFIG = {
580
- allowCwd: [],
581
580
  maxWorkers: DEFAULT_MAX_WORKERS,
582
581
  killGraceMs: 15e3,
583
582
  defaultTtlMs: 0
@@ -610,9 +609,13 @@ function readConfigDetailed() {
610
609
  throw new Error("top-level JSON value must be an object");
611
610
  }
612
611
  const raw = parsed;
612
+ if (raw.allowCwd !== void 0 && !Array.isArray(raw.allowCwd)) {
613
+ throw new Error("allowCwd must be an array of directory paths");
614
+ }
615
+ const allowCwd = Array.isArray(raw.allowCwd) ? raw.allowCwd.filter((entry) => typeof entry === "string").map(expandTilde) : void 0;
613
616
  return {
614
617
  config: {
615
- allowCwd: Array.isArray(raw.allowCwd) ? raw.allowCwd.map(expandTilde) : [],
618
+ ...allowCwd !== void 0 ? { allowCwd } : {},
616
619
  maxWorkers: typeof raw.maxWorkers === "number" && raw.maxWorkers > 0 ? Math.floor(raw.maxWorkers) : DEFAULT_CONFIG.maxWorkers,
617
620
  killGraceMs: typeof raw.killGraceMs === "number" && raw.killGraceMs >= 1e3 ? Math.floor(raw.killGraceMs) : DEFAULT_CONFIG.killGraceMs,
618
621
  defaultTtlMs: typeof raw.defaultTtlMs === "number" && raw.defaultTtlMs >= 0 ? Math.floor(raw.defaultTtlMs) : DEFAULT_CONFIG.defaultTtlMs
@@ -639,14 +642,54 @@ function canonicalDir(dir) {
639
642
  if (!stat.isDirectory()) throw new Error(`"${dir}" is not a directory`);
640
643
  return real;
641
644
  }
645
+ var POSIX_SYSTEM_ROOTS = ["/etc", "/private/etc", "/bin", "/sbin", "/usr", "/System", "/dev", "/proc", "/sys"];
646
+ function unsafeDefaultWorkerCwdReason(canonical) {
647
+ const normalized = path2.normalize(canonical);
648
+ const parsedRoot = path2.parse(normalized).root;
649
+ if (normalized === parsedRoot || /^[A-Za-z]:[\\/]?$/.test(normalized)) {
650
+ return "filesystem root cannot be used as a default worker working directory";
651
+ }
652
+ if (process.platform === "win32" || /^[A-Za-z]:[\\/]/.test(normalized)) {
653
+ const winNorm = normalized.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
654
+ const sysRoot = (process.env.SystemRoot || "C:\\Windows").replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
655
+ if (winNorm === sysRoot || winNorm.startsWith(`${sysRoot}/`)) {
656
+ return "Windows system directory cannot be used as a default worker working directory";
657
+ }
658
+ return void 0;
659
+ }
660
+ const posixNorm = normalized.replace(/\/+$/, "") || "/";
661
+ for (const sysRoot of POSIX_SYSTEM_ROOTS) {
662
+ if (posixNorm === sysRoot || posixNorm.startsWith(`${sysRoot}/`)) {
663
+ return `OS system directory (${sysRoot}) cannot be used as a default worker working directory`;
664
+ }
665
+ }
666
+ try {
667
+ const stat = fs2.statSync(canonical);
668
+ if ((stat.mode & 2) !== 0 && (stat.mode & 512) === 0) {
669
+ return "world-writable directory without sticky bit cannot be used as a default worker working directory";
670
+ }
671
+ } catch {
672
+ return "working directory cannot be inspected";
673
+ }
674
+ return void 0;
675
+ }
642
676
  function cwdAllowedOrThrow(cwd, allowOrRead) {
643
- const read = Array.isArray(allowOrRead) ? { config: { ...DEFAULT_CONFIG, allowCwd: allowOrRead } } : allowOrRead;
677
+ const read = allowOrRead === void 0 ? { config: { ...DEFAULT_CONFIG } } : Array.isArray(allowOrRead) ? { config: { ...DEFAULT_CONFIG, allowCwd: allowOrRead } } : allowOrRead;
644
678
  if (read.loadError) {
645
679
  throw new Error(
646
680
  `pie-proc policy at ${read.loadError.file} could not be loaded (${read.loadError.detail}); refusing to spawn. Run \`pie manager allow "${cwd}" --backup-corrupt\` to back up the broken file and authorize this root, or fix the JSON.`
647
681
  );
648
682
  }
649
683
  const canonical = canonicalDir(cwd);
684
+ if (read.config.allowCwd === void 0) {
685
+ const unsafeReason = unsafeDefaultWorkerCwdReason(canonical);
686
+ if (unsafeReason) {
687
+ throw new Error(
688
+ `cwd "${cwd}" (canonical ${canonical}) refused: ${unsafeReason}. Pick a project directory, or explicitly authorize it with \`pie manager allow "${cwd}" --force\`.`
689
+ );
690
+ }
691
+ return canonical;
692
+ }
650
693
  for (const root of read.config.allowCwd) {
651
694
  try {
652
695
  const canonicalRoot = canonicalDir(root);
@@ -667,7 +710,7 @@ function cwdAllowedOrThrow(cwd, allowOrRead) {
667
710
  return false;
668
711
  }
669
712
  }) ?? file;
670
- throw new Error(exists || effective !== file ? `cwd "${cwd}" (canonical ${canonical}) is outside the pie-proc allowCwd roots in ${effective}. Run \`pie manager allow "${cwd}"\` (or edit that file) \u2014 it is re-read on every spawn, so no host restart is needed` : `cwd "${cwd}" is outside the pie-proc allowCwd roots: there is no config yet at ${effective}. Run \`pie manager allow "${cwd}"\` (or create ${effective} with {"allowCwd": ["${cwd}"]}) \u2014 it is read on every spawn, so no host restart is needed`);
713
+ throw new Error(exists || effective !== file ? `cwd "${cwd}" (canonical ${canonical}) is outside the pie-proc allowCwd roots in ${effective}. Run \`pie manager allow "${cwd}"\` (or remove allowCwd from ${effective} for open-by-default mode) \u2014 it is re-read on every spawn, so no host restart is needed` : `cwd "${cwd}" is outside the pie-proc allowCwd roots. Run \`pie manager allow "${cwd}"\` \u2014 it is read on every spawn, so no host restart is needed`);
671
714
  }
672
715
 
673
716
  // builtin/extensions/pie-proc/spawn-model.ts
@@ -1861,7 +1904,7 @@ function pieProc(ctx) {
1861
1904
  const unregisterPanelBridge = registerPieProcPanelBridge({
1862
1905
  pieProcDir,
1863
1906
  operatorSessionsDir: resolveOperatorSessionsDir,
1864
- allowCwd: () => currentConfig().allowCwd,
1907
+ allowCwd: () => readConfigDetailed(),
1865
1908
  cwdAllowedOrThrow,
1866
1909
  safeName,
1867
1910
  readWorkers: () => readRegistryUncached().workers,
@@ -1888,11 +1931,11 @@ function pieProc(ctx) {
1888
1931
  ctx.registerTool({
1889
1932
  name: "pie_proc",
1890
1933
  label: "Pie worker processes",
1891
- description: "Controlled lifecycle for pie worker processes (manager plan): spawn creates a bounded-shape pie worker \u2014 either a RESIDENT host (--json-events --idle, peer-addressable by worker name via ipc_send_notify) or a ONE-SHOT run (pie -p <task>, process exit is the completion). cwd must resolve inside the allowCwd roots configured in ~/.pie/pie-proc.json (symlinks resolved). Optional idle TTL retires idle RESIDENTS automatically (identity-verified; activity-aware). imForward accepts identity fields ONLY \u2014 executable selection is operator config. kill stops a worker gracefully (SIGTERM, bounded identity-verified escalation) and removes its generation; list shows workers with pid/session/cwd/liveness/last-active. Never use raw shell to start pie processes \u2014 this tool owns the audit trail, caps, and cleanup.",
1934
+ description: "Controlled lifecycle for pie worker processes (manager plan): spawn creates a bounded-shape pie worker \u2014 either a RESIDENT host (--json-events --idle, peer-addressable by worker name via ipc_send_notify) or a ONE-SHOT run (pie -p <task>, process exit is the completion). Standard working directories work out of the box (filesystem/OS system roots are blocked); optional allowCwd in ~/.pie/pie-proc.json narrows allowed roots when configured (symlinks resolved). Optional idle TTL retires idle RESIDENTS automatically (identity-verified; activity-aware). imForward accepts identity fields ONLY \u2014 executable selection is operator config. kill stops a worker gracefully (SIGTERM, bounded identity-verified escalation) and removes its generation; list shows workers with pid/session/cwd/liveness/last-active. Never use raw shell to start pie processes \u2014 this tool owns the audit trail, caps, and cleanup.",
1892
1935
  parameters: Type.Object({
1893
1936
  action: Type.Union([Type.Literal("spawn"), Type.Literal("kill"), Type.Literal("list")], { description: "spawn | kill | list" }),
1894
1937
  name: Type.Optional(Type.String({ description: "Worker name ([a-z0-9-_], unique among alive workers)" })),
1895
- cwd: Type.Optional(Type.String({ description: "spawn: working directory (must resolve under an allowCwd root)" })),
1938
+ cwd: Type.Optional(Type.String({ description: "spawn: working directory (standard directories allowed by default; narrowed by optional allowCwd in pie-proc.json)" })),
1896
1939
  kind: Type.Optional(Type.Union([Type.Literal("resident"), Type.Literal("oneshot")], { description: "spawn: resident (default) or oneshot" })),
1897
1940
  task: Type.Optional(Type.String({ description: "oneshot: the task prompt (non-empty, must not start with '-')" })),
1898
1941
  model: Type.Optional(Type.String({ description: "spawn: optional per-worker model override as 'provider/modelId' (validated against models.json; overrides default/resumed model when set)" })),
@@ -5,7 +5,7 @@ import {
5
5
  createCliRetryPolicy,
6
6
  formatTransportLifecycle,
7
7
  logTransportLifecycle
8
- } from "../../../chunks/chunk-LIA52LJU.js";
8
+ } from "../../../chunks/chunk-TFBXCEMG.js";
9
9
  import {
10
10
  getConfigDir
11
11
  } from "../../../chunks/chunk-CBDQJMUI.js";
@@ -5,10 +5,255 @@ import {
5
5
 
6
6
  // src/commands/manager-upgrade-windows.ts
7
7
  import { spawnSync } from "node:child_process";
8
+ import { randomBytes as randomBytes2 } from "node:crypto";
9
+ import * as fs2 from "node:fs";
10
+ import * as os from "node:os";
11
+ import * as path2 from "node:path";
12
+
13
+ // src/commands/manager-upgrade-launcher-windows.ts
14
+ import { execFileSync } from "node:child_process";
8
15
  import { randomBytes } from "node:crypto";
9
16
  import * as fs from "node:fs";
10
- import * as os from "node:os";
11
17
  import * as path from "node:path";
18
+ var WINDOWS_UPGRADE_LAUNCHER_FILENAME = "upgrade-launcher.v1.exe";
19
+ function quoteWindowsCommandArg(arg) {
20
+ let out = '"';
21
+ let backslashes = 0;
22
+ for (const ch of arg) {
23
+ if (ch === "\\") {
24
+ backslashes++;
25
+ } else if (ch === '"') {
26
+ out += "\\".repeat(backslashes * 2 + 1) + '"';
27
+ backslashes = 0;
28
+ } else {
29
+ if (backslashes > 0) {
30
+ out += "\\".repeat(backslashes);
31
+ backslashes = 0;
32
+ }
33
+ out += ch;
34
+ }
35
+ }
36
+ if (backslashes > 0) out += "\\".repeat(backslashes * 2);
37
+ out += '"';
38
+ return out;
39
+ }
40
+ function buildWindowsUpgradeLauncherSource() {
41
+ return `// Generated by Pie. GUI-subsystem silent launcher for Windows upgrade tasks.
42
+ using System;
43
+ using System.ComponentModel;
44
+ using System.IO;
45
+ using System.Runtime.InteropServices;
46
+ using System.Text;
47
+
48
+ internal static class PieUpgradeLauncher {
49
+ [StructLayout(LayoutKind.Sequential)] struct SECURITY_ATTRIBUTES { public int Length; public IntPtr Descriptor; public int Inherit; }
50
+ [StructLayout(LayoutKind.Sequential)] struct STARTUPINFO {
51
+ public int Size; public string Reserved, Desktop, Title;
52
+ public int X, Y, XSize, YSize, XCountChars, YCountChars, FillAttribute, Flags;
53
+ public short ShowWindow, ReservedSize; public IntPtr Reserved2, Input, Output, Error;
54
+ }
55
+ [StructLayout(LayoutKind.Sequential)] struct PROCESS_INFORMATION { public IntPtr Process, Thread; public uint ProcessId, ThreadId; }
56
+ [StructLayout(LayoutKind.Sequential)] struct BASIC_LIMITS {
57
+ public long ProcessTime, JobTime; public uint Flags; public UIntPtr MinWorkingSet, MaxWorkingSet;
58
+ public uint ActiveProcesses; public UIntPtr Affinity; public uint PriorityClass, SchedulingClass;
59
+ }
60
+ [StructLayout(LayoutKind.Sequential)] struct IO_COUNTERS { public ulong ReadOps, WriteOps, OtherOps, ReadBytes, WriteBytes, OtherBytes; }
61
+ [StructLayout(LayoutKind.Sequential)] struct EXTENDED_LIMITS {
62
+ public BASIC_LIMITS Basic; public IO_COUNTERS Io; public UIntPtr ProcessMemory, JobMemory, PeakProcess, PeakJob;
63
+ }
64
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateJobObject(IntPtr attributes, string name);
65
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref EXTENDED_LIMITS info, uint length);
66
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
67
+ [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);
68
+ [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)] static extern IntPtr CreateFile(string name, uint access, uint share, ref SECURITY_ATTRIBUTES sa, uint disposition, uint flags, IntPtr template);
69
+ [DllImport("kernel32.dll", SetLastError=true)] static extern uint ResumeThread(IntPtr thread);
70
+ [DllImport("kernel32.dll", SetLastError=true)] static extern uint WaitForSingleObject(IntPtr handle, uint milliseconds);
71
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetExitCodeProcess(IntPtr process, out uint code);
72
+ [DllImport("kernel32.dll", SetLastError=true)] static extern bool TerminateProcess(IntPtr process, uint code);
73
+ [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle);
74
+
75
+ static void Check(bool ok) { if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error()); }
76
+ static void Close(IntPtr handle) { if (handle != IntPtr.Zero && handle != new IntPtr(-1)) CloseHandle(handle); }
77
+
78
+ static string QuoteArg(string arg) {
79
+ StringBuilder sb = new StringBuilder();
80
+ sb.Append('"');
81
+ int backslashes = 0;
82
+ for (int i = 0; i < arg.Length; i++) {
83
+ char c = arg[i];
84
+ if (c == '\\\\') {
85
+ backslashes++;
86
+ } else if (c == '"') {
87
+ sb.Append('\\\\', backslashes * 2 + 1);
88
+ sb.Append('"');
89
+ backslashes = 0;
90
+ } else {
91
+ if (backslashes > 0) {
92
+ sb.Append('\\\\', backslashes);
93
+ backslashes = 0;
94
+ }
95
+ sb.Append(c);
96
+ }
97
+ }
98
+ if (backslashes > 0) sb.Append('\\\\', backslashes * 2);
99
+ sb.Append('"');
100
+ return sb.ToString();
101
+ }
102
+
103
+ static void AppendLog(string logFile, string message) {
104
+ if (string.IsNullOrEmpty(logFile)) return;
105
+ try {
106
+ File.AppendAllText(logFile, "[pie-upgrade-launcher] " + DateTime.UtcNow.ToString("o") + " " + message + Environment.NewLine);
107
+ } catch {}
108
+ }
109
+
110
+ static int Main(string[] args) {
111
+ if (args == null || args.Length < 2 || string.IsNullOrEmpty(args[0]) || string.IsNullOrEmpty(args[1])) {
112
+ return 2;
113
+ }
114
+ string nodePath = args[0];
115
+ string bootstrapPath = args[1];
116
+ string logFile = args.Length >= 3 ? args[2] : "";
117
+ IntPtr job = IntPtr.Zero, input = IntPtr.Zero, output = IntPtr.Zero;
118
+ PROCESS_INFORMATION child = new PROCESS_INFORMATION();
119
+ bool assigned = false;
120
+ try {
121
+ job = CreateJobObject(IntPtr.Zero, null);
122
+ Check(job != IntPtr.Zero);
123
+ EXTENDED_LIMITS limits = new EXTENDED_LIMITS();
124
+ limits.Basic.Flags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
125
+ Check(SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(EXTENDED_LIMITS))));
126
+
127
+ SECURITY_ATTRIBUTES inherit = new SECURITY_ATTRIBUTES();
128
+ inherit.Length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
129
+ inherit.Inherit = 1;
130
+
131
+ input = CreateFile("NUL", 0x80000000, 7, ref inherit, 3, 0, IntPtr.Zero);
132
+ Check(input != new IntPtr(-1));
133
+
134
+ output = new IntPtr(-1);
135
+ if (!string.IsNullOrEmpty(logFile)) {
136
+ try {
137
+ string logDir = Path.GetDirectoryName(logFile);
138
+ if (!string.IsNullOrEmpty(logDir)) Directory.CreateDirectory(logDir);
139
+ } catch {}
140
+ output = CreateFile(logFile, 4, 7, ref inherit, 4, 0, IntPtr.Zero); // FILE_APPEND_DATA, OPEN_ALWAYS
141
+ }
142
+ if (output == new IntPtr(-1)) {
143
+ output = CreateFile("NUL", 0x40000000, 7, ref inherit, 3, 0, IntPtr.Zero);
144
+ Check(output != new IntPtr(-1));
145
+ }
146
+
147
+ STARTUPINFO startup = new STARTUPINFO();
148
+ startup.Size = Marshal.SizeOf(typeof(STARTUPINFO));
149
+ startup.Flags = 0x100; // STARTF_USESTDHANDLES
150
+ startup.Input = input;
151
+ startup.Output = output;
152
+ startup.Error = output;
153
+
154
+ string command = QuoteArg(nodePath) + " " + QuoteArg(bootstrapPath);
155
+ // CREATE_NO_WINDOW (0x08000000) | CREATE_SUSPENDED (0x00000004).
156
+ // Inherits Task Scheduler WorkingDirectory (lpCurrentDirectory = null)
157
+ // and creates a hidden console so child npm/cmd.exe processes stay silent.
158
+ Check(CreateProcess(nodePath, new StringBuilder(command), IntPtr.Zero, IntPtr.Zero, true, 0x08000004, IntPtr.Zero, null, ref startup, out child));
159
+ Check(AssignProcessToJobObject(job, child.Process));
160
+ assigned = true;
161
+ Check(ResumeThread(child.Thread) != UInt32.MaxValue);
162
+ Check(WaitForSingleObject(child.Process, UInt32.MaxValue) == 0);
163
+ uint code;
164
+ Check(GetExitCodeProcess(child.Process, out code));
165
+ return unchecked((int)code);
166
+ } catch (Exception error) {
167
+ AppendLog(logFile, error.ToString());
168
+ return 1;
169
+ } finally {
170
+ if (!assigned && child.Process != IntPtr.Zero) TerminateProcess(child.Process, 1);
171
+ Close(job);
172
+ Close(child.Thread);
173
+ Close(child.Process);
174
+ Close(input);
175
+ Close(output);
176
+ }
177
+ }
178
+ }
179
+ `;
180
+ }
181
+ function defaultFindWindowsDotNetCompiler() {
182
+ const systemRoot = process.env.SystemRoot || "C:\\Windows";
183
+ return ["Framework64", "Framework"].map((folder) => path.join(systemRoot, "Microsoft.NET", folder, "v4.0.30319", "csc.exe")).find((file) => fs.existsSync(file));
184
+ }
185
+ function isNonEmptyFile(filePath) {
186
+ try {
187
+ const st = fs.statSync(filePath);
188
+ return st.isFile() && st.size > 0;
189
+ } catch {
190
+ return false;
191
+ }
192
+ }
193
+ function ensureWindowsUpgradeLauncher(managerDir, deps = {}) {
194
+ const launcherPath = path.join(managerDir, WINDOWS_UPGRADE_LAUNCHER_FILENAME);
195
+ if (isNonEmptyFile(launcherPath)) {
196
+ return { ok: true, launcherPath, compiled: false };
197
+ }
198
+ const findCompiler = deps.findCompiler ?? defaultFindWindowsDotNetCompiler;
199
+ const compiler = findCompiler();
200
+ if (!compiler) {
201
+ return {
202
+ ok: false,
203
+ detail: "Windows .NET Framework compiler (csc.exe) is unavailable; refusing to launch a visible console upgrade task."
204
+ };
205
+ }
206
+ const compile = deps.compile ?? ((bin, args) => {
207
+ execFileSync(bin, args, {
208
+ windowsHide: true,
209
+ stdio: ["ignore", "pipe", "pipe"],
210
+ timeout: 3e4
211
+ });
212
+ });
213
+ const nonce = `${process.pid}.${randomBytes(4).toString("hex")}`;
214
+ const tmpSrc = path.join(managerDir, `upgrade-launcher.${nonce}.cs`);
215
+ const tmpExe = path.join(managerDir, `upgrade-launcher.${nonce}.exe`);
216
+ try {
217
+ fs.mkdirSync(managerDir, { recursive: true });
218
+ fs.writeFileSync(tmpSrc, buildWindowsUpgradeLauncherSource(), { encoding: "utf8", mode: 384 });
219
+ compile(compiler, [
220
+ "/nologo",
221
+ "/target:winexe",
222
+ "/platform:anycpu",
223
+ "/optimize+",
224
+ `/out:${tmpExe}`,
225
+ tmpSrc
226
+ ]);
227
+ if (!isNonEmptyFile(tmpExe)) {
228
+ return { ok: false, detail: `csc.exe produced no output binary at ${tmpExe}` };
229
+ }
230
+ try {
231
+ fs.renameSync(tmpExe, launcherPath);
232
+ } catch (renameError) {
233
+ if (isNonEmptyFile(launcherPath)) {
234
+ return { ok: true, launcherPath, compiled: false };
235
+ }
236
+ throw renameError;
237
+ }
238
+ return { ok: true, launcherPath, compiled: true };
239
+ } catch (error) {
240
+ return {
241
+ ok: false,
242
+ detail: `failed to compile Windows silent upgrade launcher: ${error instanceof Error ? error.message : String(error)}`
243
+ };
244
+ } finally {
245
+ try {
246
+ fs.rmSync(tmpSrc, { force: true });
247
+ } catch {
248
+ }
249
+ try {
250
+ fs.rmSync(tmpExe, { force: true });
251
+ } catch {
252
+ }
253
+ }
254
+ }
255
+
256
+ // src/commands/manager-upgrade-windows.ts
12
257
  var WINDOWS_UPGRADE_TASK_NAME = "dev.pie.manager.upgrade";
13
258
  function normalizePreInstallStopOutcome(raw) {
14
259
  return typeof raw === "string" ? { status: raw } : raw;
@@ -23,12 +268,12 @@ function resolveDefaultTuiUsePidFile(env = process.env) {
23
268
  const expandHome = (value) => {
24
269
  if (value === "~") return os.homedir();
25
270
  if (value.startsWith("~/") || value.startsWith("~\\")) {
26
- return path.join(os.homedir(), value.slice(2).replace(/\\/g, "/"));
271
+ return path2.join(os.homedir(), value.slice(2).replace(/\\/g, "/"));
27
272
  }
28
273
  return value;
29
274
  };
30
- const stateDir = env.PIE_TUI_USE_STATE_DIR ? path.resolve(expandHome(env.PIE_TUI_USE_STATE_DIR)) : path.resolve(path.join(env.PIE_CODING_AGENT_DIR ? expandHome(env.PIE_CODING_AGENT_DIR) : path.join(os.homedir(), ".pie"), "tui-use"));
31
- return path.join(stateDir, "daemon.pid");
275
+ const stateDir = env.PIE_TUI_USE_STATE_DIR ? path2.resolve(expandHome(env.PIE_TUI_USE_STATE_DIR)) : path2.resolve(path2.join(env.PIE_CODING_AGENT_DIR ? expandHome(env.PIE_CODING_AGENT_DIR) : path2.join(os.homedir(), ".pie"), "tui-use"));
276
+ return path2.join(stateDir, "daemon.pid");
32
277
  }
33
278
  function scanBlockingWindowsPeers(discoveryDir, managerSessionId, managerPid, opts = {}) {
34
279
  const selfPid = opts.selfPid ?? process.pid;
@@ -45,14 +290,14 @@ function scanBlockingWindowsPeers(discoveryDir, managerSessionId, managerPid, op
45
290
  const seenPids = /* @__PURE__ */ new Set();
46
291
  let files = [];
47
292
  try {
48
- files = fs.readdirSync(discoveryDir).filter((f) => f.endsWith(".json"));
293
+ files = fs2.readdirSync(discoveryDir).filter((f) => f.endsWith(".json"));
49
294
  } catch {
50
295
  files = [];
51
296
  }
52
297
  for (const file of files.slice(0, 256)) {
53
298
  let parsed;
54
299
  try {
55
- const raw = JSON.parse(fs.readFileSync(path.join(discoveryDir, file), "utf8"));
300
+ const raw = JSON.parse(fs2.readFileSync(path2.join(discoveryDir, file), "utf8"));
56
301
  if (raw === null || typeof raw !== "object" || Array.isArray(raw)) continue;
57
302
  parsed = raw;
58
303
  } catch {
@@ -81,7 +326,7 @@ function scanBlockingWindowsPeers(discoveryDir, managerSessionId, managerPid, op
81
326
  }
82
327
  if (opts.tuiUsePidFile) {
83
328
  try {
84
- const rawPid = fs.readFileSync(opts.tuiUsePidFile, "utf8").trim();
329
+ const rawPid = fs2.readFileSync(opts.tuiUsePidFile, "utf8").trim();
85
330
  const daemonPid = Number.parseInt(rawPid, 10);
86
331
  if (Number.isInteger(daemonPid) && daemonPid > 0 && daemonPid !== selfPid && !seenPids.has(daemonPid) && isPidAlive(daemonPid) && cmdlineStillLooksLikePie(readCmdline(daemonPid))) {
87
332
  seenPids.add(daemonPid);
@@ -381,7 +626,7 @@ function runWindowsPreInstallStop(state, deps) {
381
626
  }
382
627
  function isWindowsServiceManager(configRoot) {
383
628
  try {
384
- const raw = JSON.parse(fs.readFileSync(path.join(configRoot, "manager", "manager.json"), "utf8"));
629
+ const raw = JSON.parse(fs2.readFileSync(path2.join(configRoot, "manager", "manager.json"), "utf8"));
385
630
  return raw.service === true;
386
631
  } catch {
387
632
  return false;
@@ -403,9 +648,9 @@ function resolveAbsoluteActorEnv(env, cwd = process.cwd()) {
403
648
  const trimmed = raw.trim();
404
649
  if (trimmed === "~" || trimmed.startsWith("~/") || trimmed.startsWith("~\\")) continue;
405
650
  if (key === "PIE_IPC_CONFIG_DIR" && trimmed.length === 0) {
406
- out[key] = path.resolve(cwd);
407
- } else if (trimmed.length > 0 && !path.isAbsolute(trimmed)) {
408
- out[key] = path.resolve(cwd, trimmed);
651
+ out[key] = path2.resolve(cwd);
652
+ } else if (trimmed.length > 0 && !path2.isAbsolute(trimmed)) {
653
+ out[key] = path2.resolve(cwd, trimmed);
409
654
  }
410
655
  }
411
656
  return out;
@@ -424,7 +669,12 @@ function xmlEscapeText(value) {
424
669
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
425
670
  }
426
671
  function buildWindowsUpgradeTaskXml(params) {
427
- const args = `"${params.bootstrapPath.replace(/"/g, '\\"')}"`;
672
+ const argv = [
673
+ params.nodePath,
674
+ params.bootstrapPath,
675
+ ...params.logFile ? [params.logFile] : []
676
+ ];
677
+ const args = argv.map(quoteWindowsCommandArg).join(" ");
428
678
  return [
429
679
  '<?xml version="1.0" encoding="UTF-16"?>',
430
680
  '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
@@ -459,7 +709,7 @@ function buildWindowsUpgradeTaskXml(params) {
459
709
  " </Settings>",
460
710
  ' <Actions Context="Author">',
461
711
  " <Exec>",
462
- ` <Command>${xmlEscapeText(params.nodePath)}</Command>`,
712
+ ` <Command>${xmlEscapeText(params.launcherPath)}</Command>`,
463
713
  ` <Arguments>${xmlEscapeText(args)}</Arguments>`,
464
714
  ` <WorkingDirectory>${xmlEscapeText(params.workingDir)}</WorkingDirectory>`,
465
715
  " </Exec>",
@@ -512,13 +762,13 @@ function buildWindowsUpgradeBootstrapScript(cfg) {
512
762
  function sweepStaleUpgradeBootstrapFiles(managerDir, nowMs = Date.now()) {
513
763
  const MAX_AGE_MS = 30 * 6e4;
514
764
  try {
515
- for (const name of fs.readdirSync(managerDir)) {
765
+ for (const name of fs2.readdirSync(managerDir)) {
516
766
  if (!/^upgrade-actor-[\w-]+\.(?:mjs|xml)$/.test(name)) continue;
517
- const full = path.join(managerDir, name);
767
+ const full = path2.join(managerDir, name);
518
768
  try {
519
- const st = fs.statSync(full);
769
+ const st = fs2.statSync(full);
520
770
  if (nowMs - st.mtimeMs > MAX_AGE_MS) {
521
- fs.rmSync(full, { force: true });
771
+ fs2.rmSync(full, { force: true });
522
772
  }
523
773
  } catch {
524
774
  }
@@ -529,19 +779,19 @@ function sweepStaleUpgradeBootstrapFiles(managerDir, nowMs = Date.now()) {
529
779
  function launchWindowsServiceUpgradeActor(params, runSchtasks = (args) => {
530
780
  const res = spawnSync("schtasks", args, { encoding: "utf8", timeout: 2e4, windowsHide: true });
531
781
  return { status: res.status, stdout: res.stdout, stderr: res.stderr, error: res.error };
532
- }) {
533
- const launchId = params.launchId ?? `${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`;
782
+ }, ensureLauncher = (dir) => ensureWindowsUpgradeLauncher(dir)) {
783
+ const launchId = params.launchId ?? `${Date.now().toString(36)}-${randomBytes2(4).toString("hex")}`;
534
784
  const taskName = params.taskName ?? `${WINDOWS_UPGRADE_TASK_NAME}.${launchId}`;
535
785
  const workingDir = params.workingDir ?? os.tmpdir();
536
- const bootstrapPath = path.join(params.managerDir, `upgrade-actor-${launchId}.mjs`);
537
- const xmlPath = path.join(params.managerDir, `upgrade-actor-${launchId}.xml`);
786
+ const bootstrapPath = path2.join(params.managerDir, `upgrade-actor-${launchId}.mjs`);
787
+ const xmlPath = path2.join(params.managerDir, `upgrade-actor-${launchId}.xml`);
538
788
  const cleanup = (deleteTask) => {
539
789
  try {
540
- fs.rmSync(xmlPath, { force: true });
790
+ fs2.rmSync(xmlPath, { force: true });
541
791
  } catch {
542
792
  }
543
793
  try {
544
- fs.rmSync(bootstrapPath, { force: true });
794
+ fs2.rmSync(bootstrapPath, { force: true });
545
795
  } catch {
546
796
  }
547
797
  if (deleteTask) {
@@ -552,8 +802,12 @@ function launchWindowsServiceUpgradeActor(params, runSchtasks = (args) => {
552
802
  }
553
803
  };
554
804
  try {
555
- fs.mkdirSync(params.managerDir, { recursive: true });
805
+ fs2.mkdirSync(params.managerDir, { recursive: true });
556
806
  sweepStaleUpgradeBootstrapFiles(params.managerDir);
807
+ const launcher = ensureLauncher(params.managerDir);
808
+ if (!launcher.ok) {
809
+ return { ok: false, detail: launcher.detail };
810
+ }
557
811
  const script = buildWindowsUpgradeBootstrapScript({
558
812
  node: params.nodePath,
559
813
  entry: params.entry,
@@ -564,10 +818,16 @@ function launchWindowsServiceUpgradeActor(params, runSchtasks = (args) => {
564
818
  workingDir,
565
819
  env: collectWindowsUpgradeEnv(params.env)
566
820
  });
567
- fs.writeFileSync(bootstrapPath, script, { encoding: "utf8", mode: 384 });
568
- const xml = buildWindowsUpgradeTaskXml({ nodePath: params.nodePath, bootstrapPath, workingDir });
821
+ fs2.writeFileSync(bootstrapPath, script, { encoding: "utf8", mode: 384 });
822
+ const xml = buildWindowsUpgradeTaskXml({
823
+ launcherPath: launcher.launcherPath,
824
+ nodePath: params.nodePath,
825
+ bootstrapPath,
826
+ logFile: params.logFile,
827
+ workingDir
828
+ });
569
829
  const xmlBytes = Buffer.concat([Buffer.from([255, 254]), Buffer.from(xml, "utf16le")]);
570
- fs.writeFileSync(xmlPath, xmlBytes, { mode: 384 });
830
+ fs2.writeFileSync(xmlPath, xmlBytes, { mode: 384 });
571
831
  const created = runSchtasks(["/Create", "/TN", taskName, "/XML", xmlPath, "/F"]);
572
832
  if (created.error || created.status !== 0) {
573
833
  cleanup(false);
@@ -585,7 +845,8 @@ function launchWindowsServiceUpgradeActor(params, runSchtasks = (args) => {
585
845
  detail: `scheduled task ${taskName} \xB7 log ${params.logFile}`,
586
846
  taskName,
587
847
  bootstrapPath,
588
- xmlPath
848
+ xmlPath,
849
+ launcherPath: launcher.launcherPath
589
850
  };
590
851
  } catch (error) {
591
852
  cleanup(false);
@@ -594,6 +855,7 @@ function launchWindowsServiceUpgradeActor(params, runSchtasks = (args) => {
594
855
  }
595
856
 
596
857
  export {
858
+ ensureWindowsUpgradeLauncher,
597
859
  normalizePreInstallStopOutcome,
598
860
  resolveDefaultTuiUsePidFile,
599
861
  scanBlockingWindowsPeers,