@lark-codem/codem-cli 0.1.274-test.202611170849.0.gc5a50ef → 0.1.274

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,178 +1,178 @@
1
- import { spawn } from "node:child_process";
2
- import fs from "node:fs/promises";
3
- import os from "node:os";
4
- import path from "node:path";
5
-
6
- const WINDOWS_LEGACY_DAEMON_CAPABILITY = "shutdown_for_service_operation";
7
- const WINDOWS_LEGACY_DAEMON_CAPABILITY_RELATIVE_PATH = path.join(
8
- "runtime",
9
- "legacy-daemon-control",
10
- "capability.json"
11
- );
12
-
13
- // The dedicated Windows daemon Host owns the top-level console policy. Every
14
- // child it can reach must stay hidden, and a local spawn option must not be able
15
- // to undo that invariant. Interactive and non-Windows launches keep their
16
- // options object untouched.
17
- export function applyHostedWindowsChildOptions(
18
- options = {},
19
- {
20
- // Hosted mode belongs to the current daemon process, not to the child env
21
- // object supplied by an individual caller. Otherwise a caller could omit
22
- // or replace `options.env` and accidentally bypass the console invariant.
23
- env = process.env,
24
- platform = process.platform
25
- } = {}
26
- ) {
27
- if (platform !== "win32" || env?.CODEM_DAEMON_HOSTED_WINDOWS !== "1") {
28
- return options;
29
- }
30
-
31
- return {
32
- ...options,
33
- windowsHide: true
34
- };
35
- }
36
-
37
- export function shouldWatchWindowsDaemonHostMigration({
38
- platform = process.platform,
39
- argv = process.argv.slice(2),
40
- env = process.env
41
- } = {}) {
42
- return platform === "win32" &&
43
- argv[0] === "daemon" &&
44
- env?.CODEM_DAEMON_HOSTED_WINDOWS !== "1" &&
45
- typeof env?.CODEM_DAEMON_RUNTIME_CLIENT_INSTANCE_ID === "string" &&
46
- env.CODEM_DAEMON_RUNTIME_CLIENT_INSTANCE_ID.trim() !== "";
47
- }
48
-
49
- export function isCurrentWindowsLegacyDaemonCapability(
50
- value,
51
- { daemonPid, startedAtMs } = {}
52
- ) {
53
- return value?.schemaVersion === 1 &&
54
- value?.protocolVersion === 1 &&
55
- value?.capability === WINDOWS_LEGACY_DAEMON_CAPABILITY &&
56
- Number(value?.rootIdentity?.pid) === daemonPid &&
57
- Number(value?.publishedAtUnixMs) >= startedAtMs;
58
- }
59
-
60
- export function launchWindowsDaemonHostMigration({
61
- binaryPath,
62
- launcherPid = process.pid,
63
- env = process.env,
64
- spawnImpl = spawn
65
- } = {}) {
66
- if (String(binaryPath).includes("'")) {
67
- throw new Error("CodeM runtime path cannot be represented in the Windows migration handoff");
68
- }
69
- const workingDirectory = path.win32.dirname(binaryPath);
70
- if (workingDirectory.includes("'")) {
71
- throw new Error("CodeM working directory cannot be represented in the Windows migration handoff");
72
- }
73
- const commandLine = `"${binaryPath}" service start --windows-migration-launcher-pid ${launcherPid}`;
74
- const script = [
75
- "$startup = ([wmiclass]'Win32_ProcessStartup').CreateInstance()",
76
- "$startup.ShowWindow = 0",
77
- `$result = ([wmiclass]'Win32_Process').Create('${commandLine}', '${workingDirectory}', $startup)`,
78
- "if ($null -eq $result -or [int]$result.ReturnValue -ne 0) { exit 1 }"
79
- ].join("\r\n");
80
- const powershellPath = path.win32.join(
81
- env?.SystemRoot || String.raw`C:\Windows`,
82
- "System32",
83
- "WindowsPowerShell",
84
- "v1.0",
85
- "powershell.exe"
86
- );
87
- const bridge = spawnImpl(powershellPath, [
88
- "-NoLogo",
89
- "-NoProfile",
90
- "-NonInteractive",
91
- "-WindowStyle",
92
- "Hidden",
93
- "-EncodedCommand",
94
- Buffer.from(script, "utf16le").toString("base64")
95
- ], {
96
- env,
97
- stdio: "ignore",
98
- windowsHide: true
99
- });
100
- // Task Scheduler may place the launcher in a Job. CREATE_NEW_PROCESS_GROUP
101
- // (`detached` in Node) does not escape that Job. Windows PowerShell delegates
102
- // the exact worker creation to Win32_Process.Create, whose documented
103
- // contract creates it outside the caller's Job; the short-lived bridge can
104
- // then remain inside the Task without owning migration lifetime.
105
- bridge.once?.("error", () => {});
106
- bridge.unref?.();
107
- return bridge;
108
- }
109
-
110
- export function watchWindowsDaemonHostMigration({
111
- binaryPath,
112
- daemonPid,
113
- launcherPid = process.pid,
114
- argv = process.argv.slice(2),
115
- env = process.env,
116
- platform = process.platform,
117
- codemHome = env?.CODEM_HOME || path.join(env?.USERPROFILE || os.homedir(), ".codem"),
118
- fsImpl = fs,
119
- spawnImpl = spawn,
120
- pollIntervalMs = 250,
121
- timeoutMs = 60_000,
122
- nowImpl = Date.now,
123
- setTimeoutImpl = setTimeout,
124
- clearTimeoutImpl = clearTimeout
125
- } = {}) {
126
- if (!shouldWatchWindowsDaemonHostMigration({ platform, argv, env })) {
127
- return () => {};
128
- }
129
-
130
- const capabilityPath = path.join(codemHome, WINDOWS_LEGACY_DAEMON_CAPABILITY_RELATIVE_PATH);
131
- const startedAtMs = nowImpl();
132
- let stopped = false;
133
- let timer = null;
134
-
135
- const stop = () => {
136
- stopped = true;
137
- if (timer !== null) {
138
- clearTimeoutImpl(timer);
139
- timer = null;
140
- }
141
- };
142
- const schedule = () => {
143
- if (stopped) return;
144
- timer = setTimeoutImpl(() => {
145
- timer = null;
146
- void probe();
147
- }, pollIntervalMs);
148
- timer?.unref?.();
149
- };
150
- const probe = async () => {
151
- if (stopped) return;
152
- try {
153
- const value = JSON.parse(await fsImpl.readFile(capabilityPath, "utf8"));
154
- if (isCurrentWindowsLegacyDaemonCapability(value, { daemonPid, startedAtMs })) {
155
- stop();
156
- launchWindowsDaemonHostMigration({
157
- binaryPath,
158
- launcherPid,
159
- env,
160
- spawnImpl
161
- });
162
- return;
163
- }
164
- } catch {
165
- // Capability publication is atomic and expected to be absent while the
166
- // daemon starts. A malformed/unreadable file is never accepted; keep the
167
- // bounded watcher alive so a later valid replacement can win.
168
- }
169
- if (nowImpl() - startedAtMs >= timeoutMs) {
170
- stop();
171
- return;
172
- }
173
- schedule();
174
- };
175
-
176
- void probe();
177
- return stop;
178
- }
1
+ import { spawn } from "node:child_process";
2
+ import fs from "node:fs/promises";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+
6
+ const WINDOWS_LEGACY_DAEMON_CAPABILITY = "shutdown_for_service_operation";
7
+ const WINDOWS_LEGACY_DAEMON_CAPABILITY_RELATIVE_PATH = path.join(
8
+ "runtime",
9
+ "legacy-daemon-control",
10
+ "capability.json"
11
+ );
12
+
13
+ // The dedicated Windows daemon Host owns the top-level console policy. Every
14
+ // child it can reach must stay hidden, and a local spawn option must not be able
15
+ // to undo that invariant. Interactive and non-Windows launches keep their
16
+ // options object untouched.
17
+ export function applyHostedWindowsChildOptions(
18
+ options = {},
19
+ {
20
+ // Hosted mode belongs to the current daemon process, not to the child env
21
+ // object supplied by an individual caller. Otherwise a caller could omit
22
+ // or replace `options.env` and accidentally bypass the console invariant.
23
+ env = process.env,
24
+ platform = process.platform
25
+ } = {}
26
+ ) {
27
+ if (platform !== "win32" || env?.CODEM_DAEMON_HOSTED_WINDOWS !== "1") {
28
+ return options;
29
+ }
30
+
31
+ return {
32
+ ...options,
33
+ windowsHide: true
34
+ };
35
+ }
36
+
37
+ export function shouldWatchWindowsDaemonHostMigration({
38
+ platform = process.platform,
39
+ argv = process.argv.slice(2),
40
+ env = process.env
41
+ } = {}) {
42
+ return platform === "win32" &&
43
+ argv[0] === "daemon" &&
44
+ env?.CODEM_DAEMON_HOSTED_WINDOWS !== "1" &&
45
+ typeof env?.CODEM_DAEMON_RUNTIME_CLIENT_INSTANCE_ID === "string" &&
46
+ env.CODEM_DAEMON_RUNTIME_CLIENT_INSTANCE_ID.trim() !== "";
47
+ }
48
+
49
+ export function isCurrentWindowsLegacyDaemonCapability(
50
+ value,
51
+ { daemonPid, startedAtMs } = {}
52
+ ) {
53
+ return value?.schemaVersion === 1 &&
54
+ value?.protocolVersion === 1 &&
55
+ value?.capability === WINDOWS_LEGACY_DAEMON_CAPABILITY &&
56
+ Number(value?.rootIdentity?.pid) === daemonPid &&
57
+ Number(value?.publishedAtUnixMs) >= startedAtMs;
58
+ }
59
+
60
+ export function launchWindowsDaemonHostMigration({
61
+ binaryPath,
62
+ launcherPid = process.pid,
63
+ env = process.env,
64
+ spawnImpl = spawn
65
+ } = {}) {
66
+ if (String(binaryPath).includes("'")) {
67
+ throw new Error("CodeM runtime path cannot be represented in the Windows migration handoff");
68
+ }
69
+ const workingDirectory = path.win32.dirname(binaryPath);
70
+ if (workingDirectory.includes("'")) {
71
+ throw new Error("CodeM working directory cannot be represented in the Windows migration handoff");
72
+ }
73
+ const commandLine = `"${binaryPath}" service start --windows-migration-launcher-pid ${launcherPid}`;
74
+ const script = [
75
+ "$startup = ([wmiclass]'Win32_ProcessStartup').CreateInstance()",
76
+ "$startup.ShowWindow = 0",
77
+ `$result = ([wmiclass]'Win32_Process').Create('${commandLine}', '${workingDirectory}', $startup)`,
78
+ "if ($null -eq $result -or [int]$result.ReturnValue -ne 0) { exit 1 }"
79
+ ].join("\r\n");
80
+ const powershellPath = path.win32.join(
81
+ env?.SystemRoot || String.raw`C:\Windows`,
82
+ "System32",
83
+ "WindowsPowerShell",
84
+ "v1.0",
85
+ "powershell.exe"
86
+ );
87
+ const bridge = spawnImpl(powershellPath, [
88
+ "-NoLogo",
89
+ "-NoProfile",
90
+ "-NonInteractive",
91
+ "-WindowStyle",
92
+ "Hidden",
93
+ "-EncodedCommand",
94
+ Buffer.from(script, "utf16le").toString("base64")
95
+ ], {
96
+ env,
97
+ stdio: "ignore",
98
+ windowsHide: true
99
+ });
100
+ // Task Scheduler may place the launcher in a Job. CREATE_NEW_PROCESS_GROUP
101
+ // (`detached` in Node) does not escape that Job. Windows PowerShell delegates
102
+ // the exact worker creation to Win32_Process.Create, whose documented
103
+ // contract creates it outside the caller's Job; the short-lived bridge can
104
+ // then remain inside the Task without owning migration lifetime.
105
+ bridge.once?.("error", () => {});
106
+ bridge.unref?.();
107
+ return bridge;
108
+ }
109
+
110
+ export function watchWindowsDaemonHostMigration({
111
+ binaryPath,
112
+ daemonPid,
113
+ launcherPid = process.pid,
114
+ argv = process.argv.slice(2),
115
+ env = process.env,
116
+ platform = process.platform,
117
+ codemHome = env?.CODEM_HOME || path.join(env?.USERPROFILE || os.homedir(), ".codem"),
118
+ fsImpl = fs,
119
+ spawnImpl = spawn,
120
+ pollIntervalMs = 250,
121
+ timeoutMs = 60_000,
122
+ nowImpl = Date.now,
123
+ setTimeoutImpl = setTimeout,
124
+ clearTimeoutImpl = clearTimeout
125
+ } = {}) {
126
+ if (!shouldWatchWindowsDaemonHostMigration({ platform, argv, env })) {
127
+ return () => {};
128
+ }
129
+
130
+ const capabilityPath = path.join(codemHome, WINDOWS_LEGACY_DAEMON_CAPABILITY_RELATIVE_PATH);
131
+ const startedAtMs = nowImpl();
132
+ let stopped = false;
133
+ let timer = null;
134
+
135
+ const stop = () => {
136
+ stopped = true;
137
+ if (timer !== null) {
138
+ clearTimeoutImpl(timer);
139
+ timer = null;
140
+ }
141
+ };
142
+ const schedule = () => {
143
+ if (stopped) return;
144
+ timer = setTimeoutImpl(() => {
145
+ timer = null;
146
+ void probe();
147
+ }, pollIntervalMs);
148
+ timer?.unref?.();
149
+ };
150
+ const probe = async () => {
151
+ if (stopped) return;
152
+ try {
153
+ const value = JSON.parse(await fsImpl.readFile(capabilityPath, "utf8"));
154
+ if (isCurrentWindowsLegacyDaemonCapability(value, { daemonPid, startedAtMs })) {
155
+ stop();
156
+ launchWindowsDaemonHostMigration({
157
+ binaryPath,
158
+ launcherPid,
159
+ env,
160
+ spawnImpl
161
+ });
162
+ return;
163
+ }
164
+ } catch {
165
+ // Capability publication is atomic and expected to be absent while the
166
+ // daemon starts. A malformed/unreadable file is never accepted; keep the
167
+ // bounded watcher alive so a later valid replacement can win.
168
+ }
169
+ if (nowImpl() - startedAtMs >= timeoutMs) {
170
+ stop();
171
+ return;
172
+ }
173
+ schedule();
174
+ };
175
+
176
+ void probe();
177
+ return stop;
178
+ }
@@ -0,0 +1,217 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+
4
+ import { applyHostedWindowsChildOptions } from "./platform-child-process.js";
5
+
6
+ const execFileAsync = promisify(execFile);
7
+
8
+ /**
9
+ * 进程树终止。
10
+ *
11
+ * 为什么不能只 `child.kill()`:我们 spawn 的是 linco 一个进程,但 linco 干活时
12
+ * 会自己再起子进程(内联的 `npm run dev`、`cargo build`、git…)。只杀直接子进程
13
+ * 会把整棵子树留成孤儿——它们继续占端口、占锁,而且**继承了我们的 stdio 管道**,
14
+ * 于是 `child` 的 `close` 永远不触发(见 linco-runner.js 的
15
+ * LINCO_EXIT_DRAIN_GRACE_MS)。
16
+ *
17
+ * 为什么必须"先快照后代、再杀":`ps` 反查 ppid(unix)和 `taskkill /T`
18
+ * (Windows)**都依赖父进程还活着**。父进程一死,后代立刻被 reparent 到 PID 1
19
+ * (Windows 上 ppid 指向一个已消失的 pid),血缘信息就永久丢了,再也认不出哪些
20
+ * 进程曾属于这次 run。而"父死子活"恰恰就是我们要处理的那个场景。所以血缘必须
21
+ * 在**树还完整的时刻**取样,强杀阶段只按快照执行。
22
+ */
23
+
24
+ // `ps -A -o pid=,ppid=` 是 POSIX 通用形态,macOS / Linux 输出一致(两列数字,
25
+ // 前导空格对齐)。用 `=` 后缀去掉表头,省一次解析分支。
26
+ const UNIX_PS_ARGS = ["-A", "-o", "pid=,ppid="];
27
+
28
+ // Win32 没有 POSIX ps。PowerShell 的 CIM 查询比已废弃的 wmic 稳(wmic 在
29
+ // Windows 11 / Server 2025 上默认不再安装)。输出两列数字,与 unix 分支同构。
30
+ const WINDOWS_PS_ARGS = [
31
+ "-NoProfile",
32
+ "-NonInteractive",
33
+ "-Command",
34
+ "Get-CimInstance Win32_Process | ForEach-Object { \"$($_.ProcessId) $($_.ParentProcessId)\" }"
35
+ ];
36
+
37
+ function parsePidPairs(stdout) {
38
+ const pairs = [];
39
+ for (const line of String(stdout ?? "").split("\n")) {
40
+ const match = line.trim().match(/^(\d+)\s+(\d+)$/);
41
+ if (!match) {
42
+ continue;
43
+ }
44
+ pairs.push([Number.parseInt(match[1], 10), Number.parseInt(match[2], 10)]);
45
+ }
46
+ return pairs;
47
+ }
48
+
49
+ /**
50
+ * 广度优先收集 rootPid 的全部后代(不含 rootPid 自己),返回**由深到浅**的顺序。
51
+ *
52
+ * 由深到浅是为了终止时先杀叶子:先杀中间节点会让它的孩子提前变孤儿,剩下的
53
+ * kill 就打空了。
54
+ *
55
+ * 任何失败都返回空数组——快照是尽力而为的增强,绝不能让它把调用方的终止路径
56
+ * 拖崩。拿不到血缘时调用方仍会杀直接子进程,等于退回改动前的行为。
57
+ */
58
+ export async function snapshotDescendantPids(
59
+ rootPid,
60
+ { platform = process.platform, execFileImpl = execFileAsync, timeoutMs = null, onError = null } = {}
61
+ ) {
62
+ if (!Number.isInteger(rootPid) || rootPid <= 0) {
63
+ return [];
64
+ }
65
+
66
+ const startedAt = performance.now();
67
+ let pairs = [];
68
+ try {
69
+ const { stdout } =
70
+ platform === "win32"
71
+ ? await execFileImpl(
72
+ "powershell.exe",
73
+ WINDOWS_PS_ARGS,
74
+ applyHostedWindowsChildOptions(
75
+ Number.isFinite(timeoutMs) && timeoutMs > 0 ? { timeout: timeoutMs } : {},
76
+ { platform }
77
+ )
78
+ )
79
+ : await execFileImpl(
80
+ "ps",
81
+ UNIX_PS_ARGS,
82
+ applyHostedWindowsChildOptions(
83
+ Number.isFinite(timeoutMs) && timeoutMs > 0 ? { timeout: timeoutMs } : {},
84
+ { platform }
85
+ )
86
+ );
87
+ pairs = parsePidPairs(stdout);
88
+ } catch (error) {
89
+ onError?.(error, {
90
+ durationMs: Math.round(performance.now() - startedAt),
91
+ timeoutMs,
92
+ code: error?.code ?? null,
93
+ killed: error?.killed === true,
94
+ signal: error?.signal ?? null
95
+ });
96
+ return [];
97
+ }
98
+
99
+ const childrenByParent = new Map();
100
+ for (const [pid, ppid] of pairs) {
101
+ if (pid === ppid) {
102
+ // 自指(部分系统上 pid 1 会这么报)。放任会让下面的 BFS 死循环。
103
+ continue;
104
+ }
105
+ const bucket = childrenByParent.get(ppid);
106
+ if (bucket) {
107
+ bucket.push(pid);
108
+ } else {
109
+ childrenByParent.set(ppid, [pid]);
110
+ }
111
+ }
112
+
113
+ const levels = [];
114
+ const seen = new Set([rootPid]);
115
+ let frontier = [rootPid];
116
+ // 深度上限:纯防御。真实进程树不会有 64 层,但快照来自外部命令的文本输出,
117
+ // 一旦解析出环就会在这里无限打转。
118
+ for (let depth = 0; depth < 64 && frontier.length > 0; depth += 1) {
119
+ const next = [];
120
+ for (const pid of frontier) {
121
+ for (const childPid of childrenByParent.get(pid) ?? []) {
122
+ if (seen.has(childPid)) {
123
+ continue;
124
+ }
125
+ seen.add(childPid);
126
+ next.push(childPid);
127
+ }
128
+ }
129
+ if (next.length > 0) {
130
+ levels.push(next);
131
+ }
132
+ frontier = next;
133
+ }
134
+
135
+ return levels.reverse().flat();
136
+ }
137
+
138
+ /**
139
+ * 杀掉 rootPid 及其后代。
140
+ *
141
+ * `descendants` 由调用方在树还完整时用 snapshotDescendantPids 取样后传入;
142
+ * 不传就现取(只在父进程仍活着时才有意义)。
143
+ *
144
+ * 返回实际发出信号的 pid 数——调用方用它做日志,不做控制流:kill 失败绝大多数
145
+ * 是"进程已经没了",那正是我们要的结果。
146
+ */
147
+ export async function terminateProcessTree({
148
+ pid,
149
+ descendants = null,
150
+ signal = "SIGKILL",
151
+ platform = process.platform,
152
+ execFileImpl = execFileAsync,
153
+ killImpl = (targetPid, targetSignal) => process.kill(targetPid, targetSignal),
154
+ timeoutMs = null,
155
+ onError = null
156
+ } = {}) {
157
+ if (!Number.isInteger(pid) || pid <= 0) {
158
+ return { signaled: 0 };
159
+ }
160
+
161
+ const targets =
162
+ descendants ??
163
+ (await snapshotDescendantPids(pid, { platform, execFileImpl, timeoutMs, onError }));
164
+ let signaled = 0;
165
+
166
+ if (platform === "win32") {
167
+ // /T 覆盖此刻仍挂在 pid 下的活树,一次调用比逐个 taskkill 更少竞态。
168
+ try {
169
+ await execFileImpl(
170
+ "taskkill.exe",
171
+ ["/F", "/T", "/PID", String(pid)],
172
+ applyHostedWindowsChildOptions(
173
+ Number.isFinite(timeoutMs) && timeoutMs > 0 ? { timeout: timeoutMs } : {},
174
+ { platform }
175
+ )
176
+ );
177
+ signaled += 1;
178
+ } catch (error) {
179
+ // pid 已消失时 taskkill 返回非 0,属预期。
180
+ onError?.(error);
181
+ }
182
+ // 快照里那些已经和 pid 断了血缘的(父先死的孤儿),/T 够不着,逐个补刀。
183
+ for (const targetPid of targets) {
184
+ try {
185
+ await execFileImpl(
186
+ "taskkill.exe",
187
+ ["/F", "/PID", String(targetPid)],
188
+ applyHostedWindowsChildOptions(
189
+ Number.isFinite(timeoutMs) && timeoutMs > 0 ? { timeout: timeoutMs } : {},
190
+ { platform }
191
+ )
192
+ );
193
+ signaled += 1;
194
+ } catch {
195
+ // 已退出。
196
+ }
197
+ }
198
+ return { signaled };
199
+ }
200
+
201
+ // unix:叶子优先,最后才是 root。
202
+ for (const targetPid of targets) {
203
+ try {
204
+ killImpl(targetPid, signal);
205
+ signaled += 1;
206
+ } catch {
207
+ // 已退出。
208
+ }
209
+ }
210
+ try {
211
+ killImpl(pid, signal);
212
+ signaled += 1;
213
+ } catch {
214
+ // 已退出。
215
+ }
216
+ return { signaled };
217
+ }