tmux-ide 2.9.21 → 2.9.23

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.
Files changed (131) hide show
  1. package/bin/cli.js +6235 -8473
  2. package/package.json +3 -3
  3. package/packages/contracts/src/index.ts +2 -0
  4. package/packages/contracts/src/pane-reader.ts +121 -0
  5. package/packages/contracts/src/pane-stream.ts +18 -0
  6. package/packages/contracts/src/visual-theme-presets.ts +58 -2
  7. package/packages/contracts/src/websocket-heartbeat.ts +41 -0
  8. package/packages/daemon/dist/command-center/automation.js +1 -1
  9. package/packages/daemon/dist/command-center/daemon-fleet-facts-observer.js +37 -5
  10. package/packages/daemon/dist/command-center/discovery.js +28 -2
  11. package/packages/daemon/dist/command-center/server.js +8 -2
  12. package/packages/daemon/dist/command-center/tmux-server-reader.js +41 -0
  13. package/packages/daemon/dist/command-center/tmux-servers.js +7 -1
  14. package/packages/daemon/dist/doctor.js +147 -43
  15. package/packages/daemon/dist/lib/bounded-tmux-read.js +34 -12
  16. package/packages/daemon/dist/lib/cli-command.js +13 -0
  17. package/packages/daemon/dist/lib/daemon-embed.js +126 -55
  18. package/packages/daemon/dist/lib/daemon-stop-progress.js +58 -0
  19. package/packages/daemon/dist/lib/embedded-daemon-lifecycle.js +11 -0
  20. package/packages/daemon/dist/lib/embedded-tmux-server-owners.js +88 -12
  21. package/packages/daemon/dist/lib/headless-daemon.js +177 -10
  22. package/packages/daemon/dist/lib/log.js +18 -1
  23. package/packages/daemon/dist/lib/pane-reader-files.js +226 -0
  24. package/packages/daemon/dist/lib/remote-tmux-command.js +8 -5
  25. package/packages/daemon/dist/lib/tmux-client-execution.js +73 -7
  26. package/packages/daemon/dist/lib/tmux-external-interaction-observer.js +140 -19
  27. package/packages/daemon/dist/lib/tmux-native-browser.js +4 -2
  28. package/packages/daemon/dist/lib/tmux-pane-reader.js +107 -0
  29. package/packages/daemon/dist/lib/tmux-server-agent-admission.js +6 -1
  30. package/packages/daemon/dist/lib/tmux-server-features.js +38 -0
  31. package/packages/daemon/dist/lib/tmux-server-owner-teardown.js +33 -0
  32. package/packages/daemon/dist/lib/tmux-server-owner.js +38 -37
  33. package/packages/daemon/dist/lib/tmux-server-owners.js +310 -20
  34. package/packages/daemon/dist/lib/tmux-server-registration.js +128 -9
  35. package/packages/daemon/dist/lib/unix-socket-authority.js +58 -3
  36. package/packages/daemon/dist/lib/workspace-pane-creation.js +10 -1
  37. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  38. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  39. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  40. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  41. package/packages/daemon/dist/open-browser.js +26 -12
  42. package/packages/daemon/dist/open-reader.js +84 -0
  43. package/packages/daemon/dist/plugins/cli.js +1 -2
  44. package/packages/daemon/dist/plugins/daemon-plugins.js +2 -10
  45. package/packages/daemon/dist/restore.js +57 -40
  46. package/packages/daemon/dist/server/pane-stream-upgrade.js +5 -1
  47. package/packages/daemon/dist/server/websocket-heartbeat.js +103 -0
  48. package/packages/daemon/dist/terminal/attachments/native-runtime.js +32 -14
  49. package/packages/daemon/dist/terminal/mirror/layout-content-rows.js +11 -0
  50. package/packages/daemon/dist/terminal/mirror/mirror-service.js +61 -3
  51. package/packages/daemon/dist/terminal/mirror/session-channel.js +13 -12
  52. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +123 -25
  53. package/packages/daemon/dist/terminal/pane-stream/runtime.js +3 -2
  54. package/packages/daemon/dist/terminal/protocol/reader-option.js +66 -0
  55. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +30 -2
  56. package/packages/daemon/dist/terminal/protocol/stock-split-resize.js +4 -1
  57. package/packages/daemon/dist/terminal/session-runtime/registry.js +17 -0
  58. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-interpreter.js +81 -3
  59. package/packages/daemon/dist/terminal/session-runtime/terminal-replica-owner.js +60 -3
  60. package/packages/daemon/dist/tmux-upgrade/cli.js +106 -0
  61. package/packages/daemon/dist/tmux-upgrade/io.js +540 -0
  62. package/packages/daemon/dist/tmux-upgrade/plan.js +238 -0
  63. package/packages/daemon/dist/tmux-upgrade/run.js +199 -0
  64. package/packages/daemon/dist/tui/chrome/snapshot.js +3 -4
  65. package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +64 -4
  66. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +35 -5
  67. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +12 -8
  68. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +125 -111
  69. package/packages/daemon/src/command-center/automation.ts +1 -1
  70. package/packages/daemon/src/command-center/daemon-fleet-facts-observer.ts +49 -8
  71. package/packages/daemon/src/command-center/discovery.ts +35 -2
  72. package/packages/daemon/src/command-center/server.ts +22 -8
  73. package/packages/daemon/src/command-center/tmux-server-reader.ts +62 -0
  74. package/packages/daemon/src/command-center/tmux-servers.ts +7 -1
  75. package/packages/daemon/src/doctor.ts +164 -45
  76. package/packages/daemon/src/lib/bounded-tmux-read.ts +29 -9
  77. package/packages/daemon/src/lib/cli-command.ts +16 -0
  78. package/packages/daemon/src/lib/daemon-embed.ts +176 -64
  79. package/packages/daemon/src/lib/daemon-stop-progress.ts +78 -0
  80. package/packages/daemon/src/lib/embedded-daemon-lifecycle.ts +12 -0
  81. package/packages/daemon/src/lib/embedded-tmux-server-owners.ts +115 -11
  82. package/packages/daemon/src/lib/headless-daemon.ts +205 -12
  83. package/packages/daemon/src/lib/log.ts +18 -1
  84. package/packages/daemon/src/lib/pane-reader-files.ts +294 -0
  85. package/packages/daemon/src/lib/remote-tmux-command.ts +13 -6
  86. package/packages/daemon/src/lib/tmux-client-execution.ts +79 -7
  87. package/packages/daemon/src/lib/tmux-external-interaction-observer.ts +163 -25
  88. package/packages/daemon/src/lib/tmux-native-browser.ts +4 -3
  89. package/packages/daemon/src/lib/tmux-pane-reader.ts +145 -0
  90. package/packages/daemon/src/lib/tmux-server-agent-admission.ts +6 -1
  91. package/packages/daemon/src/lib/tmux-server-features.ts +43 -0
  92. package/packages/daemon/src/lib/tmux-server-owner-teardown.ts +54 -0
  93. package/packages/daemon/src/lib/tmux-server-owner.ts +41 -35
  94. package/packages/daemon/src/lib/tmux-server-owners.ts +427 -22
  95. package/packages/daemon/src/lib/tmux-server-registration.ts +155 -7
  96. package/packages/daemon/src/lib/unix-socket-authority.ts +72 -3
  97. package/packages/daemon/src/lib/workspace-pane-creation.ts +11 -1
  98. package/packages/daemon/src/open-browser.ts +59 -18
  99. package/packages/daemon/src/open-reader.ts +148 -0
  100. package/packages/daemon/src/plugins/cli.ts +1 -2
  101. package/packages/daemon/src/plugins/daemon-plugins.ts +2 -12
  102. package/packages/daemon/src/restore.ts +80 -44
  103. package/packages/daemon/src/server/pane-stream-upgrade.ts +6 -0
  104. package/packages/daemon/src/server/websocket-heartbeat.ts +135 -0
  105. package/packages/daemon/src/terminal/attachments/native-runtime.ts +58 -14
  106. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  107. package/packages/daemon/src/terminal/mirror/layout-content-rows.ts +11 -0
  108. package/packages/daemon/src/terminal/mirror/mirror-service.ts +61 -2
  109. package/packages/daemon/src/terminal/mirror/session-channel.ts +15 -14
  110. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +140 -23
  111. package/packages/daemon/src/terminal/pane-stream/runtime.ts +4 -2
  112. package/packages/daemon/src/terminal/protocol/reader-option.ts +77 -0
  113. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +41 -1
  114. package/packages/daemon/src/terminal/protocol/stock-split-resize.ts +6 -1
  115. package/packages/daemon/src/terminal/session-runtime/registry.ts +23 -0
  116. package/packages/daemon/src/terminal/session-runtime/runtime-observability.ts +2 -0
  117. package/packages/daemon/src/terminal/session-runtime/terminal-replica-interpreter.ts +100 -3
  118. package/packages/daemon/src/terminal/session-runtime/terminal-replica-owner.ts +60 -3
  119. package/packages/daemon/src/tmux-upgrade/cli.ts +118 -0
  120. package/packages/daemon/src/tmux-upgrade/io.ts +596 -0
  121. package/packages/daemon/src/tmux-upgrade/plan.ts +353 -0
  122. package/packages/daemon/src/tmux-upgrade/run.ts +325 -0
  123. package/packages/daemon/src/tui/chrome/snapshot.ts +3 -4
  124. package/packages/daemon/src/tui/mirror/runtime/application-home-agent-navigation.ts +110 -10
  125. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +58 -6
  126. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +20 -9
  127. package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +2 -2
  128. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +149 -128
  129. package/packages/daemon-client/src/direct-application-shell-transport.ts +21 -3
  130. package/packages/daemon-client/src/workspace-event-supervisor.ts +63 -2
  131. package/packages/tmux-bridge/src/runner.ts +3 -1
@@ -0,0 +1,540 @@
1
+ /**
2
+ * The real io behind `tmux-ide servers upgrade` (#766). Every tmux call names
3
+ * its server with `-S <socket>`; nothing here reaches a server by default.
4
+ */
5
+ import { execFileSync, spawn } from "node:child_process";
6
+ import { closeSync, fsyncSync, mkdirSync, mkdtempSync, openSync, readFileSync, readlinkSync, realpathSync, renameSync, rmSync, writeFileSync, writeSync, } from "node:fs";
7
+ import { hostname, tmpdir } from "node:os";
8
+ import { dirname, join } from "node:path";
9
+ import { createInterface } from "node:readline/promises";
10
+ import { z } from "zod";
11
+ import { configureTmuxClientResolver } from "@tmux-ide/tmux-bridge";
12
+ import { restoreFleet } from "../restore.js";
13
+ import { collectFleetSnapshot, readSnapshot, resolvePaneCommand, SNAPSHOT_PANE_FORMAT, SNAPSHOT_SESSION_FORMAT, } from "../tui/chrome/snapshot.js";
14
+ import { readProcessTable } from "../tui/detect/process-tree.js";
15
+ import { isListableSession } from "../tui/team/sessions.js";
16
+ import { resolveBundledTmux, withBundledTmuxResources } from "../lib/bundled-tmux.js";
17
+ import { IdeError } from "../lib/errors.js";
18
+ import { resolveRuntimeNamespace } from "../lib/runtime-namespace.js";
19
+ import { nativeCommands, } from "../lib/tmux-server-features.js";
20
+ import { COVERAGE_PANE_FORMAT } from "./plan.js";
21
+ /** A hidden session that starts the new server before restore rebuilds into it. */
22
+ export const UPGRADE_HOLD_SESSION = "_tmux-ide-upgrade";
23
+ /**
24
+ * The socket to upgrade: `--socket-path`, `--socket-name`, then the
25
+ * TMUX_IDE_TMUX_SOCKET_PATH / _NAME environment (as doctor reads them), the
26
+ * server this shell runs in, else tmux's default socket.
27
+ */
28
+ export function targetSocket(target, environment = process.env) {
29
+ if (target.socketPath && target.socketName)
30
+ throw new IdeError("Pass --socket-path or --socket-name, not both.", {
31
+ code: "USAGE",
32
+ exitCode: 2,
33
+ });
34
+ const directory = join(environment.TMUX_TMPDIR || "/tmp", `tmux-${process.getuid?.() ?? 0}`);
35
+ if (target.socketPath)
36
+ return target.socketPath;
37
+ if (target.socketName)
38
+ return join(directory, target.socketName);
39
+ const envPath = environment.TMUX_IDE_TMUX_SOCKET_PATH?.trim();
40
+ if (envPath)
41
+ return envPath;
42
+ const envName = environment.TMUX_IDE_TMUX_SOCKET_NAME?.trim();
43
+ if (envName)
44
+ return join(directory, envName);
45
+ const inside = environment.TMUX?.split(",")[0];
46
+ if (inside)
47
+ return inside;
48
+ return join(directory, "default");
49
+ }
50
+ function sameFile(a, b) {
51
+ try {
52
+ return realpathSync(a) === realpathSync(b);
53
+ }
54
+ catch {
55
+ return a === b;
56
+ }
57
+ }
58
+ function tmux(client, socket, args) {
59
+ return execFileSync(client, ["-S", socket, ...args], {
60
+ encoding: "utf8",
61
+ stdio: ["ignore", "pipe", "pipe"],
62
+ timeout: 10_000,
63
+ env: withBundledTmuxResources(client, process.env),
64
+ });
65
+ }
66
+ function stderrOf(error) {
67
+ const failure = error;
68
+ return String(failure.stderr ?? failure.message ?? "");
69
+ }
70
+ const NO_SERVER = /no server running|error connecting|failed to connect|connection refused/u;
71
+ /**
72
+ * PURE: the executable from `lsof -a -p PID -d txt -Fn` output. The first `n`
73
+ * line of the txt descriptors is the program itself; dylibs follow.
74
+ */
75
+ export function executableFromLsof(output) {
76
+ const line = output.split("\n").find((entry) => entry.startsWith("n/"));
77
+ return line ? line.slice(1) : "";
78
+ }
79
+ /**
80
+ * PURE: a `/proc/<pid>/exe` link as a path to run. After a package upgrade
81
+ * replaced the file, Linux appends " (deleted)"; the path then names the new
82
+ * binary, which is what a fallback restore should run.
83
+ */
84
+ export function procExePath(link) {
85
+ return link.replace(/ \(deleted\)$/u, "");
86
+ }
87
+ /**
88
+ * The binary a process runs, or "" when it can't be read. `ps -o comm=` gives
89
+ * only "tmux" for a server started by its PATH name, so macOS asks lsof.
90
+ */
91
+ export function processExecutable(pid) {
92
+ try {
93
+ if (process.platform === "linux")
94
+ return procExePath(readlinkSync(`/proc/${pid}/exe`));
95
+ const lsof = executableFromLsof(execFileSync("/usr/sbin/lsof", ["-a", "-p", String(pid), "-d", "txt", "-Fn"], {
96
+ encoding: "utf8",
97
+ stdio: ["ignore", "pipe", "ignore"],
98
+ timeout: 5000,
99
+ }));
100
+ if (lsof)
101
+ return lsof;
102
+ }
103
+ catch {
104
+ // Fall through to ps.
105
+ }
106
+ try {
107
+ const comm = execFileSync("/bin/ps", ["-o", "comm=", "-p", String(pid)], {
108
+ encoding: "utf8",
109
+ stdio: ["ignore", "pipe", "ignore"],
110
+ timeout: 3000,
111
+ }).trim();
112
+ return comm.startsWith("/") ? comm : "";
113
+ }
114
+ catch {
115
+ return "";
116
+ }
117
+ }
118
+ /** PURE: tmux ends the server only when both its pid and start time still match. */
119
+ export function killGuardArgs(server) {
120
+ const guard = `#{&&:#{==:#{pid},${server.pid}},#{==:#{start_time},${server.startTime}}}`;
121
+ return ["if-shell", "-F", guard, "kill-server", "display-message -p identity-mismatch"];
122
+ }
123
+ /** PURE: what the guarded kill's output means. */
124
+ export function killOutcome(result) {
125
+ if ("stdout" in result)
126
+ return result.stdout.includes("identity-mismatch") ? "mismatch" : "ended";
127
+ // kill-server ends the server under the client; that is success.
128
+ if (NO_SERVER.test(result.stderr) || /server exited|lost server/u.test(result.stderr))
129
+ return "ended";
130
+ return { error: result.stderr.trim() || "tmux refused" };
131
+ }
132
+ /** The pids of this process and its ancestors, nearest first. */
133
+ function ancestry() {
134
+ const pids = [];
135
+ let pid = process.pid;
136
+ for (let step = 0; step < 64 && pid > 1; step++) {
137
+ pids.push(pid);
138
+ try {
139
+ pid = Number(execFileSync("/bin/ps", ["-o", "ppid=", "-p", String(pid)], {
140
+ encoding: "utf8",
141
+ stdio: ["ignore", "pipe", "ignore"],
142
+ timeout: 3000,
143
+ }).trim());
144
+ }
145
+ catch {
146
+ break;
147
+ }
148
+ if (!Number.isInteger(pid))
149
+ break;
150
+ }
151
+ return pids;
152
+ }
153
+ /**
154
+ * PURE: the pane (`session:window.pane`) whose process is this process or one
155
+ * of its ancestors, from `#{pane_pid}\t<target>` lines; null when none is.
156
+ */
157
+ export function ownPaneFrom(ancestors, lines) {
158
+ const panes = new Map(lines.map((line) => {
159
+ const [pid = "", target = ""] = line.split("\t");
160
+ return [Number(pid), target];
161
+ }));
162
+ const mine = ancestors.find((pid) => panes.has(pid));
163
+ return mine === undefined ? null : (panes.get(mine) ?? null);
164
+ }
165
+ /** Ask at a terminal. No terminal, a failed read or anything but y/yes is No. */
166
+ export async function confirmAt(question, terminal) {
167
+ if (!terminal.isTTY) {
168
+ terminal.print("No terminal to ask in. Pass --yes to go ahead. Nothing was stopped.");
169
+ return false;
170
+ }
171
+ try {
172
+ return answerIsYes(await terminal.ask(question));
173
+ }
174
+ catch {
175
+ return false;
176
+ }
177
+ }
178
+ /** PURE: the prompt's answer. Anything but y or yes, including nothing, is No. */
179
+ export function answerIsYes(answer) {
180
+ return answer !== null && /^y(es)?$/iu.test(answer.trim());
181
+ }
182
+ /** Write a new file, fsync it and its folder. Never overwrites. */
183
+ function writeDurably(path, text) {
184
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
185
+ const fd = openSync(path, "wx", 0o600);
186
+ try {
187
+ writeSync(fd, text);
188
+ fsyncSync(fd);
189
+ }
190
+ finally {
191
+ closeSync(fd);
192
+ }
193
+ try {
194
+ const dir = openSync(dirname(path), "r");
195
+ try {
196
+ fsyncSync(dir);
197
+ }
198
+ finally {
199
+ closeSync(dir);
200
+ }
201
+ }
202
+ catch {
203
+ // Some filesystems refuse a directory fsync; the file itself is synced.
204
+ }
205
+ }
206
+ /** `~/.tmux-ide/upgrades/<timestamp>`, unique per run. */
207
+ export function newUpgradeDirectory(now = new Date()) {
208
+ const stamp = now.toISOString().replace(/[:.]/gu, "-");
209
+ return join(resolveRuntimeNamespace().stateHome, "upgrades", stamp);
210
+ }
211
+ const ServerIdentitySchemaZ = z
212
+ .object({
213
+ host: z.string(),
214
+ socketPath: z.string().min(1),
215
+ pid: z.number().int().positive(),
216
+ startTime: z.number().int().nonnegative(),
217
+ version: z.string(),
218
+ executable: z.string(),
219
+ features: z.enum(["full", "stock", "older", "partial", "unknown"]),
220
+ })
221
+ .strict();
222
+ const WorkerStateSchemaZ = z
223
+ .object({
224
+ server: ServerIdentitySchemaZ,
225
+ client: z.string().min(1),
226
+ snapshotPath: z.string().min(1),
227
+ resumeAgents: z.boolean(),
228
+ })
229
+ .strict();
230
+ export function parseWorkerState(text) {
231
+ return WorkerStateSchemaZ.parse(JSON.parse(text));
232
+ }
233
+ const WorkerResultSchemaZ = z.object({
234
+ status: z.enum([
235
+ "already-full",
236
+ "preview",
237
+ "declined",
238
+ "refused",
239
+ "handed-off",
240
+ "upgraded",
241
+ "failed",
242
+ ]),
243
+ message: z.string(),
244
+ restored: z.array(z.string()).optional(),
245
+ failed: z.array(z.string()).optional(),
246
+ });
247
+ /** The worker's result, written once at the end; null while it is still running. */
248
+ export function readWorkerResult(path) {
249
+ try {
250
+ return WorkerResultSchemaZ.parse(JSON.parse(readFileSync(path, "utf8")));
251
+ }
252
+ catch {
253
+ return null;
254
+ }
255
+ }
256
+ /** Write the worker's result atomically, so the foreground never reads half a file. */
257
+ export function writeWorkerResult(path, result) {
258
+ const { status, message, restored, failed } = result;
259
+ const temporary = `${path}.${process.pid}.tmp`;
260
+ writeFileSync(temporary, JSON.stringify({ status, message, restored, failed }) + "\n", {
261
+ mode: 0o600,
262
+ });
263
+ renameSync(temporary, path);
264
+ }
265
+ function processAlive(pid) {
266
+ try {
267
+ process.kill(pid, 0);
268
+ return true;
269
+ }
270
+ catch (error) {
271
+ return error.code === "EPERM";
272
+ }
273
+ }
274
+ export function createUpgradeIo(options) {
275
+ const socket = targetSocket(options.target);
276
+ let directory = null;
277
+ const runDirectory = () => (directory ??= newUpgradeDirectory());
278
+ const print = (text) => (options.json ? console.error(text) : console.log(text));
279
+ return {
280
+ host: () => hostname(),
281
+ bundled() {
282
+ let executable;
283
+ try {
284
+ executable = resolveBundledTmux();
285
+ }
286
+ catch (error) {
287
+ throw new IdeError(`tmux-ide's own tmux is damaged (${error.message}). Reinstall tmux-ide. Nothing was stopped.`, { code: "BUNDLED_TMUX_INVALID", exitCode: 1 });
288
+ }
289
+ if (!executable)
290
+ return null;
291
+ const version = execFileSync(executable, ["-V"], {
292
+ encoding: "utf8",
293
+ timeout: 3000,
294
+ env: withBundledTmuxResources(executable, process.env),
295
+ })
296
+ .trim()
297
+ .replace(/^tmux\s+/u, "");
298
+ return { executable, version };
299
+ },
300
+ configuredBinary: () => process.env.TMUX_IDE_TMUX_BIN || undefined,
301
+ identify(client) {
302
+ let line;
303
+ try {
304
+ line =
305
+ tmux(client, socket, [
306
+ "list-sessions",
307
+ "-F",
308
+ "#{socket_path}\t#{pid}\t#{start_time}\t#{version}",
309
+ ]).split("\n")[0] ?? "";
310
+ }
311
+ catch (error) {
312
+ if (NO_SERVER.test(stderrOf(error)))
313
+ return null;
314
+ throw new IdeError(`Could not read the server at ${socket}: ${stderrOf(error).trim()}`, {
315
+ code: "SERVER_UNREADABLE",
316
+ exitCode: 1,
317
+ });
318
+ }
319
+ const [socketPath = "", pid = "", startTime = "", version = ""] = line.split("\t");
320
+ if (!/^\d+$/u.test(pid) || !/^\d+$/u.test(startTime))
321
+ return null;
322
+ return {
323
+ socketPath: socketPath || socket,
324
+ pid: Number(pid),
325
+ startTime: Number(startTime),
326
+ version,
327
+ executable: processExecutable(Number(pid)),
328
+ };
329
+ },
330
+ features(client, at) {
331
+ const probe = (args) => tmux(client, at, args);
332
+ const answer = nativeCommands(probe);
333
+ return answer === "no-server" ? "unknown" : answer;
334
+ },
335
+ scratchFeatures(client) {
336
+ const scratch = mkdtempSync(join(tmpdir(), "tmi-upgrade-"));
337
+ const at = join(scratch, "s");
338
+ const run = (args) => execFileSync(client, ["-S", at, "-f", "/dev/null", ...args], {
339
+ encoding: "utf8",
340
+ stdio: ["ignore", "pipe", "pipe"],
341
+ timeout: 5000,
342
+ env: withBundledTmuxResources(client, process.env),
343
+ });
344
+ try {
345
+ run(["new-session", "-d", "-s", "probe"]);
346
+ const answer = nativeCommands(run);
347
+ return answer === "no-server" ? "unknown" : answer;
348
+ }
349
+ catch {
350
+ return "unknown";
351
+ }
352
+ finally {
353
+ try {
354
+ run(["kill-server"]);
355
+ }
356
+ catch {
357
+ // Already gone.
358
+ }
359
+ rmSync(scratch, { recursive: true, force: true });
360
+ }
361
+ },
362
+ endingPanes(client, at) {
363
+ const table = readProcessTable();
364
+ return tmux(client, at, ["list-panes", "-a", "-F", SNAPSHOT_PANE_FORMAT])
365
+ .split("\n")
366
+ .filter(Boolean)
367
+ .flatMap((line) => {
368
+ const [session = "", window = "", , , , pane = "", cwd = "", cmd = "", pid = "0", , , hint = "",] = line.split("\t");
369
+ // tmux-ide's own hidden sessions (updater, app host) hold no user work.
370
+ if (isListableSession(session) || session.startsWith("_tmux-ide"))
371
+ return [];
372
+ const { agent, command } = resolvePaneCommand(cmd, Number(pid) || 0, hint, table);
373
+ return [{ target: `${session}:${window}.${pane}`, cwd, agent, command }];
374
+ });
375
+ },
376
+ listPanes: (client, at) => tmux(client, at, ["list-panes", "-a", "-F", COVERAGE_PANE_FORMAT])
377
+ .split("\n")
378
+ .filter(Boolean),
379
+ collect: (client, at) =>
380
+ // Strict: any tmux error throws, so a partial listing never becomes the snapshot.
381
+ collectFleetSnapshot({
382
+ listPanes: () => tmux(client, at, ["list-panes", "-a", "-F", SNAPSHOT_PANE_FORMAT]),
383
+ listSessions: () => tmux(client, at, ["list-sessions", "-F", SNAPSHOT_SESSION_FORMAT]),
384
+ processTable: () => readProcessTable(),
385
+ }),
386
+ saveSnapshot(snapshot) {
387
+ const path = join(runDirectory(), "snapshot.json");
388
+ writeDurably(path, JSON.stringify(snapshot, null, 2) + "\n");
389
+ return path;
390
+ },
391
+ loadSnapshot: (path) => readSnapshot(path),
392
+ ownPane(client, at) {
393
+ let lines;
394
+ try {
395
+ lines = tmux(client, at, [
396
+ "list-panes",
397
+ "-a",
398
+ "-F",
399
+ "#{pane_pid}\t#{session_name}:#{window_index}.#{pane_index}",
400
+ ])
401
+ .split("\n")
402
+ .filter(Boolean);
403
+ }
404
+ catch {
405
+ return null;
406
+ }
407
+ return ownPaneFrom(ancestry(), lines);
408
+ },
409
+ insideTarget(client, at) {
410
+ const inside = process.env.TMUX?.split(",")[0];
411
+ if (inside && sameFile(inside, at))
412
+ return true;
413
+ // $TMUX can be unset or wrong; the process tree can't.
414
+ return this.ownPane(client, at) !== null;
415
+ },
416
+ confirm: (question) => confirmAt(question, {
417
+ isTTY: Boolean(process.stdin.isTTY),
418
+ print,
419
+ ask: async (text) => {
420
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
421
+ try {
422
+ return await prompt.question(text);
423
+ }
424
+ finally {
425
+ prompt.close();
426
+ }
427
+ },
428
+ }),
429
+ startWorker(work) {
430
+ const folder = runDirectory();
431
+ const statePath = join(folder, "worker.json");
432
+ writeDurably(statePath, JSON.stringify(work, null, 2) + "\n");
433
+ const log = join(folder, "log");
434
+ const resultPath = join(folder, "result.json");
435
+ const fd = openSync(log, "a", 0o600);
436
+ let pid;
437
+ try {
438
+ const child = spawn(process.execPath, [options.cliEntry, "servers", "upgrade", "--continue", statePath],
439
+ // A session of its own and no terminal: a closing pane, a hangup or
440
+ // Ctrl-C in the foreground does not reach it.
441
+ { detached: true, stdio: ["ignore", fd, fd], env: process.env });
442
+ child.unref();
443
+ if (!child.pid)
444
+ throw new Error("the background worker did not start");
445
+ pid = child.pid;
446
+ }
447
+ finally {
448
+ closeSync(fd);
449
+ }
450
+ return { log, resultPath, pid };
451
+ },
452
+ async waitForWorker(handle) {
453
+ const note = () => print(`\nThe restart continues in the background. Log: ${handle.log}`);
454
+ const onSignal = () => {
455
+ note();
456
+ process.exit(130);
457
+ };
458
+ process.once("SIGINT", onSignal);
459
+ process.once("SIGTERM", onSignal);
460
+ try {
461
+ const deadline = Date.now() + 10 * 60_000;
462
+ for (;;) {
463
+ const result = readWorkerResult(handle.resultPath);
464
+ if (result)
465
+ return result;
466
+ if (!processAlive(handle.pid) || Date.now() > deadline) {
467
+ // One last look: it may have written the result just before it exited.
468
+ return readWorkerResult(handle.resultPath);
469
+ }
470
+ await new Promise((resolve) => setTimeout(resolve, 200));
471
+ }
472
+ }
473
+ finally {
474
+ process.off("SIGINT", onSignal);
475
+ process.off("SIGTERM", onSignal);
476
+ }
477
+ },
478
+ kill(client, server) {
479
+ // tmux checks the identity itself, so a newer server on the socket is never ended.
480
+ let outcome;
481
+ try {
482
+ outcome = killOutcome({ stdout: tmux(client, server.socketPath, killGuardArgs(server)) });
483
+ }
484
+ catch (error) {
485
+ outcome = killOutcome({ stderr: stderrOf(error) });
486
+ }
487
+ if (outcome === "mismatch")
488
+ throw new Error("another server now answers on that socket");
489
+ if (typeof outcome === "object")
490
+ throw new Error(outcome.error);
491
+ },
492
+ serverGone(client, at) {
493
+ const deadline = Date.now() + 5000;
494
+ for (;;) {
495
+ try {
496
+ tmux(client, at, ["list-sessions", "-F", "#{pid}"]);
497
+ }
498
+ catch (error) {
499
+ if (NO_SERVER.test(stderrOf(error)))
500
+ return true;
501
+ }
502
+ if (Date.now() > deadline)
503
+ return false;
504
+ execFileSync("/bin/sleep", ["0.1"]);
505
+ }
506
+ },
507
+ async restore({ client, socket: at, snapshotPath, resumeAgents }) {
508
+ const environment = withBundledTmuxResources(client, process.env);
509
+ // Every runTmux in restore goes to this binary and this socket.
510
+ const release = configureTmuxClientResolver(() => ({
511
+ executable: client,
512
+ environment,
513
+ globalArgs: ["-S", at],
514
+ }));
515
+ try {
516
+ // Start the server explicitly, so a binary that can't start one throws here
517
+ // instead of failing each session one by one.
518
+ tmux(client, at, ["new-session", "-d", "-s", UPGRADE_HOLD_SESSION]);
519
+ const outcome = await restoreFleet({
520
+ from: snapshotPath,
521
+ snapshotOnly: true,
522
+ resumeAgents,
523
+ resumeFromConfig: false,
524
+ });
525
+ return { restored: outcome.restored, failed: outcome.failed };
526
+ }
527
+ finally {
528
+ release();
529
+ try {
530
+ tmux(client, at, ["kill-session", "-t", `=${UPGRADE_HOLD_SESSION}`]);
531
+ }
532
+ catch {
533
+ // Never started, or already gone.
534
+ }
535
+ }
536
+ },
537
+ print,
538
+ nowSec: () => Math.floor(Date.now() / 1000),
539
+ };
540
+ }