tabherd 0.0.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/LICENSE +674 -0
  3. package/README.md +538 -2
  4. package/launcher/npm.js +9 -0
  5. package/lib/agents.js +324 -0
  6. package/lib/codex-client.js +306 -0
  7. package/lib/codex-rollout.js +251 -0
  8. package/lib/codex.js +424 -0
  9. package/lib/comfy.js +479 -0
  10. package/lib/completed.js +55 -0
  11. package/lib/copilot.js +359 -0
  12. package/lib/cursor.js +516 -0
  13. package/lib/dismissed.js +30 -0
  14. package/lib/filters.js +120 -0
  15. package/lib/groups.js +144 -0
  16. package/lib/history.js +253 -0
  17. package/lib/llamacpp.js +159 -0
  18. package/lib/lmstudio.js +134 -0
  19. package/lib/localai.js +291 -0
  20. package/lib/memory.js +55 -0
  21. package/lib/ollama.js +124 -0
  22. package/lib/open-dashboard.js +39 -0
  23. package/lib/opencode.js +371 -0
  24. package/lib/repos.js +81 -0
  25. package/lib/saved.js +33 -0
  26. package/lib/secrets.js +196 -0
  27. package/lib/session-id.js +9 -0
  28. package/lib/settings.js +231 -0
  29. package/lib/store.js +44 -0
  30. package/lib/terminals/index.js +62 -0
  31. package/lib/terminals/kitty.js +126 -0
  32. package/lib/terminals/linux.js +310 -0
  33. package/lib/terminals/macos.js +468 -0
  34. package/lib/terminals/tmux.js +89 -0
  35. package/lib/terminals/unix-driver.js +172 -0
  36. package/lib/terminals/unix.js +204 -0
  37. package/lib/terminals/unsupported.js +22 -0
  38. package/lib/terminals/wezterm.js +103 -0
  39. package/lib/terminals/windows-close.ps1 +125 -0
  40. package/lib/terminals/windows-focus.ps1 +235 -0
  41. package/lib/terminals/windows-pick-folder.ps1 +57 -0
  42. package/lib/terminals/windows-titles.js +124 -0
  43. package/lib/terminals/windows-titles.ps1 +95 -0
  44. package/lib/terminals/windows.js +166 -0
  45. package/lib/ticket-refs.js +184 -0
  46. package/lib/tickets.js +437 -0
  47. package/lib/todos.js +166 -0
  48. package/lib/trackers.js +541 -0
  49. package/lib/transcript.js +314 -0
  50. package/lib/updates.js +186 -0
  51. package/package.json +35 -7
  52. package/public/app.js +4077 -0
  53. package/public/favicon.svg +1 -0
  54. package/public/icons/tabherd-128.png +0 -0
  55. package/public/icons/tabherd-16.png +0 -0
  56. package/public/icons/tabherd-20.png +0 -0
  57. package/public/icons/tabherd-24.png +0 -0
  58. package/public/icons/tabherd-256.png +0 -0
  59. package/public/icons/tabherd-32.png +0 -0
  60. package/public/icons/tabherd-40.png +0 -0
  61. package/public/icons/tabherd-48.png +0 -0
  62. package/public/icons/tabherd-512.png +0 -0
  63. package/public/icons/tabherd-64.png +0 -0
  64. package/public/index.html +655 -0
  65. package/public/lang/es.js +742 -0
  66. package/public/style.css +1443 -0
  67. package/server.js +814 -0
  68. package/placeholder.js +0 -3
@@ -0,0 +1,172 @@
1
+ 'use strict';
2
+
3
+ // The driver for macOS and Linux, built from a list of terminal backends. A
4
+ // backend knows one terminal app:
5
+ //
6
+ // id, name as Settings shows it
7
+ // processNames the terminal's own processes; "name*" matches a prefix
8
+ // available() installed, or running, here
9
+ // hosts(ctx) whether it's the terminal a session runs in, when no
10
+ // terminal process is among the session's ancestors
11
+ // open(dir, command) opens a tab, or a window where tabs can't be opened
12
+ // focus(ctx) selects the session's tab and brings its window forward:
13
+ // { ok, tab, error }
14
+ // type(ctx, text) types text, then Enter on its own; null, or what went wrong
15
+ // titles(ctxs) Map of terminal device -> the title that tab shows, for
16
+ // the sessions it hosts
17
+ //
18
+ // ctx describes the session's terminal: { pid, tty, chain, env }, where chain
19
+ // is the session's process and its ancestors, nearest first, and env is the
20
+ // session's environment when it can be read (Linux).
21
+
22
+ const fs = require('fs');
23
+ const unix = require('./unix');
24
+ const tmux = require('./tmux');
25
+
26
+ const TITLE_REFRESH_MS = 3000;
27
+
28
+ // The process table, environments and tmux can be stood in for by tests.
29
+ function create({ name, backends, openFolder, pickFolder, defaultTerminal, processTable = unix.processTable, environment = unix.environment, tmux: mux = tmux }) {
30
+ const byId = new Map(backends.map((b) => [b.id, b]));
31
+
32
+ async function context(pid, table) {
33
+ table = table || (await processTable());
34
+ const self = table.get(pid);
35
+ if (!self) return null;
36
+ return { pid, tty: self.tty, chain: unix.ancestors(table, pid), env: environment(pid), table };
37
+ }
38
+
39
+ // The nearest terminal above the session is the one it runs in. A terminal
40
+ // started from another one sits under it, and inherits its environment, so
41
+ // the first match further up, or in the environment, could be the wrong one.
42
+ const owns = (b, p) => (b.processNames || []).some((n) => (n.endsWith('*') ? p.name.startsWith(n.slice(0, -1)) : p.name === n));
43
+ function hostOf(ctx) {
44
+ for (const p of ctx.chain) {
45
+ const backend = backends.find((b) => owns(b, p));
46
+ if (backend) return backend;
47
+ }
48
+ return backends.find((b) => b.hosts?.(ctx)) || null;
49
+ }
50
+
51
+ function terminals() {
52
+ return backends.filter((b) => b.open).map((b) => ({ id: b.id, name: b.name, available: b.available() }));
53
+ }
54
+
55
+ async function open(dir, command, { terminal } = {}) {
56
+ let backend = byId.get(terminal);
57
+ if (!backend?.open || !backend.available()) backend = byId.get(await defaultTerminal(backends));
58
+ if (!backend) return { ok: false, error: 'No supported terminal was found. Install one, or choose one in Settings.' };
59
+ return backend.open(dir, command);
60
+ }
61
+
62
+ // Nothing is typed while the session waits on a prompt or dialog, which
63
+ // typing could answer.
64
+ function waiting(statusFile) {
65
+ try {
66
+ return JSON.parse(fs.readFileSync(statusFile, 'utf8')).status === 'waiting';
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
71
+
72
+ async function focus(pid, { send, statusFile } = {}) {
73
+ const ctx = await context(pid);
74
+ if (!ctx) return { ok: false, error: 'That session is no longer running.' };
75
+ if (!ctx.tty) return { ok: false, error: 'This session has no terminal. It may be running in the background.' };
76
+
77
+ // In tmux, tmux selects the pane and types; the terminal showing tmux is
78
+ // then brought forward.
79
+ const pane = await mux.findPane(ctx.tty);
80
+ if (pane) {
81
+ const client = await mux.select(pane);
82
+ let raised = null;
83
+ if (client) {
84
+ const outer = await context(client.pid, ctx.table);
85
+ const host = outer && hostOf(outer);
86
+ raised = host ? await host.focus(outer) : null;
87
+ }
88
+ if (send) {
89
+ if (waiting(statusFile)) return { ok: false, error: 'It started waiting on a prompt or dialog, so nothing was typed. Answer that first.' };
90
+ const problem = await mux.type(pane, send);
91
+ if (problem) return { ok: false, error: `Couldn't send the question: ${problem}` };
92
+ }
93
+ if (!client && !send) return { ok: false, error: 'Its tmux session isn\'t shown in any terminal. Attach to it with "tmux attach".' };
94
+ return { ok: true, tab: true, terminal: raised?.ok ? `tmux in ${raised.terminal}` : 'tmux', sent: Boolean(send) };
95
+ }
96
+
97
+ const host = hostOf(ctx);
98
+ if (!host) return { ok: false, error: "Tabherd doesn't know the terminal this session runs in." };
99
+ const result = await host.focus(ctx);
100
+ if (!result.ok) return result;
101
+ if (send) {
102
+ if (!host.type) return { ok: false, error: `${host.name} can't be typed into from outside. Run the session inside tmux to use Catch up.` };
103
+ if (waiting(statusFile)) return { ok: false, error: 'It started waiting on a prompt or dialog, so nothing was typed. Answer that first.' };
104
+ const problem = await host.type(ctx, send);
105
+ if (problem) return { ok: false, error: `Couldn't send the question: ${problem}` };
106
+ }
107
+ return { ...result, terminal: host.name, sent: Boolean(send) };
108
+ }
109
+
110
+ // Titles are read in the background and kept by session PID.
111
+ const titles = new Map();
112
+ let scanning = false;
113
+ let lastScanAt = 0;
114
+
115
+ async function scanTitles(pids) {
116
+ const table = await processTable();
117
+ const byTty = new Map();
118
+ for (const pid of pids) {
119
+ const tty = table.get(pid)?.tty;
120
+ if (tty) byTty.set(tty, pid);
121
+ }
122
+ const found = new Map();
123
+ const take = (map) => {
124
+ for (const [tty, title] of map) if (byTty.has(tty) && title && !found.has(tty)) found.set(tty, title);
125
+ };
126
+ take(await mux.titles());
127
+ const hosted = new Map();
128
+ for (const pid of byTty.values()) {
129
+ const ctx = { pid, tty: table.get(pid).tty, chain: unix.ancestors(table, pid), env: environment(pid), table };
130
+ const host = hostOf(ctx);
131
+ if (!host?.titles || found.has(ctx.tty)) continue;
132
+ if (!hosted.has(host)) hosted.set(host, []);
133
+ hosted.get(host).push(ctx);
134
+ }
135
+ for (const [host, ctxs] of hosted) {
136
+ try {
137
+ take(await host.titles(ctxs));
138
+ } catch {}
139
+ }
140
+ titles.clear();
141
+ for (const [tty, pid] of byTty) {
142
+ const title = unix.titleKey(found.get(tty));
143
+ if (title) titles.set(pid, title);
144
+ }
145
+ }
146
+
147
+ function refreshTitles(pids) {
148
+ if (scanning || Date.now() - lastScanAt < TITLE_REFRESH_MS || !pids.length) return;
149
+ scanning = true;
150
+ lastScanAt = Date.now();
151
+ scanTitles(pids)
152
+ .catch(() => {})
153
+ .finally(() => (scanning = false));
154
+ }
155
+
156
+ return {
157
+ name,
158
+ terminals,
159
+ // Commands run in a POSIX shell, or are typed into the user's own one.
160
+ quote: unix.shQuote,
161
+ open,
162
+ focus,
163
+ pickFolder,
164
+ stop: unix.stop,
165
+ close: unix.close,
166
+ openFolder,
167
+ refreshTitles,
168
+ titleFor: (pid) => titles.get(pid) || null,
169
+ };
170
+ }
171
+
172
+ module.exports = { create };
@@ -0,0 +1,204 @@
1
+ 'use strict';
2
+
3
+ // What macOS and Linux share: the process table, a session's terminal device
4
+ // and the processes above it, ending a process tree, and running the
5
+ // command-line tools that drive terminals.
6
+
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const { execFile, spawn } = require('child_process');
10
+
11
+ // Runs a command and resolves to { ok, code, stdout, stderr }; never rejects.
12
+ // With TABHERD_DEBUG set, each command that fails is logged with its output.
13
+ function run(cmd, args, { timeout = 10000, env, input } = {}) {
14
+ return new Promise((resolve) => {
15
+ const child = execFile(cmd, args, { timeout, env, maxBuffer: 8 * 1024 * 1024 }, (err, stdout, stderr) => {
16
+ const result = { ok: !err, code: err ? (typeof err.code === 'number' ? err.code : -1) : 0, stdout: String(stdout), stderr: String(stderr || err?.message || '') };
17
+ if (!result.ok && process.env.TABHERD_DEBUG) {
18
+ console.error(`[debug] ${cmd} ${args.map((a) => JSON.stringify(a).slice(0, 120)).join(' ')}\n[debug] exit ${result.code}: ${result.stderr.trim().slice(0, 500)}`);
19
+ }
20
+ resolve(result);
21
+ });
22
+ if (input !== undefined) child.stdin.end(input);
23
+ });
24
+ }
25
+
26
+ // The full path of a command on the PATH, or null.
27
+ function which(cmd) {
28
+ for (const dir of (process.env.PATH || '').split(path.delimiter)) {
29
+ if (!dir) continue;
30
+ const file = path.join(dir, cmd);
31
+ try {
32
+ fs.accessSync(file, fs.constants.X_OK);
33
+ if (fs.statSync(file).isFile()) return file;
34
+ } catch {}
35
+ }
36
+ return null;
37
+ }
38
+
39
+ function detached(cmd, args, { env } = {}) {
40
+ return new Promise((resolve) => {
41
+ const child = spawn(cmd, args, { detached: true, stdio: 'ignore', env });
42
+ child.on('error', (err) => resolve({ ok: false, error: err.message }));
43
+ child.on('spawn', () => {
44
+ child.unref();
45
+ resolve({ ok: true });
46
+ });
47
+ });
48
+ }
49
+
50
+ // Every process: pid -> { pid, ppid, tty, name }. `tty` is a device path such
51
+ // as /dev/ttys003 or /dev/pts/3, or null for a process with no terminal.
52
+ async function processTable() {
53
+ const out = await run('ps', ['-A', '-o', 'pid=,ppid=,tty=,comm=']);
54
+ const table = new Map();
55
+ for (const line of out.stdout.split('\n')) {
56
+ const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/);
57
+ if (!m) continue;
58
+ const tty = m[3] === '?' || m[3] === '??' || m[3] === '-' ? null : `/dev/${m[3]}`;
59
+ table.set(Number(m[1]), { pid: Number(m[1]), ppid: Number(m[2]), tty, name: path.basename(m[4].trim()) });
60
+ }
61
+ return table;
62
+ }
63
+
64
+ // The process and its ancestors, nearest first.
65
+ function ancestors(table, pid) {
66
+ const chain = [];
67
+ const seen = new Set();
68
+ for (let p = table.get(pid); p && !seen.has(p.pid); p = table.get(p.ppid)) {
69
+ seen.add(p.pid);
70
+ chain.push(p);
71
+ }
72
+ return chain;
73
+ }
74
+
75
+ function descendants(table, pid) {
76
+ const children = new Map();
77
+ for (const p of table.values()) {
78
+ if (!children.has(p.ppid)) children.set(p.ppid, []);
79
+ children.get(p.ppid).push(p.pid);
80
+ }
81
+ const found = [];
82
+ const queue = [...(children.get(pid) || [])];
83
+ while (queue.length) {
84
+ const next = queue.shift();
85
+ if (found.includes(next)) continue;
86
+ found.push(next);
87
+ queue.push(...(children.get(next) || []));
88
+ }
89
+ return found;
90
+ }
91
+
92
+ // A process's environment. Linux only: macOS doesn't let one process read
93
+ // another's, so there it's null.
94
+ function environment(pid) {
95
+ try {
96
+ const raw = fs.readFileSync(`/proc/${pid}/environ`, 'utf8');
97
+ const env = {};
98
+ for (const entry of raw.split('\0')) {
99
+ const at = entry.indexOf('=');
100
+ if (at > 0) env[entry.slice(0, at)] = entry.slice(at + 1);
101
+ }
102
+ return env;
103
+ } catch {
104
+ return null;
105
+ }
106
+ }
107
+
108
+ const alive = (pid) => {
109
+ try {
110
+ process.kill(pid, 0);
111
+ return true;
112
+ } catch (err) {
113
+ return err.code === 'EPERM';
114
+ }
115
+ };
116
+
117
+ // Ends the session and everything it started, such as its shells and MCP
118
+ // servers: asked politely first, then forced after two seconds, as Stop on
119
+ // Windows forces it.
120
+ async function stop(pid) {
121
+ const table = await processTable();
122
+ if (!table.has(pid)) return { ok: false, error: 'That process has already ended.' };
123
+ const tree = [pid, ...descendants(table, pid)];
124
+ for (const p of tree.slice().reverse()) {
125
+ try {
126
+ process.kill(p, 'SIGTERM');
127
+ } catch {}
128
+ }
129
+ for (let waited = 0; waited < 2000 && tree.some(alive); waited += 100) await new Promise((r) => setTimeout(r, 100));
130
+ for (const p of tree.filter(alive)) {
131
+ try {
132
+ process.kill(p, 'SIGKILL');
133
+ } catch {}
134
+ }
135
+ if (alive(pid)) return { ok: false, error: `PID ${pid} didn't end.` };
136
+ return { ok: true };
137
+ }
138
+
139
+ // Shells, by the name ps gives them; a login shell's starts with a dash.
140
+ const SHELLS = /^-?(bash|zsh|fish|sh|dash|ksh|mksh|tcsh|csh|nu|elvish|xonsh)$/;
141
+
142
+ // Ends the session as Stop does, then the shell it ran in, if it ran in one,
143
+ // so the terminal closes that tab or pane, or tmux that pane.
144
+ async function close(pid) {
145
+ const table = await processTable();
146
+ const self = table.get(pid);
147
+ const shell = self && table.get(self.ppid);
148
+ const result = await stop(pid);
149
+ if (!result.ok) return result;
150
+ if (!shell || !SHELLS.test(shell.name)) return { ok: true, closedTab: false };
151
+ try {
152
+ process.kill(shell.pid, 'SIGHUP');
153
+ } catch {}
154
+ return { ok: true, closedTab: true };
155
+ }
156
+
157
+ // Single-quoted for a POSIX shell.
158
+ const shQuote = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
159
+
160
+ // The command line a new tab runs: `command` in `dir`, then the user's own
161
+ // shell, so the tab stays open at a prompt there after the command ends.
162
+ function shellLine(dir, command) {
163
+ return `cd ${shQuote(dir)} && ${command}; exec "\${SHELL:-/bin/sh}" -l`;
164
+ }
165
+
166
+ // That line run by the user's shell as an interactive login shell, which
167
+ // reads the files where `claude` is usually put on the PATH.
168
+ const userShell = () => process.env.SHELL || '/bin/bash';
169
+ const shellArgs = (dir, command) => [userShell(), '-lic', shellLine(dir, command)];
170
+ const shellCommand = (dir, command) => shellArgs(dir, command).map(shQuote).join(' ');
171
+
172
+ // The title Claude Code shows, without the spinner or status glyph in front.
173
+ const titleKey = (title) => String(title || '').replace(/^[^\p{L}\p{N}]+/u, '').trim();
174
+
175
+ // Whether a unix socket is at that path.
176
+ function isSocket(file) {
177
+ try {
178
+ return fs.statSync(file).isSocket();
179
+ } catch {
180
+ return false;
181
+ }
182
+ }
183
+
184
+ const pause = (ms) => new Promise((r) => setTimeout(r, ms));
185
+
186
+ module.exports = {
187
+ close,
188
+ run,
189
+ which,
190
+ detached,
191
+ processTable,
192
+ ancestors,
193
+ descendants,
194
+ environment,
195
+ alive,
196
+ stop,
197
+ shQuote,
198
+ shellLine,
199
+ shellArgs,
200
+ shellCommand,
201
+ titleKey,
202
+ isSocket,
203
+ pause,
204
+ };
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ // Operating systems without a driver yet: the dashboard works, but nothing
4
+ // that drives terminals or windows does.
5
+
6
+ const unix = require('./unix');
7
+
8
+ const notHere = (what) => async () => ({ ok: false, error: `${what} isn't supported on ${process.platform} yet.` });
9
+
10
+ module.exports = {
11
+ name: process.platform,
12
+ terminals: () => [],
13
+ quote: unix.shQuote,
14
+ open: notHere('Opening a terminal'),
15
+ focus: notHere('Going to a window'),
16
+ pickFolder: notHere('The folder picker'),
17
+ stop: unix.stop,
18
+ close: unix.close,
19
+ openFolder: () => {},
20
+ refreshTitles: () => {},
21
+ titleFor: () => null,
22
+ };
@@ -0,0 +1,103 @@
1
+ 'use strict';
2
+
3
+ // WezTerm, on macOS and Linux, through `wezterm cli`. Each WezTerm window
4
+ // process listens on its own socket, with no setup. It can select a pane, type
5
+ // into it and read its title, but not bring its window forward; the platform
6
+ // driver does that.
7
+
8
+ const fs = require('fs');
9
+ const os = require('os');
10
+ const path = require('path');
11
+ const unix = require('./unix');
12
+
13
+ const MAC_BIN = '/Applications/WezTerm.app/Contents/MacOS/wezterm';
14
+ const bin = () => unix.which('wezterm') || (fs.existsSync(MAC_BIN) ? MAC_BIN : null);
15
+
16
+ const socketDirs = () =>
17
+ [process.env.XDG_RUNTIME_DIR && path.join(process.env.XDG_RUNTIME_DIR, 'wezterm'), path.join(os.homedir(), '.local', 'share', 'wezterm')].filter(Boolean);
18
+
19
+ // The sockets of running WezTerms, the session's own first.
20
+ function sockets(table, ctx) {
21
+ const found = [];
22
+ if (ctx?.env?.WEZTERM_UNIX_SOCKET) found.push(ctx.env.WEZTERM_UNIX_SOCKET);
23
+ const own = ctx?.chain.find((p) => p.name === 'wezterm-gui');
24
+ const pids = [...(own ? [own.pid] : []), ...[...table.values()].filter((p) => p.name === 'wezterm-gui').map((p) => p.pid)];
25
+ for (const pid of pids) {
26
+ for (const dir of socketDirs()) {
27
+ const file = path.join(dir, `gui-sock-${pid}`);
28
+ if (unix.isSocket(file)) found.push(file);
29
+ }
30
+ }
31
+ return [...new Set(found)];
32
+ }
33
+
34
+ const cli = (socket, args) => unix.run(bin(), ['cli', '--no-auto-start', ...args], { env: { ...process.env, WEZTERM_UNIX_SOCKET: socket } });
35
+
36
+ async function panes(socket) {
37
+ const out = await cli(socket, ['list', '--format', 'json']);
38
+ if (!out.ok) return [];
39
+ try {
40
+ return JSON.parse(out.stdout);
41
+ } catch {
42
+ return [];
43
+ }
44
+ }
45
+
46
+ async function locate(ctx) {
47
+ for (const socket of sockets(ctx.table || (await unix.processTable()), ctx)) {
48
+ const pane = (await panes(socket)).find((p) => p.tty_name === ctx.tty);
49
+ if (pane) return { socket, pane };
50
+ }
51
+ return null;
52
+ }
53
+
54
+ function backend({ raise } = {}) {
55
+ return {
56
+ id: 'wezterm',
57
+ name: 'WezTerm',
58
+ processNames: ['wezterm-gui'],
59
+ available: () => Boolean(bin()),
60
+ hosts: (ctx) => ctx.chain.some((p) => p.name === 'wezterm-gui'),
61
+ async open(dir, command) {
62
+ const socket = sockets(await unix.processTable())[0];
63
+ if (socket) {
64
+ const out = await cli(socket, ['spawn', '--cwd', dir, '--', ...unix.shellArgs(dir, command)]);
65
+ if (out.ok) {
66
+ if (raise) await raise({ title: null });
67
+ return { ok: true };
68
+ }
69
+ }
70
+ if (!bin()) return { ok: false, error: "WezTerm wasn't found." };
71
+ return unix.detached(bin(), ['start', '--cwd', dir, '--', ...unix.shellArgs(dir, command)]);
72
+ },
73
+ async focus(ctx) {
74
+ const at = await locate(ctx);
75
+ if (!at) return { ok: false, error: "WezTerm didn't list this session's pane." };
76
+ const out = await cli(at.socket, ['activate-pane', '--pane-id', String(at.pane.pane_id)]);
77
+ if (!out.ok) return { ok: false, error: `WezTerm couldn't go to it: ${out.stderr.trim()}` };
78
+ const raised = raise ? await raise({ ...ctx, title: at.pane.window_title }) : false;
79
+ return { ok: true, tab: true, raised };
80
+ },
81
+ // Sent as a paste, marked as one if the session asked for that; then a
82
+ // carriage return on its own.
83
+ async type(ctx, text) {
84
+ const at = await locate(ctx);
85
+ if (!at) return "WezTerm didn't list this session's pane";
86
+ const id = String(at.pane.pane_id);
87
+ let out = await cli(at.socket, ['send-text', '--pane-id', id, '--', text]);
88
+ if (!out.ok) return `WezTerm couldn't type into it: ${out.stderr.trim()}`;
89
+ await unix.pause(300);
90
+ out = await cli(at.socket, ['send-text', '--no-paste', '--pane-id', id, '--', '\r']);
91
+ return out.ok ? null : `WezTerm couldn't press Enter: ${out.stderr.trim()}`;
92
+ },
93
+ async titles(ctxs) {
94
+ const map = new Map();
95
+ for (const socket of sockets(ctxs[0]?.table || (await unix.processTable()), ctxs[0])) {
96
+ for (const p of await panes(socket)) if (p.tty_name && p.title) map.set(p.tty_name, p.title);
97
+ }
98
+ return map;
99
+ },
100
+ };
101
+ }
102
+
103
+ module.exports = { backend };
@@ -0,0 +1,125 @@
1
+ param([int]$TargetPid)
2
+
3
+ # Ends a session and closes its terminal tab. It ends the session's process,
4
+ # and the ones it started, then, if it ran in a shell, as it does in a
5
+ # terminal tab, types `exit` into that shell. The shell exits as if you'd
6
+ # typed it, so Windows Terminal closes the tab instead of leaving a "process
7
+ # exited" message. A shell that won't take the typing is ended instead.
8
+ # Prints one line of JSON.
9
+
10
+ $ErrorActionPreference = 'Stop'
11
+ $ProgressPreference = 'SilentlyContinue'
12
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
13
+ Add-Type @"
14
+ using System; using System.Collections.Generic; using System.Runtime.InteropServices;
15
+
16
+ // An INPUT_RECORD holding a KEY_EVENT_RECORD, flattened.
17
+ [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)]
18
+ public struct KeyRecord {
19
+ [FieldOffset(0)] public ushort EventType;
20
+ [FieldOffset(4)] public int KeyDown;
21
+ [FieldOffset(8)] public ushort RepeatCount;
22
+ [FieldOffset(10)] public ushort VirtualKeyCode;
23
+ [FieldOffset(12)] public ushort VirtualScanCode;
24
+ [FieldOffset(14)] public char UnicodeChar;
25
+ [FieldOffset(16)] public uint ControlKeyState;
26
+ }
27
+
28
+ public static class C {
29
+ [DllImport("kernel32.dll")] public static extern bool FreeConsole();
30
+ [DllImport("kernel32.dll")] public static extern bool AttachConsole(uint pid);
31
+ [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr CreateFile(string name, uint access, uint share, IntPtr security, uint disposition, uint flags, IntPtr template);
32
+ [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr handle);
33
+ [DllImport("kernel32.dll", EntryPoint = "WriteConsoleInputW")] public static extern bool WriteConsoleInput(IntPtr input, KeyRecord[] records, uint count, out uint written);
34
+ [DllImport("kernel32.dll")] public static extern bool SetConsoleCtrlHandler(IntPtr handler, bool add);
35
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern short VkKeyScan(char c);
36
+ [DllImport("user32.dll")] public static extern uint MapVirtualKey(uint code, uint type);
37
+
38
+ // The input buffer of whichever console this process is attached to.
39
+ public static IntPtr OpenConsoleInput() {
40
+ return CreateFile("CONIN$", 0xC0000000, 3, IntPtr.Zero, 3, 0, IntPtr.Zero);
41
+ }
42
+
43
+ // Key-down and key-up records for each character, as if typed.
44
+ public static bool Type(IntPtr input, string text) {
45
+ var records = new List<KeyRecord>();
46
+ foreach (char c in text) {
47
+ short scan = VkKeyScan(c);
48
+ ushort vk = (ushort)(scan == -1 ? 0 : scan & 0xff);
49
+ uint shift = scan != -1 && (scan & 0x100) != 0 ? 0x10u : 0u;
50
+ for (int down = 1; down >= 0; down--) {
51
+ records.Add(new KeyRecord { EventType = 1, KeyDown = down, RepeatCount = 1, VirtualKeyCode = vk,
52
+ VirtualScanCode = (ushort)MapVirtualKey(vk, 0), UnicodeChar = c, ControlKeyState = shift });
53
+ }
54
+ }
55
+ uint written;
56
+ return WriteConsoleInput(input, records.ToArray(), (uint)records.Count, out written) && written == records.Count;
57
+ }
58
+ }
59
+ "@
60
+
61
+ function Out-Result($ok, $props) {
62
+ $props.ok = $ok
63
+ [Console]::Out.WriteLine(($props | ConvertTo-Json -Compress))
64
+ exit 0
65
+ }
66
+
67
+ function Wait-Gone([int]$id) {
68
+ for ($i = 0; $i -lt 40 -and (Get-Process -Id $id -ErrorAction SilentlyContinue); $i++) { Start-Sleep -Milliseconds 100 }
69
+ return -not (Get-Process -Id $id -ErrorAction SilentlyContinue)
70
+ }
71
+
72
+ $self = Get-CimInstance Win32_Process -Filter "ProcessId=$TargetPid"
73
+ if (-not $self) { Out-Result $false @{ error = 'That process has already ended.' } }
74
+ # The shell it runs in, if it runs in one. Launchers can come between, each
75
+ # started moments before the next: npm's .cmd wrappers (cmd /c), Node running
76
+ # a CLI that starts the real program, and version managers' shims, such as
77
+ # mise's and nvm's, which start the real one, sometimes through each other.
78
+ # Those end with it. Anything else, such as the terminal or an editor, stops
79
+ # the search. A parent that started after its child has only been given the
80
+ # real parent's old PID.
81
+ function Test-Shell($p) {
82
+ if ($p.Name -eq 'cmd.exe') { return $p.CommandLine -notmatch '\s/[cC]\s' }
83
+ return $p.Name -match '^(pwsh|powershell|nu|bash|zsh|fish)\.exe$'
84
+ }
85
+ $Launchers = '^(node|bun|deno|cmd|mise|volta|volta-shim|fnm|proto|npx|npm|pnpm|yarn|claude|codex)(-[\w.-]+)?\.exe$'
86
+ $top = $self
87
+ $shell = $null
88
+ for ($i = 0; $i -lt 8; $i++) {
89
+ $parent = Get-CimInstance Win32_Process -Filter "ProcessId=$($top.ParentProcessId)"
90
+ if (-not $parent -or $parent.CreationDate -gt $top.CreationDate) { break }
91
+ if (Test-Shell $parent) { $shell = $parent; break }
92
+ if ($parent.Name -notmatch $Launchers -or ($top.CreationDate - $parent.CreationDate).TotalSeconds -gt 30) { break }
93
+ $top = $parent
94
+ }
95
+ # Only a launcher that's there for this session ends with it.
96
+ if (-not $shell) { $top = $self }
97
+
98
+ & taskkill.exe /PID $top.ProcessId /T /F *> $null
99
+ if (-not (Wait-Gone $TargetPid) -or -not (Wait-Gone $top.ProcessId)) { Out-Result $false @{ error = "PID $TargetPid didn't end." } }
100
+ if (-not $shell) { Out-Result $true @{ closedTab = $false } }
101
+
102
+ # Typing into the tab's console. A Ctrl+C there would otherwise end this too.
103
+ [void][C]::SetConsoleCtrlHandler([IntPtr]::Zero, $true)
104
+ [void][C]::FreeConsole()
105
+ $typed = $false
106
+ if ([C]::AttachConsole([uint32]$shell.ProcessId)) {
107
+ try {
108
+ $in = [C]::OpenConsoleInput()
109
+ if ($in -ne [IntPtr]-1) {
110
+ try {
111
+ # Lets the shell come back to its prompt first.
112
+ Start-Sleep -Milliseconds 300
113
+ $typed = [C]::Type($in, "exit`r")
114
+ } finally {
115
+ [void][C]::CloseHandle($in)
116
+ }
117
+ }
118
+ } finally {
119
+ [void][C]::FreeConsole()
120
+ }
121
+ }
122
+ if (-not (Wait-Gone $shell.ProcessId)) {
123
+ Stop-Process -Id $shell.ProcessId -Force -ErrorAction SilentlyContinue
124
+ }
125
+ Out-Result $true @{ closedTab = $true; typed = $typed }