@cydm/pie 4.10.0 → 4.10.2
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.
- package/dist/builtin/extensions/im-forward/index.js +172 -53
- package/dist/builtin/extensions/mcp-adapter/index.js +216 -7
- package/dist/builtin/extensions/pie-proc/index.js +176 -146
- package/dist/chunks/chunk-BB7ETSJK.js +463 -0
- package/dist/chunks/chunk-Z2RT3P4F.js +251 -0
- package/dist/chunks/manager-allow-SF5ROGDM.js +21 -0
- package/dist/chunks/{manager-cli-Y6HM3MHA.js → manager-cli-BXI4UFTJ.js} +12 -55
- package/dist/chunks/{manager-upgrade-LSTOHBUV.js → manager-upgrade-XPFXKO7A.js} +64 -39
- package/dist/cli.js +295 -36
- package/package.json +1 -1
|
@@ -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, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
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
|
+
};
|