tmux-ide 2.9.20 → 2.9.22

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 (145) hide show
  1. package/bin/cli.js +16998 -4283
  2. package/package.json +3 -2
  3. package/packages/contracts/src/command-catalog.ts +116 -0
  4. package/packages/contracts/src/commands.ts +5 -4
  5. package/packages/contracts/src/daemon-events.ts +2 -1
  6. package/packages/contracts/src/index.ts +3 -0
  7. package/packages/contracts/src/pane-reader.ts +121 -0
  8. package/packages/contracts/src/pane-stream.ts +18 -0
  9. package/packages/contracts/src/plain-text.ts +61 -0
  10. package/packages/contracts/src/visual-theme-presets.ts +58 -2
  11. package/packages/daemon/dist/command-center/command-catalog-routes.js +78 -0
  12. package/packages/daemon/dist/command-center/plugin-routes.js +84 -0
  13. package/packages/daemon/dist/command-center/server.js +13 -0
  14. package/packages/daemon/dist/command-center/tmux-server-reader.js +41 -0
  15. package/packages/daemon/dist/command-center/tmux-servers.js +6 -0
  16. package/packages/daemon/dist/doctor.js +106 -43
  17. package/packages/daemon/dist/lib/cli-action-bridge.js +15 -0
  18. package/packages/daemon/dist/lib/cli-command.js +13 -0
  19. package/packages/daemon/dist/lib/daemon-embed.js +39 -1
  20. package/packages/daemon/dist/lib/headless-daemon.js +1 -0
  21. package/packages/daemon/dist/lib/pane-reader-files.js +226 -0
  22. package/packages/daemon/dist/lib/remote-tmux-command.js +8 -5
  23. package/packages/daemon/dist/lib/tmux-client-execution.js +73 -7
  24. package/packages/daemon/dist/lib/tmux-pane-reader.js +105 -0
  25. package/packages/daemon/dist/lib/tmux-server-features.js +38 -0
  26. package/packages/daemon/dist/lib/tmux-server-owner.js +9 -0
  27. package/packages/daemon/dist/lib/worktree.js +18 -0
  28. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  29. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  30. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  31. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  32. package/packages/daemon/dist/open-browser.js +26 -12
  33. package/packages/daemon/dist/open-reader.js +84 -0
  34. package/packages/daemon/dist/plugins/action-catalog.js +129 -0
  35. package/packages/daemon/dist/plugins/action-cli.js +212 -0
  36. package/packages/daemon/dist/plugins/api-table.js +303 -0
  37. package/packages/daemon/dist/plugins/cli.js +556 -0
  38. package/packages/daemon/dist/plugins/consent.js +107 -0
  39. package/packages/daemon/dist/plugins/daemon-plugins.js +124 -0
  40. package/packages/daemon/dist/plugins/discovery.js +142 -0
  41. package/packages/daemon/dist/plugins/examples/worktree-tasks.js +115 -0
  42. package/packages/daemon/dist/plugins/exec-sandbox.js +202 -0
  43. package/packages/daemon/dist/plugins/host/actions-prelude.js +279 -0
  44. package/packages/daemon/dist/plugins/host/entry.js +4 -0
  45. package/packages/daemon/dist/plugins/host/host-api-prelude.js +232 -0
  46. package/packages/daemon/dist/plugins/host/lua-state.js +493 -0
  47. package/packages/daemon/dist/plugins/host/main.js +322 -0
  48. package/packages/daemon/dist/plugins/host/sandbox.js +299 -0
  49. package/packages/daemon/dist/plugins/host-calls.js +279 -0
  50. package/packages/daemon/dist/plugins/manifest.js +69 -0
  51. package/packages/daemon/dist/plugins/plugin-exec.js +261 -0
  52. package/packages/daemon/dist/plugins/plugin-log.js +54 -0
  53. package/packages/daemon/dist/plugins/plugin-store.js +74 -0
  54. package/packages/daemon/dist/plugins/protocol.js +252 -0
  55. package/packages/daemon/dist/plugins/safe-files.js +97 -0
  56. package/packages/daemon/dist/plugins/supervisor.js +790 -0
  57. package/packages/daemon/dist/plugins/worktree-calls.js +154 -0
  58. package/packages/daemon/dist/restore.js +57 -40
  59. package/packages/daemon/dist/terminal/mirror/session-channel.js +4 -1
  60. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +12 -3
  61. package/packages/daemon/dist/terminal/protocol/reader-option.js +66 -0
  62. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +7 -2
  63. package/packages/daemon/dist/tmux-upgrade/cli.js +106 -0
  64. package/packages/daemon/dist/tmux-upgrade/io.js +540 -0
  65. package/packages/daemon/dist/tmux-upgrade/plan.js +238 -0
  66. package/packages/daemon/dist/tmux-upgrade/run.js +199 -0
  67. package/packages/daemon/dist/tui/chrome/snapshot.js +3 -4
  68. package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +64 -4
  69. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +62 -5
  70. package/packages/daemon/dist/tui/mirror/runtime/application-home-experience.js +2 -0
  71. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +12 -8
  72. package/packages/daemon/dist/tui/mirror/runtime/application-palette-command-owner.js +30 -2
  73. package/packages/daemon/dist/tui/mirror/runtime/application-plugin-commands.js +152 -0
  74. package/packages/daemon/dist/tui/mirror/runtime/application-plugin-form.js +251 -0
  75. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +125 -111
  76. package/packages/daemon/dist/tui/mirror/workspace/application-command-description.js +14 -0
  77. package/packages/daemon/dist/tui/mirror/workspace/palette-list-layout.js +5 -0
  78. package/packages/daemon/src/command-center/command-catalog-routes.ts +116 -0
  79. package/packages/daemon/src/command-center/plugin-routes.ts +110 -0
  80. package/packages/daemon/src/command-center/server.ts +15 -0
  81. package/packages/daemon/src/command-center/tmux-server-reader.ts +62 -0
  82. package/packages/daemon/src/command-center/tmux-servers.ts +6 -0
  83. package/packages/daemon/src/doctor.ts +118 -45
  84. package/packages/daemon/src/lib/cli-action-bridge.ts +19 -0
  85. package/packages/daemon/src/lib/cli-command.ts +16 -0
  86. package/packages/daemon/src/lib/daemon-embed.ts +59 -0
  87. package/packages/daemon/src/lib/headless-daemon.ts +1 -0
  88. package/packages/daemon/src/lib/pane-reader-files.ts +294 -0
  89. package/packages/daemon/src/lib/remote-tmux-command.ts +13 -6
  90. package/packages/daemon/src/lib/tmux-client-execution.ts +79 -7
  91. package/packages/daemon/src/lib/tmux-pane-reader.ts +144 -0
  92. package/packages/daemon/src/lib/tmux-server-features.ts +43 -0
  93. package/packages/daemon/src/lib/tmux-server-owner.ts +9 -0
  94. package/packages/daemon/src/lib/worktree.ts +16 -0
  95. package/packages/daemon/src/open-browser.ts +59 -18
  96. package/packages/daemon/src/open-reader.ts +148 -0
  97. package/packages/daemon/src/plugins/action-catalog.ts +141 -0
  98. package/packages/daemon/src/plugins/action-cli.ts +248 -0
  99. package/packages/daemon/src/plugins/api-table.ts +346 -0
  100. package/packages/daemon/src/plugins/cli.ts +630 -0
  101. package/packages/daemon/src/plugins/consent.ts +125 -0
  102. package/packages/daemon/src/plugins/daemon-plugins.ts +172 -0
  103. package/packages/daemon/src/plugins/discovery.ts +176 -0
  104. package/packages/daemon/src/plugins/examples/worktree-tasks.ts +120 -0
  105. package/packages/daemon/src/plugins/exec-sandbox.ts +264 -0
  106. package/packages/daemon/src/plugins/host/actions-prelude.ts +280 -0
  107. package/packages/daemon/src/plugins/host/entry.ts +5 -0
  108. package/packages/daemon/src/plugins/host/host-api-prelude.ts +233 -0
  109. package/packages/daemon/src/plugins/host/lua-state.ts +557 -0
  110. package/packages/daemon/src/plugins/host/main.ts +359 -0
  111. package/packages/daemon/src/plugins/host/sandbox.ts +301 -0
  112. package/packages/daemon/src/plugins/host-calls.ts +343 -0
  113. package/packages/daemon/src/plugins/manifest.ts +74 -0
  114. package/packages/daemon/src/plugins/plugin-exec.ts +326 -0
  115. package/packages/daemon/src/plugins/plugin-log.ts +63 -0
  116. package/packages/daemon/src/plugins/plugin-store.ts +80 -0
  117. package/packages/daemon/src/plugins/protocol.ts +275 -0
  118. package/packages/daemon/src/plugins/safe-files.ts +105 -0
  119. package/packages/daemon/src/plugins/supervisor.ts +954 -0
  120. package/packages/daemon/src/plugins/worktree-calls.ts +183 -0
  121. package/packages/daemon/src/restore.ts +80 -44
  122. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  123. package/packages/daemon/src/terminal/mirror/session-channel.ts +6 -1
  124. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +15 -2
  125. package/packages/daemon/src/terminal/protocol/reader-option.ts +77 -0
  126. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +10 -1
  127. package/packages/daemon/src/tmux-upgrade/cli.ts +118 -0
  128. package/packages/daemon/src/tmux-upgrade/io.ts +596 -0
  129. package/packages/daemon/src/tmux-upgrade/plan.ts +353 -0
  130. package/packages/daemon/src/tmux-upgrade/run.ts +325 -0
  131. package/packages/daemon/src/tui/chrome/snapshot.ts +3 -4
  132. package/packages/daemon/src/tui/mirror/runtime/application-fleet-switcher.tsx +3 -1
  133. package/packages/daemon/src/tui/mirror/runtime/application-home-agent-navigation.ts +110 -10
  134. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +90 -6
  135. package/packages/daemon/src/tui/mirror/runtime/application-home-experience.ts +2 -0
  136. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +20 -9
  137. package/packages/daemon/src/tui/mirror/runtime/application-palette-command-owner.ts +42 -2
  138. package/packages/daemon/src/tui/mirror/runtime/application-palette-preview.tsx +7 -1
  139. package/packages/daemon/src/tui/mirror/runtime/application-plugin-commands.ts +229 -0
  140. package/packages/daemon/src/tui/mirror/runtime/application-plugin-form.ts +312 -0
  141. package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +2 -2
  142. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +149 -128
  143. package/packages/daemon/src/tui/mirror/workspace/application-command-description.ts +44 -2
  144. package/packages/daemon/src/tui/mirror/workspace/palette-list-layout.ts +4 -0
  145. package/packages/tmux-bridge/src/runner.ts +3 -1
@@ -1,12 +1,19 @@
1
1
  import { shellEscape } from "./shell.ts";
2
2
 
3
+ // Respect the host's existing installation preference, then try the installer
4
+ // and common package-manager prefixes. Never source shell profiles.
5
+ const REMOTE_PATH =
6
+ 'export PATH="${PATH:-/usr/bin:/bin}:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/home/linuxbrew/.linuxbrew/bin:$HOME/.npm-global/bin"; ';
7
+
3
8
  /** Fixed commands only. SSH normally omits interactive shell PATH setup. */
4
9
  export function remoteTmuxIdeCommand(operation: "discover" | "start"): string {
5
- const args = operation === "discover" ? "remote-daemon-info --json" : "update --daemon --json";
6
- // Respect the host's existing installation preference, then try the installer
7
- // and common package-manager prefixes. Never source shell profiles.
8
- const script =
9
- 'export PATH="${PATH:-/usr/bin:/bin}:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin:/home/linuxbrew/.linuxbrew/bin:$HOME/.npm-global/bin"; ' +
10
- `exec tmux-ide ${args}`;
10
+ return remoteTmuxIdeArgsCommand(
11
+ operation === "discover" ? ["remote-daemon-info", "--json"] : ["update", "--daemon", "--json"],
12
+ );
13
+ }
14
+
15
+ /** `tmux-ide <args…>` on a remote host, each argument quoted for its shell. */
16
+ export function remoteTmuxIdeArgsCommand(args: readonly string[]): string {
17
+ const script = REMOTE_PATH + `exec tmux-ide ${args.map(shellEscape).join(" ")}`;
11
18
  return `/bin/sh -c ${shellEscape(script)}`;
12
19
  }
@@ -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";
@@ -63,15 +64,91 @@ export function tmuxClientEnvironment(
63
64
  return { ...environment, ...bundledTmuxResourceEnvironment(executable) };
64
65
  }
65
66
 
66
- /** Ordinary CLI commands retain PATH selection; bundled tmux fills a missing system client. */
67
+ /**
68
+ * The socket an ordinary tmux client reaches, or null inside tmux (where the
69
+ * server exists by definition). Ordinary clients pass no -S or -L in
70
+ * production, so this is tmux's own rule: $TMUX, else the default socket.
71
+ */
72
+ export function ordinaryTargetSocket(environment: NodeJS.ProcessEnv): string | null {
73
+ if (environment.TMUX) return null;
74
+ const uid = process.getuid?.() ?? 0;
75
+ return join(environment.TMUX_TMPDIR || "/tmp", `tmux-${uid}`, "default");
76
+ }
77
+
78
+ const answering = new Set<string>();
79
+
80
+ /**
81
+ * Does a server answer on this socket? A socket file alone is not enough: a
82
+ * server that crashed leaves one behind. `probe` asks with `list-sessions`,
83
+ * which never starts a server. A running server is remembered for the process.
84
+ */
85
+ export function serverAnswers(socket: string, probe: string): boolean {
86
+ if (answering.has(socket)) return true;
87
+ try {
88
+ if (!statSync(socket).isSocket()) return false;
89
+ } catch {
90
+ return false;
91
+ }
92
+ try {
93
+ execFileSync(probe, ["-S", socket, "list-sessions", "-F", "#{pid}"], {
94
+ stdio: ["ignore", "ignore", "pipe"],
95
+ timeout: 3000,
96
+ env: withBundledTmuxResources(probe, process.env),
97
+ });
98
+ } catch (error) {
99
+ const stderr = String((error as { stderr?: unknown }).stderr ?? "");
100
+ // A refused connection is a stale socket. Anything else (a protocol
101
+ // mismatch, a timeout) means something is there: keep the PATH client.
102
+ if (/no server running|error connecting|connection refused|no such file/iu.test(stderr))
103
+ return false;
104
+ }
105
+ answering.add(socket);
106
+ return true;
107
+ }
108
+
109
+ export interface OrdinaryTmuxClientOptions {
110
+ /** Whether a server answers on this socket. Defaults to {@link serverAnswers}. */
111
+ readonly serverRunning?: (socket: string) => boolean;
112
+ /** The validated bundled executable, or null. */
113
+ readonly bundled?: () => string | null;
114
+ }
115
+
116
+ /**
117
+ * Ordinary CLI commands retain PATH selection for a running server. When no
118
+ * server runs, the next command starts one, so bundled tmux goes first: a
119
+ * Homebrew client must not start a reduced-feature server (#766).
120
+ * TMUX_IDE_TMUX_BIN always wins.
121
+ */
67
122
  export function resolveOrdinaryTmuxClient(
68
123
  environment: NodeJS.ProcessEnv,
69
124
  cwd?: string | URL,
125
+ options: OrdinaryTmuxClientOptions = {},
70
126
  ): {
71
127
  executable: string;
72
128
  environment: NodeJS.ProcessEnv;
73
129
  } {
130
+ const bundled =
131
+ options.bundled ??
132
+ (() =>
133
+ resolveBundledTmux([
134
+ ...(environment.TMUX_IDE_CLI ? [environment.TMUX_IDE_CLI] : []),
135
+ fileURLToPath(import.meta.url),
136
+ ]));
74
137
  const configured = environment.TMUX_IDE_TMUX_BIN;
138
+ if (!configured) {
139
+ const socket = ordinaryTargetSocket(environment);
140
+ if (socket !== null) {
141
+ let starter: string | null = null;
142
+ try {
143
+ starter = bundled();
144
+ } catch {
145
+ // An invalid bundle falls back to the PATH client below.
146
+ }
147
+ const running = options.serverRunning ?? ((at: string) => serverAnswers(at, starter!));
148
+ if (starter && !running(socket))
149
+ return { executable: starter, environment: withBundledTmuxResources(starter, environment) };
150
+ }
151
+ }
75
152
  const candidates = configured
76
153
  ? [configured]
77
154
  : (environment.PATH ?? "/usr/bin:/bin")
@@ -93,12 +170,7 @@ export function resolveOrdinaryTmuxClient(
93
170
  /* Try the next ordinary PATH candidate. */
94
171
  }
95
172
  }
96
- if (!executable && !configured)
97
- executable =
98
- resolveBundledTmux([
99
- ...(environment.TMUX_IDE_CLI ? [environment.TMUX_IDE_CLI] : []),
100
- fileURLToPath(import.meta.url),
101
- ]) ?? undefined;
173
+ if (!executable && !configured) executable = bundled() ?? undefined;
102
174
  if (!executable) throw new Error("tmux_executable_unavailable");
103
175
  return { executable, environment: withBundledTmuxResources(executable, environment) };
104
176
  }
@@ -0,0 +1,144 @@
1
+ import { basename, dirname } from "node:path";
2
+ import {
3
+ PaneReaderAssetRequestSchemaZ,
4
+ PaneReaderAssetResponseSchemaZ,
5
+ PaneReaderRequestSchemaZ,
6
+ PaneReaderResponseSchemaZ,
7
+ type PaneEditorContextTarget,
8
+ type PaneReaderAssetResponse,
9
+ type PaneReaderResponse,
10
+ } from "@tmux-ide/contracts";
11
+ import type { LiveSessionSummary } from "../command-center/discovery.ts";
12
+ import type { WorkspaceTerminalInventoryRuntime } from "../terminal/attachments/native-runtime.ts";
13
+ import type { WorkspaceRegistry } from "./workspace-registry.ts";
14
+ import { decodeTmuxArgument } from "../terminal/protocol/session-descriptor-discovery.ts";
15
+ import { readerOption, type ReaderOption } from "../terminal/protocol/reader-option.ts";
16
+ import { readReaderAssetPage, readReaderPage } from "./pane-reader-files.ts";
17
+
18
+ /** Any identity, liveness or option failure. Carries no path or detail. */
19
+ export class PaneReaderUnavailable extends Error {
20
+ constructor() {
21
+ super("The reader pane is unavailable");
22
+ }
23
+ }
24
+
25
+ export interface PaneReaderResolver {
26
+ read(input: unknown, cancellation: AbortSignal): Promise<PaneReaderResponse>;
27
+ asset(input: unknown, cancellation: AbortSignal): Promise<PaneReaderAssetResponse>;
28
+ }
29
+
30
+ /**
31
+ * Serves only the file named by the target pane's `@tmux_ide_reader` option,
32
+ * for a pane whose identity is proven again before and after the read, and
33
+ * whose reader process is alive.
34
+ */
35
+ export function createPaneReaderResolver(options: {
36
+ generation: string;
37
+ assertOpen(): void;
38
+ registry: Pick<WorkspaceRegistry, "get">;
39
+ catalog(): Promise<LiveSessionSummary[]>;
40
+ inventory: Pick<WorkspaceTerminalInventoryRuntime, "discoverTerminalInventory">;
41
+ run(args: readonly string[], signal: AbortSignal): Promise<string>;
42
+ alive?: (pid: number) => boolean;
43
+ }): PaneReaderResolver {
44
+ let readers = 0;
45
+ const withReader = async <T>(
46
+ target: PaneEditorContextTarget,
47
+ cancellation: AbortSignal,
48
+ work: (reader: ReaderOption) => T,
49
+ ): Promise<T> => {
50
+ const signal = AbortSignal.any([cancellation, AbortSignal.timeout(2500)]);
51
+ const workspace = options.registry.get(target.workspaceName);
52
+ const assertCurrent = () => {
53
+ options.assertOpen();
54
+ signal.throwIfAborted();
55
+ if (
56
+ target.generation !== options.generation ||
57
+ !workspace ||
58
+ options.registry.get(target.workspaceName) !== workspace
59
+ )
60
+ throw new PaneReaderUnavailable();
61
+ };
62
+ assertCurrent();
63
+ if (readers >= 8) throw new PaneReaderUnavailable();
64
+ readers++;
65
+ try {
66
+ const sessions = await options.catalog();
67
+ assertCurrent();
68
+ const matching = sessions.filter((s) => s.liveSessionId === target.liveSessionId);
69
+ if (matching.length !== 1 || matching[0]!.sessionName !== workspace!.sessionName)
70
+ throw new PaneReaderUnavailable();
71
+ const snapshot = await options.inventory.discoverTerminalInventory(signal);
72
+ assertCurrent();
73
+ if (
74
+ snapshot.catalog.invalidRuntimeProof ||
75
+ snapshot.catalog.duplicateSemanticStamp ||
76
+ snapshot.catalog.duplicateRuntimePaneBinding
77
+ )
78
+ throw new PaneReaderUnavailable();
79
+ const matches = snapshot.panes.filter(
80
+ (p) =>
81
+ p.workspaceName === target.workspaceName &&
82
+ p.semanticPaneId === target.semanticPaneId &&
83
+ p.sessionName === workspace!.sessionName,
84
+ );
85
+ if (matches.length !== 1) throw new PaneReaderUnavailable();
86
+ const pane = { ...matches[0]! };
87
+ if (!pane.nativePaneBirthId || !/^%[0-9]+$/u.test(pane.runtimePaneId))
88
+ throw new PaneReaderUnavailable();
89
+ const observe = async (): Promise<ReaderOption> => {
90
+ const raw = await options.run(
91
+ [
92
+ "display-message",
93
+ "-p",
94
+ "-t",
95
+ pane.runtimePaneId,
96
+ "#{qa:@tmux_ide_pane_id}\t#{qa:pane_birth_id}\t#{pane_pid}\t#{qa:@tmux_ide_reader}",
97
+ ],
98
+ signal,
99
+ );
100
+ assertCurrent();
101
+ if (raw.length > 16_384) throw new PaneReaderUnavailable();
102
+ const [semantic, birth, panePid, option] = raw
103
+ .trimEnd()
104
+ .split("\t")
105
+ .map(decodeTmuxArgument);
106
+ if (semantic !== target.semanticPaneId || birth !== pane.nativePaneBirthId)
107
+ throw new PaneReaderUnavailable();
108
+ const reader = readerOption(option ?? "", panePid ?? "", options.alive);
109
+ if (!reader) throw new PaneReaderUnavailable();
110
+ return reader;
111
+ };
112
+ const reader = await observe();
113
+ const result = work(reader);
114
+ const current = await observe();
115
+ if (current.path !== reader.path || current.pid !== reader.pid)
116
+ throw new PaneReaderUnavailable();
117
+ return result;
118
+ } finally {
119
+ readers--;
120
+ }
121
+ };
122
+ return {
123
+ read: async (input, cancellation) => {
124
+ const request = PaneReaderRequestSchemaZ.parse(input);
125
+ return withReader(request.target, cancellation, (reader) =>
126
+ PaneReaderResponseSchemaZ.parse({
127
+ version: 1,
128
+ name: reader.name,
129
+ folder: basename(dirname(reader.path)),
130
+ ...readReaderPage(reader.path, request.have, request.page),
131
+ }),
132
+ );
133
+ },
134
+ asset: async (input, cancellation) => {
135
+ const request = PaneReaderAssetRequestSchemaZ.parse(input);
136
+ return withReader(request.target, cancellation, (reader) =>
137
+ PaneReaderAssetResponseSchemaZ.parse({
138
+ version: 1,
139
+ ...readReaderAssetPage(reader.path, request.src, request.page),
140
+ }),
141
+ );
142
+ },
143
+ };
144
+ }
@@ -0,0 +1,43 @@
1
+ import { nativeSplitCapability } from "../terminal/protocol/native-split-resize.ts";
2
+
3
+ /** Runs one tmux command against a server and returns its stdout; throws with stderr. */
4
+ export type TmuxProbe = (args: readonly string[]) => string;
5
+ const UNKNOWN = (command: string) => new RegExp(`^unknown command: ${command}$`, "mu");
6
+
7
+ export type NativeAnswer = "full" | "stock" | "older" | "partial" | "no-server" | "unknown";
8
+ /** The same reading of the server as the mirror's: the stock resize when it refuses
9
+ * the split command by name, and full only with the split capability it requires. */
10
+ export function nativeCommands(probe: TmuxProbe): NativeAnswer {
11
+ const ask = (command: string) => {
12
+ try {
13
+ return { output: probe([command, "-V"]) };
14
+ } catch (error) {
15
+ const failure = error as { stderr?: unknown; message?: string };
16
+ return { failure: String(failure.stderr ?? failure.message ?? "") };
17
+ }
18
+ };
19
+ const split = ask("tmux-ide-resize-split");
20
+ const events = ask("tmux-ide-events");
21
+ const failures = [split.failure, events.failure].filter((text) => text !== undefined);
22
+ if (failures.some((text) => /no server running|error connecting/u.test(text!)))
23
+ return "no-server";
24
+ const refused = (answer: { failure?: string }, command: string) =>
25
+ answer.failure !== undefined && UNKNOWN(command).test(answer.failure);
26
+ if (refused(split, "tmux-ide-resize-split")) {
27
+ if (refused(events, "tmux-ide-events")) return "stock";
28
+ // The journal answers: a tmux-ide tmux built before the split command.
29
+ if (events.output !== undefined) return "older";
30
+ return "unknown";
31
+ }
32
+ if (split.output !== undefined && events.output !== undefined) {
33
+ try {
34
+ return nativeSplitCapability(split.output) ? "full" : "partial";
35
+ } catch {
36
+ return "partial";
37
+ }
38
+ }
39
+ return failures.length === 2 ? "unknown" : "partial";
40
+ }
41
+
42
+ /** The answers a live server can give (doctor also reports "no-server"). */
43
+ export type ServerFeatures = Exclude<NativeAnswer, "no-server">;
@@ -1,3 +1,4 @@
1
+ import { createPaneReaderResolver } from "./tmux-pane-reader.ts";
1
2
  import { createNativeBrowserResolver } from "./tmux-native-browser.ts";
2
3
  import { createNativeSurfaceContextResolver } from "./native-surface-context.ts";
3
4
  import type { LocalImageOwner } from "../terminal/graphics/local-image-owner.ts";
@@ -659,6 +660,14 @@ export async function createNativeTmuxServerOwner(options: NativeTmuxServerOwner
659
660
  inventory: terminalInventoryRuntime,
660
661
  run: generationRunAsync,
661
662
  }),
663
+ paneReader: createPaneReaderResolver({
664
+ generation,
665
+ assertOpen,
666
+ registry: workspaceRegistry,
667
+ catalog,
668
+ inventory: terminalInventoryRuntime,
669
+ run: generationRunAsync,
670
+ }),
662
671
  catalog,
663
672
  readWindowSplitLayout: async (workspaceName: string, input: WindowLinkTarget) => {
664
673
  assertOpen();
@@ -208,6 +208,22 @@ export function mapWorktreeError(stderr: string, fallbackMessage: string): Workt
208
208
  // io — git shell-outs (map stderr → WorktreeError)
209
209
  // ---------------------------------------------------------------------------
210
210
 
211
+ /**
212
+ * `env` with git hooks off for every git command run with it: core.hooksPath
213
+ * points at /dev/null, through GIT_CONFIG_* (which outrank the repository's
214
+ * own config, a relative hooksPath that a branch carries included).
215
+ */
216
+ export function gitHooksOff(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
217
+ const count = Number.parseInt(env.GIT_CONFIG_COUNT ?? "0", 10);
218
+ const index = Number.isInteger(count) && count >= 0 ? count : 0;
219
+ return {
220
+ ...env,
221
+ GIT_CONFIG_COUNT: String(index + 1),
222
+ [`GIT_CONFIG_KEY_${index}`]: "core.hooksPath",
223
+ [`GIT_CONFIG_VALUE_${index}`]: "/dev/null",
224
+ };
225
+ }
226
+
211
227
  /** Injectable git runner so io wrappers stay unit-testable. */
212
228
  export type GitRunner = (repoDir: string, args: string[]) => string;
213
229
 
@@ -114,7 +114,7 @@ export function validateBrowserOpen(url: string | undefined, options: OpenBrowse
114
114
  });
115
115
  }
116
116
 
117
- type Run = (args: readonly string[]) => string;
117
+ export type Run = (args: readonly string[]) => string;
118
118
 
119
119
  /** Printed when the opened browser never publishes tmux-ide's native controls. */
120
120
  export const NO_NATIVE_CONTROLS_NOTICE =
@@ -163,16 +163,16 @@ export async function nativeControlsNotice(
163
163
  await sleep(250);
164
164
  }
165
165
  }
166
- export function createBrowserPane(
166
+ type PaneKind = "BROWSER" | "READER";
167
+
168
+ /** Where a new browser or reader pane goes: resolved IDs, before any mutation. */
169
+ export function resolveOpenPaneTarget(
167
170
  run: Run,
168
- executable: string,
169
- url: string | undefined,
170
171
  options: OpenBrowserOptions,
171
172
  environment: NodeJS.ProcessEnv,
172
- cwd: string,
173
- namespace: Readonly<Record<string, string>>,
174
- ): { pane: string; session: string; window: string; status: "created" } {
175
- validateBrowserOpen(url, options);
173
+ kind: PaneKind = "BROWSER",
174
+ ): { session: string; window: string; sourcePane: string } {
175
+ const noun = kind.toLowerCase();
176
176
  const inheritedPane = /^%\d+$/u.test(environment.TMUX_PANE ?? "")
177
177
  ? environment.TMUX_PANE
178
178
  : undefined;
@@ -188,7 +188,7 @@ export function createBrowserPane(
188
188
  if (!target)
189
189
  throw new IdeError(
190
190
  "Run tmux-ide open inside a tmux pane, or select a session with --session NAME.",
191
- { code: "BROWSER_TARGET_REQUIRED", exitCode: 2 },
191
+ { code: `${kind}_TARGET_REQUIRED`, exitCode: 2 },
192
192
  );
193
193
  // Resolve IDs before mutation. No implicit last-used session or window target.
194
194
  const identity = run([
@@ -207,13 +207,13 @@ export function createBrowserPane(
207
207
  !/^@\d+$/u.test(window ?? "") ||
208
208
  !/^%\d+$/u.test(sourcePane ?? "")
209
209
  )
210
- throw new IdeError("The browser target is no longer available.", {
211
- code: "BROWSER_TARGET_UNAVAILABLE",
210
+ throw new IdeError(`The ${noun} target is no longer available.`, {
211
+ code: `${kind}_TARGET_UNAVAILABLE`,
212
212
  });
213
213
  if (implicit && serverPid !== inheritedServer?.[2])
214
214
  throw new IdeError(
215
215
  "The current pane belongs to a different tmux server. Select a session explicitly.",
216
- { code: "BROWSER_TARGET_MISMATCH", exitCode: 2 },
216
+ { code: `${kind}_TARGET_MISMATCH`, exitCode: 2 },
217
217
  );
218
218
  if (options.session && options.pane) {
219
219
  const selected = run([
@@ -225,21 +225,38 @@ export function createBrowserPane(
225
225
  ]).trim();
226
226
  if (selected !== session)
227
227
  throw new IdeError("The pane does not belong to the requested session.", {
228
- code: "BROWSER_TARGET_MISMATCH",
228
+ code: `${kind}_TARGET_MISMATCH`,
229
229
  exitCode: 2,
230
230
  });
231
231
  }
232
+ return { session: session!, window: window!, sourcePane: sourcePane! };
233
+ }
234
+
235
+ /**
236
+ * The tmux argv that creates the pane and runs `command` in it directly (no
237
+ * shell parsing). `format` is what tmux prints for the new pane.
238
+ */
239
+ export function openPaneArgs(
240
+ target: { session: string; window: string; sourcePane: string },
241
+ options: OpenBrowserOptions,
242
+ environment: NodeJS.ProcessEnv,
243
+ cwd: string,
244
+ namespace: Readonly<Record<string, string>>,
245
+ command: readonly string[],
246
+ format: string,
247
+ windowName: string,
248
+ ): string[] {
232
249
  const args = options.window
233
- ? ["new-window", "-t", `${session}:`, "-n", "Browser"]
250
+ ? ["new-window", "-t", `${target.session}:`, "-n", windowName]
234
251
  : [
235
252
  "split-window",
236
253
  options.split === "down" ? "-v" : "-h",
237
254
  "-t",
238
- `${session}:${window}.${sourcePane}`,
255
+ `${target.session}:${target.window}.${target.sourcePane}`,
239
256
  "-l",
240
257
  `${options.size ?? "50"}%`,
241
258
  ];
242
- args.push("-c", resolve(cwd), "-P", "-F", "#{session_id}\t#{window_id}\t#{pane_id}");
259
+ args.push("-c", resolve(cwd), "-P", "-F", format);
243
260
  // tmux supplies the new pane's TMUX and TMUX_PANE. Never copy the caller's
244
261
  // native-surface route, which belongs to a different pane.
245
262
  const childEnvironment: Record<string, string> = { ...namespace };
@@ -255,11 +272,35 @@ export function createBrowserPane(
255
272
  if (environment[key] !== undefined) childEnvironment[key] = environment[key];
256
273
  for (const [key, value] of Object.entries(childEnvironment)) args.push("-e", `${key}=${value}`);
257
274
  // Multiple command arguments use tmux's direct exec path, not shell parsing.
258
- args.push(executable, "open", ...(url === undefined ? [] : [url]), "--no-merge");
275
+ args.push(...command);
276
+ return args;
277
+ }
278
+
279
+ export function createBrowserPane(
280
+ run: Run,
281
+ executable: string,
282
+ url: string | undefined,
283
+ options: OpenBrowserOptions,
284
+ environment: NodeJS.ProcessEnv,
285
+ cwd: string,
286
+ namespace: Readonly<Record<string, string>>,
287
+ ): { pane: string; session: string; window: string; status: "created" } {
288
+ validateBrowserOpen(url, options);
289
+ const target = resolveOpenPaneTarget(run, options, environment);
290
+ const args = openPaneArgs(
291
+ target,
292
+ options,
293
+ environment,
294
+ cwd,
295
+ namespace,
296
+ [executable, "open", ...(url === undefined ? [] : [url]), "--no-merge"],
297
+ "#{session_id}\t#{window_id}\t#{pane_id}",
298
+ "Browser",
299
+ );
259
300
  const [createdSession, createdWindow, pane] = run(args).trim().split("\t");
260
301
  if (
261
302
  !/^%\d+$/u.test(pane ?? "") ||
262
- createdSession !== session ||
303
+ createdSession !== target.session ||
263
304
  !/^@\d+$/u.test(createdWindow ?? "")
264
305
  )
265
306
  throw new IdeError("tmux did not return the created browser pane ID.", {
@@ -0,0 +1,148 @@
1
+ import { realpathSync, statSync } from "node:fs";
2
+ import { relative, resolve } from "node:path";
3
+ import { resolveCliCommand } from "./lib/cli-command.ts";
4
+ import { IdeError } from "./lib/errors.ts";
5
+ import { resolveRuntimeNamespace, runtimeNamespaceEnvironment } from "./lib/runtime-namespace.ts";
6
+ import {
7
+ createPinnedWorkspaceTmuxRunner,
8
+ resolveWorkspacePaneTmuxAuthority,
9
+ } from "./lib/workspace-pane-creation.ts";
10
+ import {
11
+ openPaneArgs,
12
+ resolveOpenPaneTarget,
13
+ validateBrowserOpen,
14
+ type OpenBrowserOptions,
15
+ type Run,
16
+ } from "./open-browser.ts";
17
+ import { isMarkdownPath } from "./terminal/protocol/reader-option.ts";
18
+
19
+ export type OpenTarget =
20
+ | { kind: "browser" }
21
+ | {
22
+ kind: "reader";
23
+ /** Absolute real path. */
24
+ path: string;
25
+ /** The path as the user named it, relative to their cwd. */
26
+ display: string;
27
+ };
28
+
29
+ const SCHEME_URL = /^[a-z][a-z0-9+.-]*:\/\//iu;
30
+ const MARKDOWN_ARGUMENT = /\.(?:md|markdown)$/iu;
31
+
32
+ /**
33
+ * Decides what `tmux-ide open <arg>` opens. A Markdown file name with no
34
+ * `scheme://` is read in the native reader and must exist; everything else
35
+ * goes to the browser exactly as before.
36
+ */
37
+ export function classifyOpenTarget(
38
+ arg: string | undefined,
39
+ cwd: string,
40
+ fs: { realpath(path: string): string; isFile(path: string): boolean } = {
41
+ realpath: (path) => realpathSync(path),
42
+ isFile: (path) => statSync(path).isFile(),
43
+ },
44
+ ): OpenTarget {
45
+ if (arg === undefined || SCHEME_URL.test(arg) || !MARKDOWN_ARGUMENT.test(arg))
46
+ return { kind: "browser" };
47
+ const named = resolve(cwd, arg);
48
+ const display = relative(cwd, named) || named;
49
+ let path: string;
50
+ try {
51
+ path = fs.realpath(named);
52
+ if (!fs.isFile(path)) throw new Error("not a file");
53
+ } catch {
54
+ throw new IdeError(`No Markdown file at ${display}.`, {
55
+ code: "FILE_NOT_FOUND",
56
+ exitCode: 2,
57
+ });
58
+ }
59
+ if (!isMarkdownPath(path))
60
+ throw new IdeError(`${display} does not resolve to a Markdown file.`, {
61
+ code: "NOT_MARKDOWN",
62
+ exitCode: 2,
63
+ });
64
+ return { kind: "reader", path, display };
65
+ }
66
+
67
+ export interface ReaderPaneResult {
68
+ pane: string;
69
+ session: string;
70
+ window: string;
71
+ status: "created";
72
+ kind: "reader";
73
+ }
74
+
75
+ /**
76
+ * Splits a pane running `tmux-ide show <file>` (the TUI renderer, which also
77
+ * watches the file) and stamps `@tmux_ide_reader` with that process's pid,
78
+ * which is what lets the Mac app paint its native reader over the pane.
79
+ */
80
+ export function createReaderPane(
81
+ run: Run,
82
+ cli: readonly string[],
83
+ path: string,
84
+ options: OpenBrowserOptions,
85
+ environment: NodeJS.ProcessEnv,
86
+ cwd: string,
87
+ namespace: Readonly<Record<string, string>>,
88
+ ): ReaderPaneResult {
89
+ validateBrowserOpen(undefined, options);
90
+ const target = resolveOpenPaneTarget(run, options, environment, "READER");
91
+ const args = openPaneArgs(
92
+ target,
93
+ options,
94
+ environment,
95
+ cwd,
96
+ namespace,
97
+ [...cli, "show", path],
98
+ "#{session_id}\t#{window_id}\t#{pane_id}\t#{pane_pid}",
99
+ "Reader",
100
+ );
101
+ const [session, window, pane, pid] = run(args).trim().split("\t");
102
+ if (
103
+ !/^%\d+$/u.test(pane ?? "") ||
104
+ session !== target.session ||
105
+ !/^@\d+$/u.test(window ?? "") ||
106
+ !/^[1-9]\d{0,9}$/u.test(pid ?? "")
107
+ )
108
+ throw new IdeError("tmux did not return the created reader pane.", {
109
+ code: "READER_CREATE_FAILED",
110
+ });
111
+ run([
112
+ "set-option",
113
+ "-p",
114
+ "-t",
115
+ pane!,
116
+ "@tmux_ide_reader",
117
+ JSON.stringify({ version: 1, pid: Number(pid), path }),
118
+ ]);
119
+ return { pane: pane!, session: session!, window: window!, status: "created", kind: "reader" };
120
+ }
121
+
122
+ export async function openReader(
123
+ target: Extract<OpenTarget, { kind: "reader" }>,
124
+ options: OpenBrowserOptions = {},
125
+ ): Promise<ReaderPaneResult> {
126
+ validateBrowserOpen(undefined, options);
127
+ try {
128
+ const namespace = { ...runtimeNamespaceEnvironment(resolveRuntimeNamespace()) };
129
+ const run = createPinnedWorkspaceTmuxRunner(resolveWorkspacePaneTmuxAuthority(), {
130
+ timeoutMs: 10_000,
131
+ });
132
+ return createReaderPane(
133
+ run,
134
+ resolveCliCommand(),
135
+ target.path,
136
+ options,
137
+ process.env,
138
+ process.cwd(),
139
+ namespace,
140
+ );
141
+ } catch (error) {
142
+ if (error instanceof IdeError) throw error;
143
+ throw new IdeError(
144
+ "Could not create the reader pane. Check that the target tmux session is running.",
145
+ { code: "READER_CREATE_FAILED", cause: error instanceof Error ? error : undefined },
146
+ );
147
+ }
148
+ }