@mozhi0012/pi-terminal-worker 0.3.0 → 0.4.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.
@@ -0,0 +1,108 @@
1
+ /** Multi-step CLI launchers. The Windows launchWorkerWindow API remains synchronous. */
2
+ import { execFile } from "node:child_process";
3
+ import { assertCmdSafeValues, type TerminalLaunchSpec } from "./launcher.js";
4
+
5
+ export class TerminalSpawnError extends Error {
6
+ constructor(public readonly backend: string, public readonly cause: Error) {
7
+ super(`终端后端 ${backend} 启动失败: ${cause.message}`);
8
+ this.name = "TerminalSpawnError";
9
+ }
10
+ }
11
+
12
+ export type TerminalCommandRunner = (
13
+ command: string, args: string[], options: { cwd: string; env: NodeJS.ProcessEnv },
14
+ ) => Promise<string>;
15
+
16
+ export const runTerminalCommand: TerminalCommandRunner = (command, args, options) => new Promise((resolve, reject) => {
17
+ execFile(command, args, { ...options, shell: false, windowsHide: true, encoding: "utf8", timeout: 10_000, maxBuffer: 1024 * 1024 },
18
+ (error, stdout, stderr) => error ? reject(new Error(`${error.message}${stderr ? `: ${stderr.trim()}` : ""}`)) : resolve(stdout));
19
+ });
20
+
21
+ export interface TerminalHandle {
22
+ backend: "herdr" | "tmux";
23
+ paneId?: string;
24
+ windowId?: string;
25
+ sessionName?: string;
26
+ close: () => Promise<void>;
27
+ }
28
+
29
+ /** Only controlled variable references are sent to the interactive shell. */
30
+ export function buildHerdrRunCommand(shellName: string, values: Record<string, string>): string {
31
+ const shell = shellName.replace(/\\/g, "/").split("/").pop()!.toLowerCase().replace(/\.exe$/, "");
32
+ if (shell === "powershell" || shell === "pwsh") {
33
+ return "& $env:PITW_BOOTSTRAP_NODE $env:PITW_BOOTSTRAP_FILE --descriptor $env:PITW_BOOTSTRAP_DESC";
34
+ }
35
+ if (shell === "cmd") {
36
+ assertCmdSafeValues(Object.entries(values));
37
+ return '"%PITW_BOOTSTRAP_NODE%" "%PITW_BOOTSTRAP_FILE%" --descriptor %PITW_BOOTSTRAP_DESC%';
38
+ }
39
+ if (["bash", "zsh", "sh", "dash", "ksh", "fish"].includes(shell)) {
40
+ return '"$PITW_BOOTSTRAP_NODE" "$PITW_BOOTSTRAP_FILE" --descriptor "$PITW_BOOTSTRAP_DESC"';
41
+ }
42
+ throw new Error(`不支持的 herdr pane shell: ${shellName}`);
43
+ }
44
+
45
+ export async function launchMultiplexer(
46
+ spec: TerminalLaunchSpec,
47
+ { run = runTerminalCommand, assertActive = () => {} }: {
48
+ run?: TerminalCommandRunner;
49
+ assertActive?: () => void;
50
+ } = {},
51
+ ): Promise<TerminalHandle> {
52
+ const options = { cwd: spec.cwd, env: { ...process.env } };
53
+ let handle: TerminalHandle | undefined;
54
+ function makeHandle(data: Omit<TerminalHandle, "close">, closeArgs: string[]): TerminalHandle {
55
+ let closing: Promise<void> | undefined;
56
+ return { ...data, close: () => closing ??= run(spec.command, closeArgs, options).then(() => {}, () => {}) };
57
+ }
58
+ try {
59
+ assertActive();
60
+ if (spec.backend === "tmux") {
61
+ const output = await run(spec.command, spec.args, options);
62
+ const windowId = output.trim();
63
+ // A new session's name is already known, including if output parsing fails.
64
+ if (spec.tmuxSession) handle = makeHandle({ backend: "tmux", sessionName: spec.tmuxSession, windowId }, ["kill-session", "-t", spec.tmuxSession]);
65
+ else if (/^@\d+$/.test(windowId)) handle = makeHandle({ backend: "tmux", windowId }, ["kill-window", "-t", windowId]);
66
+ assertActive();
67
+ if (!/^@\d+$/.test(windowId)) throw new Error(`tmux 未返回窗口 ID: ${output}`);
68
+ return handle!;
69
+ }
70
+ if (spec.backend !== "herdr" || !spec.workerCommand) throw new Error("缺少 herdr 启动描述");
71
+ const values = {
72
+ PITW_BOOTSTRAP_NODE: spec.workerCommand[0],
73
+ PITW_BOOTSTRAP_FILE: spec.workerCommand[1],
74
+ PITW_BOOTSTRAP_DESC: spec.workerCommand[3],
75
+ PITW_BOOTSTRAP_HERDR: spec.command,
76
+ };
77
+ // Fixed right split preserves focus and avoids a separate layout race/CLI round-trip.
78
+ const split = await run(spec.command, ["pane", "split", "--current", "--direction", "right", "--cwd", spec.cwd,
79
+ "--no-focus", ...Object.entries(values).flatMap(([key, value]) => ["--env", `${key}=${value}`])], options);
80
+ const paneId = JSON.parse(split)?.result?.pane?.pane_id;
81
+ if (typeof paneId !== "string" || !paneId) throw new Error("herdr split 未返回 pane_id");
82
+ handle = makeHandle({ backend: "herdr", paneId }, ["pane", "close", paneId]);
83
+ assertActive();
84
+ try { await run(spec.command, ["pane", "rename", paneId, spec.title], options); } catch { /* title is cosmetic */ }
85
+ assertActive();
86
+ let shell: string | undefined;
87
+ for (let attempt = 0; attempt < 40; attempt++) {
88
+ const output = await run(spec.command, ["pane", "process-info", "--pane", paneId], options);
89
+ assertActive();
90
+ const info = JSON.parse(output)?.result?.process_info;
91
+ const process = info?.foreground_processes?.find((p: { pid: number }) => p.pid === info.shell_pid);
92
+ shell = process?.argv0 ?? process?.name;
93
+ if (shell) break;
94
+ await new Promise((resolve) => setTimeout(resolve, 50));
95
+ assertActive();
96
+ }
97
+ if (!shell) throw new Error("herdr pane shell 尚未就绪");
98
+ const command = buildHerdrRunCommand(shell, values);
99
+ await run(spec.command, ["pane", "run", paneId, command], options);
100
+ assertActive();
101
+ return handle;
102
+ } catch (error) {
103
+ if (handle) await handle.close();
104
+ // A cancellation must never turn into a fallback launch in a new session.
105
+ assertActive();
106
+ throw new TerminalSpawnError(spec.backend, error instanceof Error ? error : new Error(String(error)));
107
+ }
108
+ }