@cydm/pie 4.10.0 → 4.10.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,4 +1,9 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ isWindowsServiceManager,
4
+ launchWindowsServiceUpgradeActor,
5
+ resolveAbsoluteActorEnv
6
+ } from "../../../chunks/chunk-BB7ETSJK.js";
2
7
  import {
3
8
  DISPATCH_PREFIX,
4
9
  IPC_PROTOCOL_VERSION,
@@ -3583,6 +3588,7 @@ ${a.runs} \u6B21 \xB7 \u6700\u8FD1 ${cleanInline2(a.lastRunBy ?? "\u2014", 20)}
3583
3588
 
3584
3589
  // builtin/extensions/im-forward/runtime-panel-lifecycle.ts
3585
3590
  import * as fs11 from "node:fs";
3591
+ import * as os6 from "node:os";
3586
3592
  import { dirname as pathDirname, join as join13, resolve as pathResolve2 } from "node:path";
3587
3593
  import { spawn as spawnProcess } from "node:child_process";
3588
3594
 
@@ -4596,48 +4602,62 @@ async function runUpgradeConfirmActor(cols, log) {
4596
4602
  const entry = process.argv[1] ? pathResolve2(process.argv[1]) : "";
4597
4603
  if (!entry) throw new Error("cannot resolve the pie entry point");
4598
4604
  const configRoot = pathDirname(pathDirname(ipcDiscoveryRoot()));
4599
- const logFile = join13(configRoot, "manager", "upgrade-actor.log");
4600
- let out;
4601
- try {
4602
- fs11.mkdirSync(pathDirname(logFile), { recursive: true });
4603
- out = fs11.openSync(logFile, "a");
4604
- } catch {
4605
- out = void 0;
4606
- }
4607
- const child = spawnProcess(process.execPath, [entry, "manager", "upgrade"], {
4608
- cwd: process.cwd(),
4609
- detached: true,
4610
- stdio: out !== void 0 ? ["ignore", out, out] : "ignore",
4611
- windowsHide: true,
4612
- env: process.env
4613
- });
4614
- const spawnOutcome = await new Promise((resolve7) => {
4615
- let settled = false;
4616
- const settle = (v) => {
4617
- if (!settled) {
4618
- settled = true;
4619
- resolve7(v);
4620
- }
4621
- };
4622
- child.once("spawn", () => settle("spawned"));
4623
- child.once("error", (error) => {
4624
- log(`im-forward: upgrade actor spawn error: ${error instanceof Error ? error.message : String(error)}`);
4625
- settle("error");
4605
+ const managerDir = join13(configRoot, "manager");
4606
+ const logFile = join13(managerDir, "upgrade-actor.log");
4607
+ const actorEnv = resolveAbsoluteActorEnv(process.env);
4608
+ if (process.platform === "win32" && isWindowsServiceManager(configRoot)) {
4609
+ const launched = launchWindowsServiceUpgradeActor({
4610
+ managerDir,
4611
+ nodePath: process.execPath,
4612
+ entry,
4613
+ logFile,
4614
+ env: actorEnv
4626
4615
  });
4627
- setTimeout(() => settle("timeout"), 3e3).unref?.();
4628
- });
4629
- child.unref();
4630
- if (out !== void 0) {
4616
+ actorOk = launched.ok;
4617
+ actorDetail = launched.detail;
4618
+ } else {
4619
+ let out;
4631
4620
  try {
4632
- fs11.closeSync(out);
4621
+ fs11.mkdirSync(managerDir, { recursive: true });
4622
+ out = fs11.openSync(logFile, "a");
4633
4623
  } catch {
4624
+ out = void 0;
4625
+ }
4626
+ const child = spawnProcess(process.execPath, [entry, "manager", "upgrade"], {
4627
+ cwd: os6.tmpdir(),
4628
+ detached: true,
4629
+ stdio: out !== void 0 ? ["ignore", out, out] : "ignore",
4630
+ windowsHide: true,
4631
+ env: actorEnv
4632
+ });
4633
+ const spawnOutcome = await new Promise((resolve7) => {
4634
+ let settled = false;
4635
+ const settle = (v) => {
4636
+ if (!settled) {
4637
+ settled = true;
4638
+ resolve7(v);
4639
+ }
4640
+ };
4641
+ child.once("spawn", () => settle("spawned"));
4642
+ child.once("error", (error) => {
4643
+ log(`im-forward: upgrade actor spawn error: ${error instanceof Error ? error.message : String(error)}`);
4644
+ settle("error");
4645
+ });
4646
+ setTimeout(() => settle("timeout"), 3e3).unref?.();
4647
+ });
4648
+ child.unref();
4649
+ if (out !== void 0) {
4650
+ try {
4651
+ fs11.closeSync(out);
4652
+ } catch {
4653
+ }
4654
+ }
4655
+ if (spawnOutcome === "error") {
4656
+ actorDetail = "the actor process failed to spawn (see the manager log)";
4657
+ } else {
4658
+ actorOk = true;
4659
+ actorDetail = `actor pid ${child.pid}${spawnOutcome === "timeout" ? " (spawn unconfirmed \u2014 will report via /panel)" : ""} \xB7 log ${logFile}`;
4634
4660
  }
4635
- }
4636
- if (spawnOutcome === "error") {
4637
- actorDetail = "the actor process failed to spawn (see the manager log)";
4638
- } else {
4639
- actorOk = true;
4640
- actorDetail = `actor pid ${child.pid}${spawnOutcome === "timeout" ? " (spawn unconfirmed \u2014 will report via /panel)" : ""} \xB7 log ${logFile}`;
4641
4661
  }
4642
4662
  } catch (error) {
4643
4663
  actorDetail = error instanceof Error ? error.message : String(error);
@@ -7377,7 +7397,7 @@ async function settingsProbeBinary() {
7377
7397
  import { spawn as spawn5 } from "node:child_process";
7378
7398
  import { createHash as createHash2 } from "node:crypto";
7379
7399
  import * as fs15 from "node:fs";
7380
- import * as os6 from "node:os";
7400
+ import * as os7 from "node:os";
7381
7401
  import * as path16 from "node:path";
7382
7402
 
7383
7403
  // builtin/extensions/im-forward/providers/feishu/card.ts
@@ -8296,7 +8316,7 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
8296
8316
  return Array.isArray(data?.messages) ? data.messages.flatMap((message) => isRecord(message) && typeof message.message_id === "string" ? [message.message_id] : []) : null;
8297
8317
  },
8298
8318
  async downloadImage(messageId, image, index) {
8299
- const directory = fs15.mkdtempSync(path16.join(os6.tmpdir(), "pie-im-forward-"));
8319
+ const directory = fs15.mkdtempSync(path16.join(os7.tmpdir(), "pie-im-forward-"));
8300
8320
  const cleanup = () => fs15.rmSync(directory, { recursive: true, force: true });
8301
8321
  try {
8302
8322
  const name = `image-${index + 1}.png`;
@@ -8487,7 +8507,7 @@ function connect(binary, profile, targetKind = "chat", settings = { targetId: ""
8487
8507
  async consumeBusHealth() {
8488
8508
  const appId = await canonicalAppIdNow();
8489
8509
  if (!appId) return void 0;
8490
- const larkHome = process.env.PIE_LARK_CLI_HOME && process.env.PIE_LARK_CLI_HOME.trim() ? process.env.PIE_LARK_CLI_HOME : os6.homedir();
8510
+ const larkHome = process.env.PIE_LARK_CLI_HOME && process.env.PIE_LARK_CLI_HOME.trim() ? process.env.PIE_LARK_CLI_HOME : os7.homedir();
8491
8511
  const logPath = path16.join(larkHome, ".lark-cli", "events", appId, "bus.log");
8492
8512
  let tail;
8493
8513
  try {
@@ -0,0 +1,463 @@
1
+ import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ readProcessCommandLine
4
+ } from "./chunk-7RJXKN7N.js";
5
+
6
+ // src/commands/manager-upgrade-windows.ts
7
+ import { spawnSync } from "node:child_process";
8
+ import { randomBytes } from "node:crypto";
9
+ import * as fs from "node:fs";
10
+ import * as os from "node:os";
11
+ import * as path from "node:path";
12
+ var WINDOWS_UPGRADE_TASK_NAME = "dev.pie.manager.upgrade";
13
+ function normalizePreInstallStopOutcome(raw) {
14
+ return typeof raw === "string" ? { status: raw } : raw;
15
+ }
16
+ function cmdlineStillLooksLikePie(cmdline) {
17
+ if (cmdline === void 0) return true;
18
+ const trimmed = cmdline.trim();
19
+ if (!trimmed) return false;
20
+ return /(?:^|[\s\\/"'])(?:node(?:\.exe)?|pie(?:\.cmd|\.exe)?|cli\.(?:m?js|ts))(?:[\s"']|$)/i.test(trimmed) || /@cydm[\\/]pie/i.test(trimmed);
21
+ }
22
+ function resolveDefaultTuiUsePidFile(env = process.env) {
23
+ const expandHome = (value) => {
24
+ if (value === "~") return os.homedir();
25
+ if (value.startsWith("~/") || value.startsWith("~\\")) {
26
+ return path.join(os.homedir(), value.slice(2).replace(/\\/g, "/"));
27
+ }
28
+ return value;
29
+ };
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");
32
+ }
33
+ function scanBlockingWindowsPeers(discoveryDir, managerSessionId, managerPid, opts = {}) {
34
+ const selfPid = opts.selfPid ?? process.pid;
35
+ const isPidAlive = opts.isPidAlive ?? ((pid) => {
36
+ try {
37
+ process.kill(pid, 0);
38
+ return true;
39
+ } catch (error) {
40
+ return error.code !== "ESRCH";
41
+ }
42
+ });
43
+ const readCmdline = opts.readCmdline ?? readProcessCommandLine;
44
+ const out = [];
45
+ const seenPids = /* @__PURE__ */ new Set();
46
+ let files = [];
47
+ try {
48
+ files = fs.readdirSync(discoveryDir).filter((f) => f.endsWith(".json"));
49
+ } catch {
50
+ files = [];
51
+ }
52
+ for (const file of files.slice(0, 256)) {
53
+ let parsed;
54
+ try {
55
+ const raw = JSON.parse(fs.readFileSync(path.join(discoveryDir, file), "utf8"));
56
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw)) continue;
57
+ parsed = raw;
58
+ } catch {
59
+ continue;
60
+ }
61
+ const pid = parsed.pid;
62
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) continue;
63
+ if (pid === selfPid || seenPids.has(pid)) continue;
64
+ if (managerPid !== void 0 && pid === managerPid) continue;
65
+ const isManager = parsed.isManager === true;
66
+ const peerSessionId = typeof parsed.sessionId === "string" ? parsed.sessionId : void 0;
67
+ if (isManager && (managerSessionId === void 0 || peerSessionId === managerSessionId)) {
68
+ continue;
69
+ }
70
+ const unattended = parsed.unattended === true;
71
+ const state = typeof parsed.state === "string" ? parsed.state : "unknown";
72
+ if (unattended && !isManager && state === "idle") {
73
+ continue;
74
+ }
75
+ if (!isPidAlive(pid)) continue;
76
+ if (!cmdlineStillLooksLikePie(readCmdline(pid))) continue;
77
+ seenPids.add(pid);
78
+ const name = typeof parsed.displayName === "string" && parsed.displayName.trim() ? parsed.displayName.trim() : String(pid);
79
+ const kind = isManager ? "other-manager" : unattended ? "busy-worker" : "interactive";
80
+ out.push({ pid, name, kind, state });
81
+ }
82
+ if (opts.tuiUsePidFile) {
83
+ try {
84
+ const rawPid = fs.readFileSync(opts.tuiUsePidFile, "utf8").trim();
85
+ const daemonPid = Number.parseInt(rawPid, 10);
86
+ if (Number.isInteger(daemonPid) && daemonPid > 0 && daemonPid !== selfPid && !seenPids.has(daemonPid) && isPidAlive(daemonPid) && cmdlineStillLooksLikePie(readCmdline(daemonPid))) {
87
+ seenPids.add(daemonPid);
88
+ out.push({ pid: daemonPid, name: "tui-use", kind: "tui-use-daemon", state: "running" });
89
+ }
90
+ } catch {
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+ function formatBlockingWindowsPeers(peers) {
96
+ return peers.map((p) => {
97
+ const label = p.kind === "interactive" ? "interactive TUI" : p.kind === "other-manager" ? "other manager" : p.kind === "tui-use-daemon" ? "tui-use daemon (node-pty)" : `busy worker (${p.state})`;
98
+ return `${label} "${p.name}" (pid ${p.pid})`;
99
+ }).join(", ");
100
+ }
101
+ function isWindowsTaskAlreadyStoppedDetail(detail) {
102
+ return /not currently running|not running|cannot find|does not exist|not found|当前未运行|尚未运行|没有正在运行|找不到指定的文件|系统找不到/i.test(detail);
103
+ }
104
+ function runWindowsPreInstallStop(state, deps) {
105
+ const checkBlockers = () => {
106
+ const blockers = deps.scanBlockingPeers(state);
107
+ if (blockers.length > 0) {
108
+ return {
109
+ status: "refused",
110
+ detail: `refused: other Pie processes still hold Windows native DLL locks (koffi.node/node-pty): ${formatBlockingWindowsPeers(blockers)}. Close them and retry.`
111
+ };
112
+ }
113
+ return void 0;
114
+ };
115
+ const initialRefusal = checkBlockers();
116
+ if (initialRefusal) return initialRefusal;
117
+ let touched = false;
118
+ const MAX_WORKER_PASSES = 2;
119
+ const clearedPids = /* @__PURE__ */ new Set();
120
+ for (let pass = 0; pass < MAX_WORKER_PASSES; pass++) {
121
+ const idleWorkers = deps.scanIdleWorkers().filter((w) => !clearedPids.has(w.pid));
122
+ if (idleWorkers.length === 0) break;
123
+ const retiredWorkers = [];
124
+ for (const peer of idleWorkers) {
125
+ const outcome = deps.retireWorkerIfStillIdle(peer);
126
+ if (outcome === "busy") {
127
+ return {
128
+ status: "refused",
129
+ detail: `refused: worker "${peer.name}" (pid ${peer.pid}) became busy before install; close or wait for it and retry.`
130
+ };
131
+ }
132
+ if (outcome === "unknown" || outcome === "failed") {
133
+ return {
134
+ status: "refused",
135
+ detail: `refused: could not safely retire idle worker "${peer.name}" (pid ${peer.pid}) (${outcome}); it may still hold Windows native DLL locks. Stop it manually and retry.`
136
+ };
137
+ }
138
+ if (outcome === "gone" && deps.isPidAlive?.(peer.pid) === true) {
139
+ return {
140
+ status: "refused",
141
+ detail: `refused: worker "${peer.name}" (pid ${peer.pid}) vanished from discovery but its PID is still alive and may hold Windows native DLL locks; stop it manually and retry.`
142
+ };
143
+ }
144
+ if (outcome === "retired") {
145
+ touched = true;
146
+ clearedPids.add(peer.pid);
147
+ retiredWorkers.push(peer);
148
+ deps.log(`windows pre-install: retired idle worker pid ${peer.pid} (${peer.name})`);
149
+ } else {
150
+ clearedPids.add(peer.pid);
151
+ }
152
+ }
153
+ for (const peer of retiredWorkers) {
154
+ if (!deps.waitExit(peer.pid, 2e4)) {
155
+ return {
156
+ status: "refused",
157
+ detail: `refused: idle worker "${peer.name}" (pid ${peer.pid}) did not exit within 20s and still holds Windows native DLL locks; stop it manually and retry.`
158
+ };
159
+ }
160
+ }
161
+ const midRefusal = checkBlockers();
162
+ if (midRefusal) return midRefusal;
163
+ if (retiredWorkers.length === 0) break;
164
+ if (pass === MAX_WORKER_PASSES - 1 && deps.scanIdleWorkers().some((w) => !clearedPids.has(w.pid))) {
165
+ return {
166
+ status: "refused",
167
+ detail: "refused: new idle workers continued spawning during Windows pre-install stop; retry when the manager is quiet."
168
+ };
169
+ }
170
+ }
171
+ const preStopRefusal = checkBlockers();
172
+ if (preStopRefusal) return preStopRefusal;
173
+ if (state.service === true) {
174
+ const liveBefore = deps.findManagerResident(state.sessionId);
175
+ const fallbackPid = liveBefore === void 0 && typeof state.pid === "number" && state.pid > 0 && deps.residentStatus(state) === "alive" ? state.pid : void 0;
176
+ const targetPid = liveBefore?.pid ?? fallbackPid;
177
+ const end = deps.endServiceTask();
178
+ if (end.spawnError) {
179
+ return {
180
+ status: "refused",
181
+ detail: `refused: schtasks /End failed before install (${end.spawnError}); check pie manager status and retry.`
182
+ };
183
+ }
184
+ if (targetPid !== void 0) {
185
+ if (!deps.waitExit(targetPid, 2e4)) {
186
+ return {
187
+ status: "refused",
188
+ detail: `refused: manager service resident pid ${targetPid} did not exit within 20s after schtasks /End${end.detail ? ` (${end.detail})` : ""}; native DLL locks are still held.`
189
+ };
190
+ }
191
+ touched = true;
192
+ deps.log(`windows pre-install: service resident pid ${targetPid} exited`);
193
+ } else if (end.status === 0) {
194
+ touched = true;
195
+ } else if (!isWindowsTaskAlreadyStoppedDetail(end.detail)) {
196
+ return {
197
+ status: "refused",
198
+ detail: `refused: schtasks /End failed before install (exit ${end.status ?? "null"}${end.detail ? `: ${end.detail}` : ""}); cannot confirm manager service is stopped.`
199
+ };
200
+ }
201
+ } else {
202
+ const status = deps.residentStatus(state);
203
+ if (status === "foreign" || status === "unknown") {
204
+ return {
205
+ status: "refused",
206
+ detail: `refused: recorded manager resident identity is ${status}; cannot safely release Windows DLL locks. Check pie manager status and retry.`
207
+ };
208
+ }
209
+ if (status === "alive") {
210
+ const targetPid = typeof state.pid === "number" && state.pid > 0 ? state.pid : deps.findManagerResident(state.sessionId)?.pid;
211
+ const stopped = deps.terminateResident(state);
212
+ if (stopped !== "terminated" && stopped !== "dead") {
213
+ return {
214
+ status: "refused",
215
+ detail: `refused: could not stop manager resident before install (${stopped}); check pie manager status and retry.`
216
+ };
217
+ }
218
+ if (stopped === "terminated") {
219
+ if (targetPid === void 0) {
220
+ return {
221
+ status: "refused",
222
+ detail: "refused: terminated manager resident but could not resolve its pid to verify exit before install."
223
+ };
224
+ }
225
+ if (!deps.waitExit(targetPid, 2e4)) {
226
+ return {
227
+ status: "refused",
228
+ detail: `refused: manager resident pid ${targetPid} did not exit within 20s; native DLL locks are still held.`
229
+ };
230
+ }
231
+ touched = true;
232
+ deps.log(`windows pre-install: manual resident pid ${targetPid} exited`);
233
+ }
234
+ }
235
+ }
236
+ if (touched) {
237
+ deps.settleAfterStop?.();
238
+ }
239
+ return { status: touched ? "stopped" : "unnecessary" };
240
+ }
241
+ function isWindowsServiceManager(configRoot) {
242
+ try {
243
+ const raw = JSON.parse(fs.readFileSync(path.join(configRoot, "manager", "manager.json"), "utf8"));
244
+ return raw.service === true;
245
+ } catch {
246
+ return false;
247
+ }
248
+ }
249
+ var SAFE_UPGRADE_ENV_KEYS = /* @__PURE__ */ new Set([
250
+ "PATH",
251
+ "PIE_IPC_CONFIG_DIR",
252
+ "PIE_CODING_AGENT_DIR",
253
+ "PIE_TUI_USE_STATE_DIR",
254
+ "NPM_CONFIG_REGISTRY",
255
+ "NPM_CONFIG_PREFIX"
256
+ ]);
257
+ function resolveAbsoluteActorEnv(env, cwd = process.cwd()) {
258
+ const out = { ...env };
259
+ for (const key of ["PIE_IPC_CONFIG_DIR", "PIE_CODING_AGENT_DIR", "PIE_TUI_USE_STATE_DIR"]) {
260
+ const raw = out[key];
261
+ if (typeof raw !== "string") continue;
262
+ const trimmed = raw.trim();
263
+ if (trimmed === "~" || trimmed.startsWith("~/") || trimmed.startsWith("~\\")) continue;
264
+ if (key === "PIE_IPC_CONFIG_DIR" && trimmed.length === 0) {
265
+ out[key] = path.resolve(cwd);
266
+ } else if (trimmed.length > 0 && !path.isAbsolute(trimmed)) {
267
+ out[key] = path.resolve(cwd, trimmed);
268
+ }
269
+ }
270
+ return out;
271
+ }
272
+ function collectWindowsUpgradeEnv(env) {
273
+ const out = {};
274
+ for (const [key, value] of Object.entries(env)) {
275
+ if (typeof value !== "string" || value.length === 0) continue;
276
+ const upper = key.toUpperCase();
277
+ if (!SAFE_UPGRADE_ENV_KEYS.has(upper)) continue;
278
+ out[upper === "PATH" ? "PATH" : key] = value;
279
+ }
280
+ return out;
281
+ }
282
+ function xmlEscapeText(value) {
283
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
284
+ }
285
+ function buildWindowsUpgradeTaskXml(params) {
286
+ const args = `"${params.bootstrapPath.replace(/"/g, '\\"')}"`;
287
+ return [
288
+ '<?xml version="1.0" encoding="UTF-16"?>',
289
+ '<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">',
290
+ " <RegistrationInfo>",
291
+ " <Description>Pie manager self-upgrade one-shot runner</Description>",
292
+ " </RegistrationInfo>",
293
+ " <Triggers />",
294
+ " <Principals>",
295
+ ' <Principal id="Author">',
296
+ " <LogonType>InteractiveToken</LogonType>",
297
+ " <RunLevel>LeastPrivilege</RunLevel>",
298
+ " </Principal>",
299
+ " </Principals>",
300
+ " <Settings>",
301
+ " <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>",
302
+ " <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>",
303
+ " <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>",
304
+ " <AllowHardTerminate>true</AllowHardTerminate>",
305
+ " <StartWhenAvailable>false</StartWhenAvailable>",
306
+ " <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>",
307
+ " <IdleSettings>",
308
+ " <StopOnIdleEnd>false</StopOnIdleEnd>",
309
+ " <RestartOnIdle>false</RestartOnIdle>",
310
+ " </IdleSettings>",
311
+ " <AllowStartOnDemand>true</AllowStartOnDemand>",
312
+ " <Enabled>true</Enabled>",
313
+ " <Hidden>true</Hidden>",
314
+ " <RunOnlyIfIdle>false</RunOnlyIfIdle>",
315
+ " <WakeToRun>false</WakeToRun>",
316
+ " <ExecutionTimeLimit>PT15M</ExecutionTimeLimit>",
317
+ " <Priority>7</Priority>",
318
+ " </Settings>",
319
+ ' <Actions Context="Author">',
320
+ " <Exec>",
321
+ ` <Command>${xmlEscapeText(params.nodePath)}</Command>`,
322
+ ` <Arguments>${xmlEscapeText(args)}</Arguments>`,
323
+ ` <WorkingDirectory>${xmlEscapeText(params.workingDir)}</WorkingDirectory>`,
324
+ " </Exec>",
325
+ " </Actions>",
326
+ "</Task>",
327
+ ""
328
+ ].join("\r\n");
329
+ }
330
+ function buildWindowsUpgradeBootstrapScript(cfg) {
331
+ return [
332
+ "// Generated by Pie for a one-shot out-of-Job Windows service upgrade.",
333
+ 'import { spawnSync } from "node:child_process";',
334
+ 'import * as fs from "node:fs";',
335
+ `const cfg = ${JSON.stringify(cfg)};`,
336
+ "try { fs.rmSync(cfg.xmlPath, { force: true }); } catch {}",
337
+ "try { fs.rmSync(cfg.bootstrapPath, { force: true }); } catch {}",
338
+ "const childEnv = { ...process.env };",
339
+ "for (const [k, v] of Object.entries(cfg.env)) {",
340
+ " const lower = k.toLowerCase();",
341
+ " for (const existing of Object.keys(childEnv)) {",
342
+ " if (existing.toLowerCase() === lower) delete childEnv[existing];",
343
+ " }",
344
+ " childEnv[k] = v;",
345
+ "}",
346
+ "let out;",
347
+ 'try { out = fs.openSync(cfg.logFile, "a"); } catch { out = undefined; }',
348
+ "const appendLog = (line) => {",
349
+ " if (out !== undefined) { try { fs.writeSync(out, line); } catch {} }",
350
+ "};",
351
+ "try {",
352
+ ' const res = spawnSync(cfg.node, [cfg.entry, "manager", "upgrade"], {',
353
+ " cwd: cfg.workingDir,",
354
+ " env: childEnv,",
355
+ " windowsHide: true,",
356
+ ' stdio: out !== undefined ? ["ignore", out, out] : "ignore",',
357
+ " });",
358
+ " if (res.error) {",
359
+ " appendLog(`[pie-upgrade-bootstrap] spawn error (${cfg.taskName}): ${res.error.message || String(res.error)}\\n`);",
360
+ " }",
361
+ ' process.exitCode = typeof res.status === "number" ? res.status : 1;',
362
+ "} finally {",
363
+ " if (out !== undefined) { try { fs.closeSync(out); } catch {} }",
364
+ " if (!cfg.skipTaskDelete) {",
365
+ ' try { spawnSync("schtasks", ["/Delete", "/TN", cfg.taskName, "/F"], { windowsHide: true, timeout: 10_000, stdio: "ignore" }); } catch {}',
366
+ " }",
367
+ "}",
368
+ ""
369
+ ].join("\n");
370
+ }
371
+ function sweepStaleUpgradeBootstrapFiles(managerDir, nowMs = Date.now()) {
372
+ const MAX_AGE_MS = 30 * 6e4;
373
+ try {
374
+ for (const name of fs.readdirSync(managerDir)) {
375
+ if (!/^upgrade-actor-[\w-]+\.(?:mjs|xml)$/.test(name)) continue;
376
+ const full = path.join(managerDir, name);
377
+ try {
378
+ const st = fs.statSync(full);
379
+ if (nowMs - st.mtimeMs > MAX_AGE_MS) {
380
+ fs.rmSync(full, { force: true });
381
+ }
382
+ } catch {
383
+ }
384
+ }
385
+ } catch {
386
+ }
387
+ }
388
+ function launchWindowsServiceUpgradeActor(params, runSchtasks = (args) => {
389
+ const res = spawnSync("schtasks", args, { encoding: "utf8", timeout: 2e4, windowsHide: true });
390
+ return { status: res.status, stdout: res.stdout, stderr: res.stderr, error: res.error };
391
+ }) {
392
+ const launchId = params.launchId ?? `${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`;
393
+ const taskName = params.taskName ?? `${WINDOWS_UPGRADE_TASK_NAME}.${launchId}`;
394
+ const workingDir = params.workingDir ?? os.tmpdir();
395
+ const bootstrapPath = path.join(params.managerDir, `upgrade-actor-${launchId}.mjs`);
396
+ const xmlPath = path.join(params.managerDir, `upgrade-actor-${launchId}.xml`);
397
+ const cleanup = (deleteTask) => {
398
+ try {
399
+ fs.rmSync(xmlPath, { force: true });
400
+ } catch {
401
+ }
402
+ try {
403
+ fs.rmSync(bootstrapPath, { force: true });
404
+ } catch {
405
+ }
406
+ if (deleteTask) {
407
+ try {
408
+ runSchtasks(["/Delete", "/TN", taskName, "/F"]);
409
+ } catch {
410
+ }
411
+ }
412
+ };
413
+ try {
414
+ fs.mkdirSync(params.managerDir, { recursive: true });
415
+ sweepStaleUpgradeBootstrapFiles(params.managerDir);
416
+ const script = buildWindowsUpgradeBootstrapScript({
417
+ node: params.nodePath,
418
+ entry: params.entry,
419
+ logFile: params.logFile,
420
+ taskName,
421
+ bootstrapPath,
422
+ xmlPath,
423
+ workingDir,
424
+ env: collectWindowsUpgradeEnv(params.env)
425
+ });
426
+ fs.writeFileSync(bootstrapPath, script, { encoding: "utf8", mode: 384 });
427
+ const xml = buildWindowsUpgradeTaskXml({ nodePath: params.nodePath, bootstrapPath, workingDir });
428
+ const xmlBytes = Buffer.concat([Buffer.from([255, 254]), Buffer.from(xml, "utf16le")]);
429
+ fs.writeFileSync(xmlPath, xmlBytes, { mode: 384 });
430
+ const created = runSchtasks(["/Create", "/TN", taskName, "/XML", xmlPath, "/F"]);
431
+ if (created.error || created.status !== 0) {
432
+ cleanup(false);
433
+ const msg = created.error?.message || `${created.stdout ?? ""} ${created.stderr ?? ""}`.trim() || `exit ${created.status}`;
434
+ return { ok: false, detail: `schtasks /Create failed for ${taskName}: ${msg.slice(0, 300)}` };
435
+ }
436
+ const started = runSchtasks(["/Run", "/TN", taskName]);
437
+ if (started.error || started.status !== 0) {
438
+ cleanup(true);
439
+ const msg = started.error?.message || `${started.stdout ?? ""} ${started.stderr ?? ""}`.trim() || `exit ${started.status}`;
440
+ return { ok: false, detail: `schtasks /Run failed for ${taskName}: ${msg.slice(0, 300)}` };
441
+ }
442
+ return {
443
+ ok: true,
444
+ detail: `scheduled task ${taskName} \xB7 log ${params.logFile}`,
445
+ taskName,
446
+ bootstrapPath,
447
+ xmlPath
448
+ };
449
+ } catch (error) {
450
+ cleanup(false);
451
+ return { ok: false, detail: error instanceof Error ? error.message : String(error) };
452
+ }
453
+ }
454
+
455
+ export {
456
+ normalizePreInstallStopOutcome,
457
+ resolveDefaultTuiUsePidFile,
458
+ scanBlockingWindowsPeers,
459
+ runWindowsPreInstallStop,
460
+ isWindowsServiceManager,
461
+ resolveAbsoluteActorEnv,
462
+ launchWindowsServiceUpgradeActor
463
+ };
@@ -907,7 +907,7 @@ function withStartLock(dir, fn) {
907
907
  });
908
908
  }
909
909
  async function runUpgradeCommand(args) {
910
- const { upgradePaths, performUpgrade, cliEffects, parseTarget } = await import("./manager-upgrade-LSTOHBUV.js");
910
+ const { upgradePaths, performUpgrade, cliEffects, parseTarget } = await import("./manager-upgrade-XPFXKO7A.js");
911
911
  const targetIdx = args.indexOf("--target");
912
912
  if (targetIdx >= 0 && typeof args[targetIdx + 1] !== "string") {
913
913
  console.error('--target expects "latest" or an x.y.z version (no value given)');
@@ -1,4 +1,10 @@
1
1
  import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
2
+ import {
3
+ normalizePreInstallStopOutcome,
4
+ resolveDefaultTuiUsePidFile,
5
+ runWindowsPreInstallStop,
6
+ scanBlockingWindowsPeers
7
+ } from "./chunk-BB7ETSJK.js";
2
8
  import {
3
9
  readProcessCommandLine
4
10
  } from "./chunk-7RJXKN7N.js";
@@ -245,22 +251,28 @@ async function performUpgrade(paths, effects, options) {
245
251
  stage = s;
246
252
  }, build));
247
253
  }
254
+ let stoppedBeforeInstall = false;
248
255
  if (effects.preInstallStop) {
249
- const stopped = effects.preInstallStop(state);
250
- if (stopped === "refused") {
251
- return finish(build("install", "refused: could not stop the resident/workers before install (Windows file locks); check pie manager status and retry"));
256
+ const stopped = normalizePreInstallStopOutcome(effects.preInstallStop(state));
257
+ if (stopped.status === "refused") {
258
+ return finish(build("install", stopped.detail || "refused: could not stop the resident/workers before install (Windows file locks); check pie manager status and retry"));
259
+ }
260
+ if (stopped.status === "stopped") {
261
+ stoppedBeforeInstall = true;
262
+ effects.log("windows: resident/workers stopped before install (native-module file locks)");
252
263
  }
253
- if (stopped === "stopped") effects.log("windows: resident/workers stopped before install (native-module file locks)");
254
264
  }
255
265
  const install = effects.npmInstall(toVersion);
256
266
  if (install.code !== 0) {
267
+ const recovery = stoppedBeforeInstall ? "\n(Windows: manager was stopped before install; run `pie manager start` or retry `pie manager upgrade`.)" : "";
257
268
  return finish(build("install", `npm install @cydm/pie@${toVersion} failed (exit ${install.code}):
258
- ${install.tail}`));
269
+ ${install.tail}${recovery}`));
259
270
  }
260
271
  const target = effects.installTargetCheck();
261
272
  if (!target.ok) {
273
+ const recovery = stoppedBeforeInstall ? "\n(Windows: manager was stopped before install; run `pie manager start` or retry `pie manager upgrade`.)" : "";
262
274
  return finish(build("install", `install target mismatch \u2014 restart skipped:
263
- ${target.detail}`));
275
+ ${target.detail}${recovery}`));
264
276
  }
265
277
  return finish(await restartAndRecycle(effects, paths, state, fromVersion, toVersion, (s) => {
266
278
  stage = s;
@@ -589,54 +601,67 @@ function cliEffects(paths, log) {
589
601
  },
590
602
  scanWorkers: () => scanWorkers(paths.discoveryDir),
591
603
  retireWorkerIfStillIdle: (peer) => {
604
+ const isPidAlive = (pid) => {
605
+ try {
606
+ process.kill(pid, 0);
607
+ return true;
608
+ } catch (error) {
609
+ return error.code !== "ESRCH";
610
+ }
611
+ };
592
612
  const fresh = readDiscoveryEntry(paths.discoveryDir, peer.file);
593
- if (!fresh || fresh.pid !== peer.pid) return "gone";
613
+ if (!fresh || fresh.pid !== peer.pid) return isPidAlive(peer.pid) ? "unknown" : "gone";
594
614
  if (fresh.unattended !== true || fresh.isManager === true) return "foreign";
595
615
  if (fresh.state !== "idle") return "busy";
596
- if (residentCommandLineLooksLikePie(peer.pid) === void 0) return "foreign";
616
+ const cmdline = readProcessCommandLine(peer.pid);
617
+ if (cmdline === void 0) return isPidAlive(peer.pid) ? "unknown" : "gone";
618
+ if (!cmdline || !/json-events/.test(cmdline) || !/--idle/.test(cmdline)) return "foreign";
597
619
  const updatedAt = typeof fresh.updatedAt === "number" ? fresh.updatedAt : peer.updatedAt;
598
620
  const startedAt = processStartedAt(peer.pid);
599
621
  if (updatedAt !== void 0 && startedAt !== void 0 && startedAt > updatedAt + 1e4) return "foreign";
600
622
  try {
601
623
  process.kill(peer.pid, process.platform === "win32" ? void 0 : "SIGTERM");
602
624
  return "retired";
603
- } catch {
604
- return "gone";
625
+ } catch (error) {
626
+ return error.code === "ESRCH" ? "gone" : "failed";
605
627
  }
606
628
  },
607
629
  writeResult: (result) => writeResultAtomic(paths.resultFile, result, log),
608
630
  tryLock: () => tryLockWithReclamation(paths.lockFile),
609
631
  unlock: () => unlockOwned(paths.lockFile),
610
- ...process.platform === "win32" ? { preInstallStop: (state) => {
611
- let touched = false;
612
- for (const peer of partitionWorkers(effects.scanWorkers()).recycle) {
613
- if (effects.retireWorkerIfStillIdle(peer) === "retired") {
614
- touched = true;
615
- effects.log(`windows pre-install: retired idle worker pid ${peer.pid} (${peer.name})`);
616
- }
617
- }
618
- if (state.service === true) {
619
- try {
620
- spawnSync("schtasks", ["/End", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4, windowsHide: true });
621
- touched = true;
622
- } catch (error) {
623
- log(`windows pre-install: schtasks /End failed: ${error instanceof Error ? error.message : String(error)}`);
624
- return "refused";
625
- }
626
- } else {
627
- const status = effects.residentStatus(state);
628
- if (status === "foreign" || status === "unknown") return "refused";
629
- if (status === "alive") {
630
- const stopped = effects.terminateResident(state);
631
- if (stopped !== "terminated" && stopped !== "dead") return "refused";
632
- if (stopped === "terminated" && typeof state.pid === "number") {
633
- if (!effects.waitExit(state.pid, 2e4)) log(`windows pre-install: resident pid ${state.pid} did not exit within 20s; npm may still hit file locks`);
632
+ ...process.platform === "win32" ? {
633
+ preInstallStop: (state) => runWindowsPreInstallStop(state, {
634
+ scanBlockingPeers: (s) => scanBlockingWindowsPeers(paths.discoveryDir, s.sessionId, s.pid, {
635
+ tuiUsePidFile: resolveDefaultTuiUsePidFile()
636
+ }),
637
+ scanIdleWorkers: () => partitionWorkers(effects.scanWorkers()).recycle,
638
+ retireWorkerIfStillIdle: (peer) => effects.retireWorkerIfStillIdle(peer),
639
+ findManagerResident: (sid) => findManagerResident(paths.discoveryDir, sid),
640
+ residentStatus: (s) => effects.residentStatus(s),
641
+ terminateResident: (s) => effects.terminateResident(s),
642
+ endServiceTask: () => {
643
+ const r = spawnSync("schtasks", ["/End", "/TN", "dev.pie.manager"], { encoding: "utf8", timeout: 2e4, windowsHide: true });
644
+ return {
645
+ status: r.status,
646
+ detail: `${r.stdout ?? ""} ${r.stderr ?? ""}`.trim().slice(0, 200),
647
+ ...r.error ? { spawnError: r.error.message } : {}
648
+ };
649
+ },
650
+ waitExit: (pid, timeoutMs) => effects.waitExit(pid, timeoutMs),
651
+ isPidAlive: (pid) => {
652
+ try {
653
+ process.kill(pid, 0);
654
+ return true;
655
+ } catch (error) {
656
+ return error.code !== "ESRCH";
634
657
  }
635
- touched = true;
636
- }
637
- }
638
- return touched ? "stopped" : "unnecessary";
639
- } } : {},
658
+ },
659
+ settleAfterStop: () => {
660
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 300);
661
+ },
662
+ log
663
+ })
664
+ } : {},
640
665
  log
641
666
  };
642
667
  return effects;
package/dist/cli.js CHANGED
@@ -63645,7 +63645,7 @@ var StdinBuffer = class extends EventEmitter {
63645
63645
 
63646
63646
  // ../../packages/tui/src/terminal.ts
63647
63647
  import * as fs11 from "node:fs";
63648
- import koffi from "koffi";
63648
+ import { createRequire as createRequire3 } from "node:module";
63649
63649
 
63650
63650
  // ../../packages/tui/src/osc-5522.ts
63651
63651
  import { randomBytes } from "node:crypto";
@@ -64028,6 +64028,7 @@ var ProcessTerminal = class _ProcessTerminal {
64028
64028
  enableWindowsVTInput() {
64029
64029
  if (process.platform !== "win32") return;
64030
64030
  try {
64031
+ const koffi = createRequire3(import.meta.url)("koffi");
64031
64032
  const k32 = koffi.load("kernel32.dll");
64032
64033
  const GetStdHandle = k32.func("void* __stdcall GetStdHandle(int)");
64033
64034
  const GetConsoleMode = k32.func("bool __stdcall GetConsoleMode(void*, _Out_ uint32_t*)");
@@ -86166,7 +86167,7 @@ async function main() {
86166
86167
  if (sub === STABLE_CLI_COMMANDS.models || sub === STABLE_CLI_COMMANDS.manager) {
86167
86168
  try {
86168
86169
  if (sub === STABLE_CLI_COMMANDS.models) await runModelsCommand(subArgs);
86169
- else await (await import("./chunks/manager-cli-Y6HM3MHA.js")).runManagerCommand(subArgs);
86170
+ else await (await import("./chunks/manager-cli-UU6SDS3F.js")).runManagerCommand(subArgs);
86170
86171
  } catch (error) {
86171
86172
  console.error(error instanceof Error ? error.message : String(error));
86172
86173
  process.exitCode = 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cydm/pie",
3
- "version": "4.10.0",
3
+ "version": "4.10.1",
4
4
  "description": "Pie AI Agent CLI",
5
5
  "type": "module",
6
6
  "bin": {