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
@@ -4,7 +4,34 @@ import { canonicalDaemonUrl, matchesCanonicalDaemonPredecessor, getCanonicalDaem
4
4
  import { DAEMON_WIRE_PROTOCOL_VERSION, isDaemonWireProtocolCompatible, } from "@tmux-ide/contracts";
5
5
  import { startEmbeddedDaemon, } from "./daemon-embed.js";
6
6
  import { DaemonStartupError, IdeError } from "./errors.js";
7
+ import { logger, reserveStdoutForProtocol } from "./log.js";
7
8
  import { generateAuthToken } from "./auth-token.js";
9
+ /**
10
+ * A SIGTERM or SIGINT is a promise to the supervisor that this process ends.
11
+ * A teardown that has not finished by then is abandoned: the daemon says what
12
+ * was still open, withdraws daemon.json and exits non-zero (#839).
13
+ */
14
+ export const SIGNAL_STOP_DEADLINE_MS = 10_000;
15
+ /**
16
+ * A slow stop that still completes teardown steps is not hung: the deadline
17
+ * above counts from the last step that settled, and this bounds the whole
18
+ * stop. So a teardown that hangs exits 10 s after its last progress, and one
19
+ * that keeps moving exits at 25 s at the latest. That stays under the 30 s the
20
+ * launchd and systemd units grant before they kill the process themselves.
21
+ */
22
+ export const SIGNAL_STOP_MAX_MS = 25_000;
23
+ export const SIGNAL_STOP_TIMEOUT_EXIT_CODE = 1;
24
+ function activeResourceCounts() {
25
+ const counts = {};
26
+ try {
27
+ for (const name of process.getActiveResourcesInfo())
28
+ counts[name] = (counts[name] ?? 0) + 1;
29
+ }
30
+ catch {
31
+ /* Diagnostics only. */
32
+ }
33
+ return counts;
34
+ }
8
35
  const defaultDependencies = {
9
36
  inspectCanonicalDaemonInfo: prepareCanonicalDaemonInfoForBootstrap,
10
37
  isCanonicalDaemonAlive,
@@ -190,7 +217,11 @@ export async function runHeadlessDaemon(options = {}, deps = defaultDependencies
190
217
  tmuxServerIntent: options.tmuxServerIntent === undefined ? resolveTmuxServerIntent() : options.tmuxServerIntent,
191
218
  };
192
219
  let restoreTmuxWorkspaces = false;
193
- const lifecycle = {};
220
+ // With --json, stdout is the status document for whoever started the
221
+ // daemon; log records, also warnings and "stream closed", go to stderr.
222
+ if (options.json === true)
223
+ reserveStdoutForProtocol();
224
+ const lifecycle = { generations: 0, startReason: "initial" };
194
225
  while (true) {
195
226
  const result = await runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces, lifecycle);
196
227
  if (result !== "restart")
@@ -199,19 +230,111 @@ export async function runHeadlessDaemon(options = {}, deps = defaultDependencies
199
230
  }
200
231
  }
201
232
  async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces, lifecycle) {
202
- const port = parsePort(lifecycle.restart?.port ?? options.port);
233
+ const requestedPort = parsePort(lifecycle.restart?.port ?? options.port);
234
+ // Nobody asked for a port: prefer the one the previous generation had.
235
+ let port = requestedPort ?? lifecycle.lastPort;
236
+ const generation = (lifecycle.generations += 1);
237
+ const startReason = lifecycle.startReason;
238
+ const generationStartedAt = performance.now();
203
239
  let restartRequested = false;
204
240
  let stopStarted = false;
205
241
  let handle = null;
206
242
  let signalRequested = false;
207
- const requestStop = () => {
243
+ /** What asked this generation to retire; logged with the timings. */
244
+ let retireTrigger = null;
245
+ const deadlineMs = deps.signalStopDeadlineMs ?? SIGNAL_STOP_DEADLINE_MS;
246
+ let deadlineTimer = null;
247
+ let rejectDeadline;
248
+ const deadlineExceeded = new Promise((_resolve, reject) => {
249
+ rejectDeadline = reject;
250
+ });
251
+ deadlineExceeded.catch(() => undefined);
252
+ const maxMs = Math.max(deadlineMs, deps.signalStopMaxMs ?? SIGNAL_STOP_MAX_MS);
253
+ let signalledAt = 0;
254
+ let lastProgress = "";
255
+ let lastProgressAt = 0;
256
+ const readStop = () => {
257
+ try {
258
+ return handle?.stopDiagnostics?.() ?? null;
259
+ }
260
+ catch {
261
+ return null; // Diagnostics never block the exit.
262
+ }
263
+ };
264
+ const progressOf = (stop) => stop ? `${stop.completed.length}:${stop.stepsSettled}` : "";
265
+ const abandonStop = (signal, stop) => {
266
+ const now = performance.now();
267
+ logger.error("daemon-lifecycle", "stop missed the signal deadline; exiting anyway", {
268
+ signal,
269
+ trigger: retireTrigger,
270
+ deadlineMs,
271
+ maxMs,
272
+ waitedMs: Math.round(now - signalledAt),
273
+ sinceLastProgressMs: Math.round(now - lastProgressAt),
274
+ generation,
275
+ startReason,
276
+ generationInstanceId: handle?.instanceId ?? null,
277
+ phase: !handle ? "starting" : stopStarted ? "stopping" : "running",
278
+ stuckStage: stop?.stage ?? null,
279
+ stuckStageMs: stop?.stageMs ?? null,
280
+ openSteps: stop?.openSteps ?? [],
281
+ stepsSettled: stop?.stepsSettled ?? 0,
282
+ completedStages: stop?.completed ?? [],
283
+ activeResources: activeResourceCounts(),
284
+ });
285
+ try {
286
+ handle?.abandon?.();
287
+ }
288
+ catch {
289
+ /* The exit below still ends the owner. */
290
+ }
291
+ (deps.exit ?? ((code) => process.exit(code)))(SIGNAL_STOP_TIMEOUT_EXIT_CODE);
292
+ rejectDeadline(new IdeError(`Daemon stop did not finish within its deadline after ${signal}`, {
293
+ code: "DAEMON_STOP_TIMEOUT",
294
+ exitCode: SIGNAL_STOP_TIMEOUT_EXIT_CODE,
295
+ }));
296
+ };
297
+ /** Looked at a few times per deadline: has the teardown moved, and how long has it been? */
298
+ const watchStop = (signal) => {
299
+ const stop = readStop();
300
+ const now = performance.now();
301
+ const progress = progressOf(stop);
302
+ if (progress !== lastProgress) {
303
+ lastProgress = progress;
304
+ lastProgressAt = now;
305
+ }
306
+ if (now - lastProgressAt < deadlineMs && now - signalledAt < maxMs)
307
+ return;
308
+ if (deadlineTimer)
309
+ clearInterval(deadlineTimer);
310
+ abandonStop(signal, stop);
311
+ };
312
+ /**
313
+ * Start the watch over a stop. A signal starts it, and so does a restart in
314
+ * place: a restart whose teardown hangs would otherwise leave a process that
315
+ * serves nothing and waits for ever, with no signal to end it.
316
+ * Armed once; repeating the signal buys no time.
317
+ */
318
+ const watchThisStop = (cause) => {
319
+ if (deadlineTimer)
320
+ return;
321
+ signalledAt = lastProgressAt = performance.now();
322
+ lastProgress = progressOf(readStop());
323
+ // Deliberately not unref'd: a hung teardown must not outlive the deadline.
324
+ deadlineTimer = setInterval(() => watchStop(cause), Math.max(1, Math.min(1_000, Math.floor(deadlineMs / 8))));
325
+ };
326
+ const requestStop = (signal) => {
208
327
  signalRequested = true;
328
+ retireTrigger ??= `signal:${signal}`;
329
+ watchThisStop(signal);
209
330
  if (handle)
210
331
  void handle.stop().catch(() => undefined);
211
332
  };
212
- deps.onSignal("SIGINT", requestStop);
213
- deps.onSignal("SIGTERM", requestStop);
214
- try {
333
+ const onSigint = () => requestStop("SIGINT");
334
+ const onSigterm = () => requestStop("SIGTERM");
335
+ deps.onSignal("SIGINT", onSigint);
336
+ deps.onSignal("SIGTERM", onSigterm);
337
+ const runGeneration = async () => {
215
338
  let existing;
216
339
  try {
217
340
  existing = await findLiveCanonicalDaemon(deps, options, lifecycle.predecessor);
@@ -256,6 +379,8 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
256
379
  return;
257
380
  lifecycle.restart = request;
258
381
  restartRequested = true;
382
+ retireTrigger ??= `restart-request:${"kind" in request ? request.kind : "settings"}`;
383
+ watchThisStop("restart");
259
384
  await handle.stop();
260
385
  },
261
386
  localBypassToken: generateAuthToken(),
@@ -265,6 +390,19 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
265
390
  });
266
391
  }
267
392
  catch (error) {
393
+ // The remembered port is a preference, not a requirement: if the new
394
+ // generation cannot start on it, it starts on a free one as before.
395
+ if (requestedPort === undefined && port !== undefined) {
396
+ logger.warn("daemon-lifecycle", "could not keep the previous port; picking a free one", {
397
+ generation,
398
+ port,
399
+ error: error instanceof Error ? error.message.slice(0, 200) : String(error),
400
+ });
401
+ port = undefined;
402
+ lifecycle.lastPort = undefined;
403
+ startAttempt -= 1;
404
+ continue;
405
+ }
268
406
  // Another process may hold the complete startup claim before its
269
407
  // daemon.json and endpoints are visible. Wait for that exact winner;
270
408
  // if it dies before publication, retry the claim once.
@@ -296,9 +434,19 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
296
434
  const originalStop = handle.stop.bind(handle);
297
435
  const mutableHandle = handle;
298
436
  mutableHandle.stop = async (stopOptions) => {
437
+ if (!stopStarted) {
438
+ retireTrigger ??= "stop-requested";
439
+ // An ordinary stop is routine (debug); an in-place restart is not (info).
440
+ logger[restartRequested && !signalRequested ? "info" : "debug"]("daemon-lifecycle", "generation retiring", {
441
+ generation,
442
+ generationInstanceId: handle?.instanceId ?? null,
443
+ trigger: retireTrigger,
444
+ uptimeMs: Math.round(performance.now() - generationStartedAt),
445
+ });
446
+ }
299
447
  stopStarted = true;
300
448
  try {
301
- await originalStop(stopOptions);
449
+ await originalStop(restartRequested && !signalRequested ? { ...stopOptions, restarting: true } : stopOptions);
302
450
  if (restartRequested && !signalRequested && options.supervisionId && ownedPublication)
303
451
  lifecycle.predecessor = ownedPublication;
304
452
  }
@@ -359,7 +507,16 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
359
507
  }
360
508
  throw error;
361
509
  }
510
+ lifecycle.lastPort = info.port;
362
511
  emitStatus(deps, options.json === true, "ready", info);
512
+ // The first generation already says so with its status line on stdout.
513
+ logger[generation > 1 ? "info" : "debug"]("daemon-lifecycle", "generation ready", {
514
+ generation,
515
+ startReason,
516
+ generationInstanceId: info.instanceId,
517
+ port: info.port,
518
+ startMs: Math.round(performance.now() - generationStartedAt),
519
+ });
363
520
  let probing = false;
364
521
  const timer = handle.tmuxAuthorityReplaced
365
522
  ? setInterval(() => {
@@ -371,6 +528,8 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
371
528
  if (!replaced || stopStarted || signalRequested)
372
529
  return;
373
530
  restartRequested = true;
531
+ retireTrigger ??= "tmux-authority-replaced";
532
+ watchThisStop("restart");
374
533
  return handle.stop();
375
534
  })
376
535
  .catch(() => undefined)
@@ -389,10 +548,18 @@ async function runHeadlessDaemonGeneration(options, deps, restoreTmuxWorkspaces,
389
548
  }
390
549
  if (stopFailure)
391
550
  throw stopFailure;
392
- return restartRequested && !signalRequested ? "restart" : "stopped";
551
+ const outcome = restartRequested && !signalRequested ? "restart" : "stopped";
552
+ if (outcome === "restart")
553
+ lifecycle.startReason = retireTrigger ?? "restart";
554
+ return outcome;
555
+ };
556
+ try {
557
+ return await Promise.race([runGeneration(), deadlineExceeded]);
393
558
  }
394
559
  finally {
395
- deps.offSignal("SIGINT", requestStop);
396
- deps.offSignal("SIGTERM", requestStop);
560
+ if (deadlineTimer)
561
+ clearInterval(deadlineTimer);
562
+ deps.offSignal("SIGINT", onSigint);
563
+ deps.offSignal("SIGTERM", onSigterm);
397
564
  }
398
565
  }
@@ -29,8 +29,21 @@ export function registerLogSecret(secret) {
29
29
  if (typeof secret === "string" && secret.length >= 8)
30
30
  secrets.add(secret);
31
31
  }
32
+ /**
33
+ * Where records below error level go. stdout by default (the service log).
34
+ * A process whose stdout is a protocol, like `tmux-ide --headless --json`
35
+ * with its one status line, reserves it: every record then goes to stderr.
36
+ */
37
+ let recordStream = "stdout";
38
+ export function reserveStdoutForProtocol() {
39
+ recordStream = "stderr";
40
+ }
41
+ export function structuredLogStream() {
42
+ return recordStream;
43
+ }
32
44
  /** @internal test seam */
33
45
  export function _resetLogStateForTests() {
46
+ recordStream = "stdout";
34
47
  identity = {};
35
48
  secrets.clear();
36
49
  logBuffer.length = 0;
@@ -91,6 +104,10 @@ function markStreamFailed(name, error) {
91
104
  const other = name === "stdout" ? "stderr" : "stdout";
92
105
  // The fallback can fail asynchronously too. Install the same error handling
93
106
  // before writing it; failed flags prevent a warning loop if both streams fail.
107
+ // A reserved stdout carries a protocol: the warning about a failed stderr
108
+ // has nowhere to go then, and the records stay in the ring.
109
+ if (other === "stdout" && recordStream === "stderr")
110
+ return;
94
111
  if (!streamState[other].failed)
95
112
  writeToStream(other, warning);
96
113
  }
@@ -164,7 +181,7 @@ function writeStructuredLog(level, component, message, data) {
164
181
  };
165
182
  if (payload.renamedKeys.length > 0)
166
183
  wire.reservedKeysRenamed = payload.renamedKeys;
167
- writeToStream(level === "error" ? "stderr" : "stdout", JSON.stringify(wire) + "\n");
184
+ writeToStream(level === "error" ? "stderr" : recordStream, JSON.stringify(wire) + "\n");
168
185
  }
169
186
  export const logger = {
170
187
  debug: (component, msg, data) => writeStructuredLog("debug", component, msg, data),
@@ -0,0 +1,226 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync, statSync, } from "node:fs";
3
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { PANE_READER_ASSET_MAX_BYTES, PANE_READER_MAX_BYTES, PANE_READER_PAGE_BYTES, hasControlCharacter, } from "@tmux-ide/contracts";
5
+ import { isMarkdownPath } from "../terminal/protocol/reader-option.js";
6
+ const IMAGE_MIME = {
7
+ ".png": "image/png",
8
+ ".jpg": "image/jpeg",
9
+ ".jpeg": "image/jpeg",
10
+ ".gif": "image/gif",
11
+ ".webp": "image/webp",
12
+ ".svg": "image/svg+xml",
13
+ };
14
+ function revisionOf(stat) {
15
+ return createHash("sha256")
16
+ .update(`${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`)
17
+ .digest("hex")
18
+ .slice(0, 32);
19
+ }
20
+ function missingError(error) {
21
+ const code = error?.code;
22
+ return code === "ENOENT" || code === "ENOTDIR" || code === "ELOOP" || code === "EISDIR";
23
+ }
24
+ function realpathOrNull(path) {
25
+ try {
26
+ return realpathSync(path);
27
+ }
28
+ catch (error) {
29
+ if (missingError(error))
30
+ return null;
31
+ throw error;
32
+ }
33
+ }
34
+ /** Equal to or below `root`, compared by path segments rather than by string prefix. */
35
+ export function isInside(root, path) {
36
+ const rel = relative(root, path);
37
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
38
+ }
39
+ /** The nearest ancestor of `directory` holding a `.git` entry; no git process is run. */
40
+ export function gitRoot(directory) {
41
+ for (let current = directory;;) {
42
+ try {
43
+ lstatSync(join(current, ".git"));
44
+ return current;
45
+ }
46
+ catch {
47
+ /* keep walking up */
48
+ }
49
+ const parent = dirname(current);
50
+ if (parent === current)
51
+ return null;
52
+ current = parent;
53
+ }
54
+ }
55
+ const NO_SEAMS = Object.freeze({});
56
+ /**
57
+ * Opens `real` (already resolved) without following a swapped-in final
58
+ * symlink, and only as a regular file. Then proves the descriptor is still the
59
+ * file at that real path: a fresh stat of the path, following every symlink on
60
+ * it, names the same device and inode as the open descriptor. A path or a
61
+ * folder on it swapped between resolving and opening is refused ("swapped").
62
+ * No separate realpath check is needed: whatever the path now resolves to,
63
+ * the stat proves the open file is the one it leads to.
64
+ */
65
+ function openRegular(real, seams) {
66
+ let fd;
67
+ try {
68
+ fd = openSync(real, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
69
+ }
70
+ catch (error) {
71
+ if (missingError(error))
72
+ return null;
73
+ throw error;
74
+ }
75
+ const stat = fstatSync(fd, { bigint: true });
76
+ if (!stat.isFile()) {
77
+ closeSync(fd);
78
+ return null;
79
+ }
80
+ seams.afterOpen?.();
81
+ let now = null;
82
+ try {
83
+ now = statSync(real, { bigint: true });
84
+ }
85
+ catch (error) {
86
+ if (!missingError(error)) {
87
+ closeSync(fd);
88
+ throw error;
89
+ }
90
+ }
91
+ if (!now || now.dev !== stat.dev || now.ino !== stat.ino) {
92
+ closeSync(fd);
93
+ return "swapped";
94
+ }
95
+ return { fd, stat };
96
+ }
97
+ function readChunk(fd, offset, size) {
98
+ const length = Math.max(0, Math.min(PANE_READER_PAGE_BYTES, size - offset));
99
+ const buffer = Buffer.alloc(length);
100
+ let done = 0;
101
+ while (done < length) {
102
+ const read = readSync(fd, buffer, done, length - done, offset + done);
103
+ if (read === 0)
104
+ break;
105
+ done += read;
106
+ }
107
+ return buffer.subarray(0, done);
108
+ }
109
+ /** One page of `opened`, re-checking after the read that the file did not change. */
110
+ function page(opened, limit, have, request, seams) {
111
+ const revision = revisionOf(opened.stat);
112
+ const size = Number(opened.stat.size);
113
+ if (size > limit)
114
+ return { state: "too_large", revision, size };
115
+ if (request) {
116
+ if (request.revision !== revision || request.offset > size)
117
+ return { state: "changed" };
118
+ }
119
+ else if (have === revision)
120
+ return { state: "unchanged", revision };
121
+ const offset = request?.offset ?? 0;
122
+ const bytes = seams.read
123
+ ? seams.read(opened.fd, offset, size, readChunk)
124
+ : readChunk(opened.fd, offset, size);
125
+ const after = fstatSync(opened.fd, { bigint: true });
126
+ if (revisionOf(after) !== revision ||
127
+ bytes.length !== Math.min(PANE_READER_PAGE_BYTES, size - offset))
128
+ return { state: "changed" };
129
+ return { state: "ok", revision, size, offset, chunk: bytes.toString("base64") };
130
+ }
131
+ /** A page of the Markdown file at `path`; its real path must still be Markdown. */
132
+ export function readReaderPage(path, have, request, seams = NO_SEAMS) {
133
+ // A whole-file read retries once if the file changed underneath it.
134
+ for (let attempt = 0;; attempt++) {
135
+ const real = realpathOrNull(path);
136
+ if (!real || !isMarkdownPath(real))
137
+ return { state: "missing" };
138
+ const opened = openRegular(real, seams);
139
+ if (!opened || opened === "swapped") {
140
+ // A document swapped mid-open reads again once, then reports changed.
141
+ if (opened === "swapped" && !request && attempt === 0)
142
+ continue;
143
+ return opened === "swapped" ? { state: "changed" } : { state: "missing" };
144
+ }
145
+ try {
146
+ const result = page(opened, PANE_READER_MAX_BYTES, have, request, seams);
147
+ if (result.state !== "changed" || request || attempt > 0)
148
+ return result;
149
+ }
150
+ finally {
151
+ closeSync(opened.fd);
152
+ }
153
+ }
154
+ }
155
+ const SCHEME = /^[a-z][a-z0-9+.-]*:/iu;
156
+ /** The decoded relative path `src` names, or null when the reader must not follow it. */
157
+ export function localImageReference(src) {
158
+ if (src.includes("\0") || SCHEME.test(src) || src.startsWith("//") || src.startsWith("\\"))
159
+ return null;
160
+ const bare = src.split(/[?#]/u, 1)[0] ?? "";
161
+ let decoded;
162
+ try {
163
+ decoded = decodeURIComponent(bare);
164
+ }
165
+ catch {
166
+ return null;
167
+ }
168
+ if (!decoded ||
169
+ hasControlCharacter(decoded) ||
170
+ decoded.startsWith("/") ||
171
+ decoded.startsWith("~") ||
172
+ decoded.startsWith("\\") ||
173
+ isAbsolute(decoded))
174
+ return null;
175
+ return decoded;
176
+ }
177
+ function imageMime(path) {
178
+ return IMAGE_MIME[extname(path).toLowerCase()] ?? null;
179
+ }
180
+ /**
181
+ * A page of the image `src` names, relative to the Markdown file at `markdown`.
182
+ * Allowed only inside the file's git repository, or its folder when there is
183
+ * none, after every symlink is resolved.
184
+ */
185
+ export function readReaderAssetPage(markdown, src, request, seams = NO_SEAMS) {
186
+ const reference = localImageReference(src);
187
+ if (reference === null)
188
+ return { state: "refused" };
189
+ const document = realpathOrNull(markdown);
190
+ if (!document || !isMarkdownPath(document))
191
+ return { state: "missing" };
192
+ const base = dirname(document);
193
+ const root = gitRoot(base) ?? base;
194
+ const candidate = resolve(base, reference);
195
+ // Refuse outside paths before touching the file system, so the answer never
196
+ // says whether a file outside the root exists.
197
+ if (!isInside(root, candidate) || !imageMime(candidate))
198
+ return { state: "refused" };
199
+ const real = realpathOrNull(candidate);
200
+ if (!real)
201
+ return { state: "missing" };
202
+ const mime = imageMime(real);
203
+ if (!isInside(root, real) || !mime)
204
+ return { state: "refused" };
205
+ const opened = openRegular(real, seams);
206
+ if (opened === "swapped")
207
+ return { state: "refused" };
208
+ if (!opened)
209
+ return { state: "missing" };
210
+ try {
211
+ // The name as written must still lead to the file that was opened.
212
+ if (realpathOrNull(candidate) !== real)
213
+ return { state: "refused" };
214
+ const result = page(opened, PANE_READER_ASSET_MAX_BYTES, null, request, seams);
215
+ if (result.state === "unchanged")
216
+ return { state: "changed" };
217
+ if (result.state === "too_large")
218
+ return { state: "too_large" };
219
+ if (result.state === "changed")
220
+ return result;
221
+ return { ...result, mime };
222
+ }
223
+ finally {
224
+ closeSync(opened.fd);
225
+ }
226
+ }
@@ -1,10 +1,13 @@
1
1
  import { shellEscape } from "./shell.js";
2
+ // Respect the host's existing installation preference, then try the installer
3
+ // and common package-manager prefixes. Never source shell profiles.
4
+ const REMOTE_PATH = 'export PATH="${PATH:-/usr/bin:/bin}:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/home/linuxbrew/.linuxbrew/bin:$HOME/.npm-global/bin"; ';
2
5
  /** Fixed commands only. SSH normally omits interactive shell PATH setup. */
3
6
  export function remoteTmuxIdeCommand(operation) {
4
- const args = operation === "discover" ? "remote-daemon-info --json" : "update --daemon --json";
5
- // Respect the host's existing installation preference, then try the installer
6
- // and common package-manager prefixes. Never source shell profiles.
7
- const script = 'export PATH="${PATH:-/usr/bin:/bin}:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/home/linuxbrew/.linuxbrew/bin:$HOME/.npm-global/bin"; ' +
8
- `exec tmux-ide ${args}`;
7
+ return remoteTmuxIdeArgsCommand(operation === "discover" ? ["remote-daemon-info", "--json"] : ["update", "--daemon", "--json"]);
8
+ }
9
+ /** `tmux-ide <args…>` on a remote host, each argument quoted for its shell. */
10
+ export function remoteTmuxIdeArgsCommand(args) {
11
+ const script = REMOTE_PATH + `exec tmux-ide ${args.map(shellEscape).join(" ")}`;
9
12
  return `/bin/sh -c ${shellEscape(script)}`;
10
13
  }
@@ -1,3 +1,4 @@
1
+ import { execFileSync } from "node:child_process";
1
2
  import { fileURLToPath } from "node:url";
2
3
  import { accessSync, constants, realpathSync, statSync } from "node:fs";
3
4
  import { delimiter, isAbsolute, join, resolve } from "node:path";
@@ -58,9 +59,78 @@ export function tmuxClientEnvironment(source, executable) {
58
59
  }
59
60
  return { ...environment, ...bundledTmuxResourceEnvironment(executable) };
60
61
  }
61
- /** Ordinary CLI commands retain PATH selection; bundled tmux fills a missing system client. */
62
- export function resolveOrdinaryTmuxClient(environment, cwd) {
62
+ /**
63
+ * The socket an ordinary tmux client reaches, or null inside tmux (where the
64
+ * server exists by definition). Ordinary clients pass no -S or -L in
65
+ * production, so this is tmux's own rule: $TMUX, else the default socket.
66
+ */
67
+ export function ordinaryTargetSocket(environment) {
68
+ if (environment.TMUX)
69
+ return null;
70
+ const uid = process.getuid?.() ?? 0;
71
+ return join(environment.TMUX_TMPDIR || "/tmp", `tmux-${uid}`, "default");
72
+ }
73
+ const answering = new Set();
74
+ /**
75
+ * Does a server answer on this socket? A socket file alone is not enough: a
76
+ * server that crashed leaves one behind. `probe` asks with `list-sessions`,
77
+ * which never starts a server. A running server is remembered for the process.
78
+ */
79
+ export function serverAnswers(socket, probe) {
80
+ if (answering.has(socket))
81
+ return true;
82
+ try {
83
+ if (!statSync(socket).isSocket())
84
+ return false;
85
+ }
86
+ catch {
87
+ return false;
88
+ }
89
+ try {
90
+ execFileSync(probe, ["-S", socket, "list-sessions", "-F", "#{pid}"], {
91
+ stdio: ["ignore", "ignore", "pipe"],
92
+ timeout: 3000,
93
+ env: withBundledTmuxResources(probe, process.env),
94
+ });
95
+ }
96
+ catch (error) {
97
+ const stderr = String(error.stderr ?? "");
98
+ // A refused connection is a stale socket. Anything else (a protocol
99
+ // mismatch, a timeout) means something is there: keep the PATH client.
100
+ if (/no server running|error connecting|connection refused|no such file/iu.test(stderr))
101
+ return false;
102
+ }
103
+ answering.add(socket);
104
+ return true;
105
+ }
106
+ /**
107
+ * Ordinary CLI commands retain PATH selection for a running server. When no
108
+ * server runs, the next command starts one, so bundled tmux goes first: a
109
+ * Homebrew client must not start a reduced-feature server (#766).
110
+ * TMUX_IDE_TMUX_BIN always wins.
111
+ */
112
+ export function resolveOrdinaryTmuxClient(environment, cwd, options = {}) {
113
+ const bundled = options.bundled ??
114
+ (() => resolveBundledTmux([
115
+ ...(environment.TMUX_IDE_CLI ? [environment.TMUX_IDE_CLI] : []),
116
+ fileURLToPath(import.meta.url),
117
+ ]));
63
118
  const configured = environment.TMUX_IDE_TMUX_BIN;
119
+ if (!configured) {
120
+ const socket = ordinaryTargetSocket(environment);
121
+ if (socket !== null) {
122
+ let starter = null;
123
+ try {
124
+ starter = bundled();
125
+ }
126
+ catch {
127
+ // An invalid bundle falls back to the PATH client below.
128
+ }
129
+ const running = options.serverRunning ?? ((at) => serverAnswers(at, starter));
130
+ if (starter && !running(socket))
131
+ return { executable: starter, environment: withBundledTmuxResources(starter, environment) };
132
+ }
133
+ }
64
134
  const candidates = configured
65
135
  ? [configured]
66
136
  : (environment.PATH ?? "/usr/bin:/bin")
@@ -83,11 +153,7 @@ export function resolveOrdinaryTmuxClient(environment, cwd) {
83
153
  }
84
154
  }
85
155
  if (!executable && !configured)
86
- executable =
87
- resolveBundledTmux([
88
- ...(environment.TMUX_IDE_CLI ? [environment.TMUX_IDE_CLI] : []),
89
- fileURLToPath(import.meta.url),
90
- ]) ?? undefined;
156
+ executable = bundled() ?? undefined;
91
157
  if (!executable)
92
158
  throw new Error("tmux_executable_unavailable");
93
159
  return { executable, environment: withBundledTmuxResources(executable, environment) };