tmux-ide 2.9.18 → 2.9.21

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 (97) hide show
  1. package/bin/cli.js +14703 -3882
  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 +2 -0
  7. package/packages/contracts/src/plain-text.ts +61 -0
  8. package/packages/daemon/dist/command-center/command-catalog-routes.js +78 -0
  9. package/packages/daemon/dist/command-center/plugin-routes.js +84 -0
  10. package/packages/daemon/dist/command-center/server.js +13 -0
  11. package/packages/daemon/dist/doctor.js +12 -5
  12. package/packages/daemon/dist/lib/cli-action-bridge.js +15 -0
  13. package/packages/daemon/dist/lib/daemon-embed.js +24 -1
  14. package/packages/daemon/dist/lib/headless-daemon.js +1 -0
  15. package/packages/daemon/dist/lib/native-split-capability.js +13 -15
  16. package/packages/daemon/dist/lib/worktree.js +18 -0
  17. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  18. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  19. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  20. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  21. package/packages/daemon/dist/plugins/action-catalog.js +129 -0
  22. package/packages/daemon/dist/plugins/action-cli.js +212 -0
  23. package/packages/daemon/dist/plugins/api-table.js +303 -0
  24. package/packages/daemon/dist/plugins/cli.js +556 -0
  25. package/packages/daemon/dist/plugins/consent.js +107 -0
  26. package/packages/daemon/dist/plugins/daemon-plugins.js +132 -0
  27. package/packages/daemon/dist/plugins/discovery.js +142 -0
  28. package/packages/daemon/dist/plugins/examples/worktree-tasks.js +115 -0
  29. package/packages/daemon/dist/plugins/exec-sandbox.js +202 -0
  30. package/packages/daemon/dist/plugins/host/actions-prelude.js +279 -0
  31. package/packages/daemon/dist/plugins/host/entry.js +4 -0
  32. package/packages/daemon/dist/plugins/host/host-api-prelude.js +232 -0
  33. package/packages/daemon/dist/plugins/host/lua-state.js +493 -0
  34. package/packages/daemon/dist/plugins/host/main.js +322 -0
  35. package/packages/daemon/dist/plugins/host/sandbox.js +299 -0
  36. package/packages/daemon/dist/plugins/host-calls.js +279 -0
  37. package/packages/daemon/dist/plugins/manifest.js +69 -0
  38. package/packages/daemon/dist/plugins/plugin-exec.js +261 -0
  39. package/packages/daemon/dist/plugins/plugin-log.js +54 -0
  40. package/packages/daemon/dist/plugins/plugin-store.js +74 -0
  41. package/packages/daemon/dist/plugins/protocol.js +252 -0
  42. package/packages/daemon/dist/plugins/safe-files.js +97 -0
  43. package/packages/daemon/dist/plugins/supervisor.js +790 -0
  44. package/packages/daemon/dist/plugins/worktree-calls.js +154 -0
  45. package/packages/daemon/dist/terminal/mirror/session-channel.js +3 -2
  46. package/packages/daemon/dist/terminal/mirror/window-split-authority.js +1 -1
  47. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +27 -0
  48. package/packages/daemon/dist/tui/mirror/runtime/application-home-experience.js +2 -0
  49. package/packages/daemon/dist/tui/mirror/runtime/application-palette-command-owner.js +30 -2
  50. package/packages/daemon/dist/tui/mirror/runtime/application-plugin-commands.js +152 -0
  51. package/packages/daemon/dist/tui/mirror/runtime/application-plugin-form.js +251 -0
  52. package/packages/daemon/dist/tui/mirror/workspace/application-command-description.js +14 -0
  53. package/packages/daemon/dist/tui/mirror/workspace/palette-list-layout.js +5 -0
  54. package/packages/daemon/src/command-center/command-catalog-routes.ts +116 -0
  55. package/packages/daemon/src/command-center/plugin-routes.ts +110 -0
  56. package/packages/daemon/src/command-center/server.ts +15 -0
  57. package/packages/daemon/src/doctor.ts +12 -5
  58. package/packages/daemon/src/lib/cli-action-bridge.ts +19 -0
  59. package/packages/daemon/src/lib/daemon-embed.ts +42 -0
  60. package/packages/daemon/src/lib/headless-daemon.ts +1 -0
  61. package/packages/daemon/src/lib/native-split-capability.ts +12 -13
  62. package/packages/daemon/src/lib/worktree.ts +16 -0
  63. package/packages/daemon/src/plugins/action-catalog.ts +141 -0
  64. package/packages/daemon/src/plugins/action-cli.ts +248 -0
  65. package/packages/daemon/src/plugins/api-table.ts +346 -0
  66. package/packages/daemon/src/plugins/cli.ts +630 -0
  67. package/packages/daemon/src/plugins/consent.ts +125 -0
  68. package/packages/daemon/src/plugins/daemon-plugins.ts +182 -0
  69. package/packages/daemon/src/plugins/discovery.ts +176 -0
  70. package/packages/daemon/src/plugins/examples/worktree-tasks.ts +120 -0
  71. package/packages/daemon/src/plugins/exec-sandbox.ts +264 -0
  72. package/packages/daemon/src/plugins/host/actions-prelude.ts +280 -0
  73. package/packages/daemon/src/plugins/host/entry.ts +5 -0
  74. package/packages/daemon/src/plugins/host/host-api-prelude.ts +233 -0
  75. package/packages/daemon/src/plugins/host/lua-state.ts +557 -0
  76. package/packages/daemon/src/plugins/host/main.ts +359 -0
  77. package/packages/daemon/src/plugins/host/sandbox.ts +301 -0
  78. package/packages/daemon/src/plugins/host-calls.ts +343 -0
  79. package/packages/daemon/src/plugins/manifest.ts +74 -0
  80. package/packages/daemon/src/plugins/plugin-exec.ts +326 -0
  81. package/packages/daemon/src/plugins/plugin-log.ts +63 -0
  82. package/packages/daemon/src/plugins/plugin-store.ts +80 -0
  83. package/packages/daemon/src/plugins/protocol.ts +275 -0
  84. package/packages/daemon/src/plugins/safe-files.ts +105 -0
  85. package/packages/daemon/src/plugins/supervisor.ts +954 -0
  86. package/packages/daemon/src/plugins/worktree-calls.ts +183 -0
  87. package/packages/daemon/src/terminal/mirror/session-channel.ts +3 -2
  88. package/packages/daemon/src/terminal/mirror/window-split-authority.ts +3 -2
  89. package/packages/daemon/src/tui/mirror/runtime/application-fleet-switcher.tsx +3 -1
  90. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +32 -0
  91. package/packages/daemon/src/tui/mirror/runtime/application-home-experience.ts +2 -0
  92. package/packages/daemon/src/tui/mirror/runtime/application-palette-command-owner.ts +42 -2
  93. package/packages/daemon/src/tui/mirror/runtime/application-palette-preview.tsx +7 -1
  94. package/packages/daemon/src/tui/mirror/runtime/application-plugin-commands.ts +229 -0
  95. package/packages/daemon/src/tui/mirror/runtime/application-plugin-form.ts +312 -0
  96. package/packages/daemon/src/tui/mirror/workspace/application-command-description.ts +44 -2
  97. package/packages/daemon/src/tui/mirror/workspace/palette-list-layout.ts +4 -0
@@ -0,0 +1,556 @@
1
+ /**
2
+ * `tmux-ide lua …` and `tmux-ide plugin …`.
3
+ */
4
+ import { execFileSync } from "node:child_process";
5
+ import { closeSync, existsSync, realpathSync, mkdirSync, openSync, readFileSync, readSync, statSync, writeFileSync, } from "node:fs";
6
+ import { basename, join } from "node:path";
7
+ import { parseArgs } from "node:util";
8
+ import { terminalSafe, terminalSafeBlock } from "@tmux-ide/contracts";
9
+ import { grantConsent, hashPluginDirectory, revokeConsent } from "./consent.js";
10
+ import { discoverPlugins, pluginPaths } from "./discovery.js";
11
+ import { findOnPath } from "./exec-sandbox.js";
12
+ import { PLUGIN_EXAMPLES } from "./examples/worktree-tasks.js";
13
+ import { API_ENTRIES, findApiEntry, suggestApiEntries } from "./api-table.js";
14
+ import { formatPluginLogEntry, pluginLogPath, readPluginLog, } from "./plugin-log.js";
15
+ import { PLUGIN_API_VERSION } from "./protocol.js";
16
+ /**
17
+ * The same io, with every line it prints and every question it asks made
18
+ * terminal-safe: plugin names, titles, logs, values and errors all pass
19
+ * through here, and none of them may drive the terminal.
20
+ */
21
+ export function terminalSafeIo(io) {
22
+ return {
23
+ ...io,
24
+ out: (text) => io.out(terminalSafeBlock(text)),
25
+ err: (text) => io.err(terminalSafeBlock(text)),
26
+ ask: (question) => io.ask(terminalSafe(question)),
27
+ };
28
+ }
29
+ export class PluginCliError extends Error {
30
+ exitCode;
31
+ constructor(message, exitCode = 1) {
32
+ super(message);
33
+ this.name = "PluginCliError";
34
+ this.exitCode = exitCode;
35
+ }
36
+ }
37
+ export const LUA_USAGE = `Usage:
38
+ tmux-ide lua run <file | -> [--timeout <ms>] [--json] Run a Lua file once against the daemon
39
+ tmux-ide lua run -e <code> [--timeout <ms>] [--json] Run Lua source given inline
40
+ tmux-ide lua api [--json] List the Lua API (version ${PLUGIN_API_VERSION})
41
+ tmux-ide lua describe <name> [--json] Describe one API entry, e.g. ide.log.info`;
42
+ export const PLUGIN_USAGE = `Usage:
43
+ tmux-ide plugin list [--json] Show the plugin host and every plugin's state
44
+ tmux-ide plugin reload [name] [--json] Discover plugins again and reload all, or one
45
+ tmux-ide plugin logs [name] [-n <lines>] [-f] Show ~/.tmux-ide/logs/plugins.log
46
+ tmux-ide plugin consent <name> [--yes] Review a plugin's permissions and allow it to run
47
+ tmux-ide plugin revoke <name> Stop a plugin and withdraw consent
48
+ tmux-ide plugin example [name] List the example plugins, or copy one into ~/.tmux-ide/plugins`;
49
+ export async function callDaemon(io, method, path, body) {
50
+ const daemon = await io.daemon();
51
+ if (!daemon)
52
+ throw new PluginCliError("The tmux-ide daemon is not running and could not be started. Run `tmux-ide doctor`.");
53
+ let response;
54
+ try {
55
+ response = await io.fetch(`${daemon.baseUrl}${path}`, {
56
+ method,
57
+ headers: {
58
+ ...(body !== undefined ? { "Content-Type": "application/json" } : {}),
59
+ ...(daemon.ownerToken ? { Authorization: `Bearer ${daemon.ownerToken}` } : {}),
60
+ },
61
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
62
+ });
63
+ }
64
+ catch (error) {
65
+ throw new PluginCliError(`Could not reach the daemon: ${error.message}`);
66
+ }
67
+ let payload;
68
+ try {
69
+ payload = await response.json();
70
+ }
71
+ catch {
72
+ throw new PluginCliError(`The daemon answered ${response.status} without JSON`);
73
+ }
74
+ if (!response.ok) {
75
+ const message = payload && typeof payload === "object" && "error" in payload
76
+ ? String(payload.error)
77
+ : `HTTP ${response.status}`;
78
+ throw new PluginCliError(message);
79
+ }
80
+ return payload;
81
+ }
82
+ export function formatValue(value) {
83
+ return typeof value === "string" ? value : JSON.stringify(value);
84
+ }
85
+ export function formatRunResult(result) {
86
+ const stdout = [];
87
+ const stderr = [];
88
+ for (const log of result.logs) {
89
+ if (log.level === "info")
90
+ stdout.push(log.message);
91
+ else
92
+ stderr.push(`${log.level}: ${log.message}`);
93
+ }
94
+ if (result.ok) {
95
+ for (const value of result.values ?? [])
96
+ stdout.push(formatValue(value));
97
+ }
98
+ else {
99
+ stderr.push(`error: ${result.error ?? "unknown error"}`);
100
+ }
101
+ return { stdout, stderr };
102
+ }
103
+ export function formatApiList(entries = API_ENTRIES) {
104
+ const width = Math.max(...entries.map((entry) => entry.signature.length));
105
+ const lines = [`tmux-ide Lua API ${PLUGIN_API_VERSION}`, ""];
106
+ for (const entry of entries) {
107
+ const tag = entry.stability === "stable" ? "" : ` [${entry.stability}]`;
108
+ lines.push(` ${entry.signature.padEnd(width)} ${entry.summary}${tag}`);
109
+ }
110
+ lines.push("", "More: tmux-ide lua describe <name>");
111
+ return lines.join("\n");
112
+ }
113
+ export function formatApiEntry(entry) {
114
+ const lines = [entry.signature, "", entry.summary];
115
+ if (entry.details)
116
+ lines.push("", entry.details);
117
+ if (entry.errors?.length)
118
+ lines.push("", `Errors: ${entry.errors.join(", ")}`);
119
+ if (entry.example)
120
+ lines.push("", "Example:", ` ${entry.example}`);
121
+ lines.push("", `Since API ${entry.since}, ${entry.stability}.`);
122
+ return lines.join("\n");
123
+ }
124
+ export function formatPluginStatus(status) {
125
+ const lines = [
126
+ status.host.running
127
+ ? `Plugin host: running (pid ${status.host.pid}, ${status.host.restarts} restarts)`
128
+ : "Plugin host: not running",
129
+ ];
130
+ if (status.plugins.length === 0) {
131
+ lines.push("No plugins. Add ~/.tmux-ide/init.lua or a directory in ~/.tmux-ide/plugins/.");
132
+ return lines.join("\n");
133
+ }
134
+ const width = Math.max(...status.plugins.map((plugin) => plugin.name.length));
135
+ for (const plugin of status.plugins) {
136
+ const memory = plugin.memoryBytes !== undefined
137
+ ? ` ${(plugin.memoryBytes / (1024 * 1024)).toFixed(1)} MiB`
138
+ : "";
139
+ lines.push(` ${plugin.name.padEnd(width)} ${plugin.state}${memory}`);
140
+ if (plugin.error)
141
+ lines.push(` ${" ".repeat(width)} ${plugin.error.split("\n")[0]}`);
142
+ }
143
+ return lines.join("\n");
144
+ }
145
+ async function luaCli(argv, io) {
146
+ const [sub, ...rest] = argv;
147
+ const { values, positionals } = parseArgs({
148
+ args: [...rest],
149
+ allowPositionals: true,
150
+ strict: true,
151
+ options: {
152
+ json: { type: "boolean" },
153
+ eval: { type: "string", short: "e" },
154
+ timeout: { type: "string" },
155
+ help: { type: "boolean", short: "h" },
156
+ },
157
+ });
158
+ if (values.help || sub === "help" || sub === "--help" || sub === "-h") {
159
+ io.out(LUA_USAGE);
160
+ return 0;
161
+ }
162
+ if (!sub)
163
+ throw new PluginCliError(LUA_USAGE, 2);
164
+ switch (sub) {
165
+ case "api":
166
+ io.out(values.json
167
+ ? JSON.stringify({ api: PLUGIN_API_VERSION, entries: API_ENTRIES }, null, 2)
168
+ : formatApiList());
169
+ return 0;
170
+ case "describe": {
171
+ const name = positionals[0];
172
+ if (!name)
173
+ throw new PluginCliError(`Name an entry to describe.\n${LUA_USAGE}`, 2);
174
+ const entry = findApiEntry(name);
175
+ if (!entry) {
176
+ const close = suggestApiEntries(name).map((candidate) => candidate.name);
177
+ throw new PluginCliError(`No API entry named '${name}'.${close.length ? ` Did you mean: ${close.join(", ")}?` : " See `tmux-ide lua api`."}`);
178
+ }
179
+ io.out(values.json ? JSON.stringify(entry, null, 2) : formatApiEntry(entry));
180
+ return 0;
181
+ }
182
+ case "run": {
183
+ let code;
184
+ let chunkName;
185
+ if (values.eval !== undefined) {
186
+ if (positionals.length > 0)
187
+ throw new PluginCliError("Give either a file or -e, not both.", 2);
188
+ code = values.eval;
189
+ chunkName = "=(command line)";
190
+ }
191
+ else {
192
+ const file = positionals[0];
193
+ if (!file)
194
+ throw new PluginCliError(`Name a file, - for stdin, or use -e.\n${LUA_USAGE}`, 2);
195
+ code = file === "-" ? io.readStdin() : io.readFile(file);
196
+ chunkName = file === "-" ? "=stdin" : `@${basename(file)}`;
197
+ }
198
+ let budgetMs;
199
+ if (values.timeout !== undefined) {
200
+ budgetMs = Number(values.timeout);
201
+ if (!Number.isInteger(budgetMs) || budgetMs < 10 || budgetMs > 600_000)
202
+ throw new PluginCliError("--timeout must be a whole number of milliseconds from 10 to 600000.", 2);
203
+ }
204
+ const { result } = await callDaemon(io, "POST", "/api/v2/lua/run", {
205
+ code,
206
+ chunkName,
207
+ ...(budgetMs !== undefined ? { budgetMs } : {}),
208
+ });
209
+ if (values.json) {
210
+ io.out(JSON.stringify(result, null, 2));
211
+ }
212
+ else {
213
+ const formatted = formatRunResult(result);
214
+ for (const line of formatted.stdout)
215
+ io.out(line);
216
+ for (const line of formatted.stderr)
217
+ io.err(line);
218
+ }
219
+ return result.ok ? 0 : 1;
220
+ }
221
+ default:
222
+ throw new PluginCliError(`Unknown lua command '${sub}'.\n${LUA_USAGE}`, 2);
223
+ }
224
+ }
225
+ async function followLog(path, plugin, io) {
226
+ let offset = existsSync(path) ? statSync(path).size : 0;
227
+ let pending = "";
228
+ for (;;) {
229
+ await io.sleep(500);
230
+ if (!existsSync(path))
231
+ continue;
232
+ const size = statSync(path).size;
233
+ if (size < offset)
234
+ offset = 0; // rotated
235
+ if (size === offset)
236
+ continue;
237
+ const fd = openSync(path, "r");
238
+ try {
239
+ const buffer = Buffer.alloc(size - offset);
240
+ readSync(fd, buffer, 0, buffer.length, offset);
241
+ offset = size;
242
+ pending += buffer.toString("utf8");
243
+ }
244
+ finally {
245
+ closeSync(fd);
246
+ }
247
+ const lines = pending.split("\n");
248
+ pending = lines.pop() ?? "";
249
+ for (const line of lines) {
250
+ try {
251
+ const entry = JSON.parse(line);
252
+ if (!plugin || entry.plugin === plugin)
253
+ io.out(formatPluginLogEntry(entry));
254
+ }
255
+ catch {
256
+ // torn line
257
+ }
258
+ }
259
+ }
260
+ }
261
+ /**
262
+ * The only programs consent does not call full control: each prints or
263
+ * transforms text and has no option, expression or config that starts
264
+ * another program. Matched exactly (case included), on both the listed
265
+ * name and the real file it resolves to. Anything else may run other
266
+ * commands, or drive tmux or tmux-ide, and consent says so.
267
+ *
268
+ * - cat, head, tail, wc, cut, tr: print or count parts of files; no exec option
269
+ * (unlike sort's --compress-program, rg's --pre, find's -exec, tar's --to-command).
270
+ * - jq: a JSON filter language with no builtin that runs a program.
271
+ * - echo, printf, true, false, pwd, basename, dirname: print fixed or derived strings.
272
+ * - date, uname, whoami, id: print system facts (setting the clock needs root).
273
+ * - ls, stat: list files and their metadata.
274
+ */
275
+ export const NOT_FULL_CONTROL_PROGRAMS = new Set([
276
+ "cat",
277
+ "head",
278
+ "tail",
279
+ "wc",
280
+ "cut",
281
+ "tr",
282
+ "jq",
283
+ "echo",
284
+ "printf",
285
+ "true",
286
+ "false",
287
+ "pwd",
288
+ "basename",
289
+ "dirname",
290
+ "date",
291
+ "uname",
292
+ "whoami",
293
+ "id",
294
+ "ls",
295
+ "stat",
296
+ ]);
297
+ /**
298
+ * Whether consent must call `program` full control: unless both its name
299
+ * and the real file it resolves to on PATH are on the short list above.
300
+ */
301
+ export function givesFullControl(program, path = process.env.PATH ?? "") {
302
+ if (!NOT_FULL_CONTROL_PROGRAMS.has(program))
303
+ return true;
304
+ const found = findOnPath(program, path);
305
+ if (!found)
306
+ return false;
307
+ try {
308
+ return !NOT_FULL_CONTROL_PROGRAMS.has(basename(realpathSync(found)));
309
+ }
310
+ catch {
311
+ return true;
312
+ }
313
+ }
314
+ export function describeForConsent(plugin) {
315
+ const { manifest } = plugin;
316
+ const exec = manifest.capabilities.exec ?? [];
317
+ const fullControl = exec.filter((program) => givesFullControl(program));
318
+ const asks = [
319
+ manifest.capabilities.shell
320
+ ? "run ANY shell command line, with full access to your account"
321
+ : null,
322
+ exec.length > 0
323
+ ? `run these programs: ${exec.join(", ")}. A program it may run can usually do anything your account can`
324
+ : null,
325
+ fullControl.length > 0
326
+ ? `NOTE: ${fullControl.join(", ")} can run other commands or drive tmux, so ${fullControl.length === 1 ? "it gives" : "they give"} full control of your account`
327
+ : null,
328
+ manifest.capabilities.worktree
329
+ ? "create, open and remove git worktrees and their sessions (plain sessions, with git hooks off: no layout or hook from the repository or a branch runs)"
330
+ : null,
331
+ manifest.capabilities["panes.send"]
332
+ ? "type into your terminals and run commands there, which gives full access to your account"
333
+ : null,
334
+ manifest.capabilities.keys ? "add key bindings" : null,
335
+ manifest.capabilities.sidebar ? "add rows to the sidebar" : null,
336
+ manifest.capabilities.status ? "add status items" : null,
337
+ ].filter((line) => line !== null);
338
+ return [
339
+ `${manifest.name} ${manifest.version}${plugin.reason === "changed" ? " (changed since you last allowed it)" : ""}`,
340
+ ...(manifest.description ? [manifest.description] : []),
341
+ `Directory: ${plugin.path}`,
342
+ `Content: ${plugin.hash}`,
343
+ "",
344
+ "It asks to:",
345
+ ...(asks.length > 0 ? asks.map((line) => ` - ${line}`) : [" - nothing beyond logging"]),
346
+ "",
347
+ "Every plugin can read what your terminals show, list your panes and run",
348
+ "tmux-ide's pane and window actions. Allow only plugins you trust.",
349
+ ].join("\n");
350
+ }
351
+ async function reloadAfterConsentChange(io, name) {
352
+ try {
353
+ const status = await callDaemon(io, "POST", "/api/v2/plugins/reload", {
354
+ name,
355
+ });
356
+ const plugin = status.plugins.find((candidate) => candidate.name === name);
357
+ if (plugin)
358
+ io.out(`${name}: ${plugin.state}${plugin.error ? ` (${plugin.error.split("\n")[0]})` : ""}`);
359
+ }
360
+ catch (error) {
361
+ io.err(`The daemon will pick this up on its next reload (${error.message}).`);
362
+ }
363
+ }
364
+ async function pluginCli(argv, io) {
365
+ const [sub, ...rest] = argv;
366
+ const { values, positionals } = parseArgs({
367
+ args: [...rest],
368
+ allowPositionals: true,
369
+ strict: true,
370
+ options: {
371
+ json: { type: "boolean" },
372
+ follow: { type: "boolean", short: "f" },
373
+ yes: { type: "boolean", short: "y" },
374
+ lines: { type: "string", short: "n" },
375
+ help: { type: "boolean", short: "h" },
376
+ },
377
+ });
378
+ if (values.help || sub === "help" || sub === "--help" || sub === "-h") {
379
+ io.out(PLUGIN_USAGE);
380
+ return 0;
381
+ }
382
+ if (!sub)
383
+ throw new PluginCliError(PLUGIN_USAGE, 2);
384
+ switch (sub) {
385
+ case "list": {
386
+ const status = await callDaemon(io, "GET", "/api/v2/plugins");
387
+ io.out(values.json ? JSON.stringify(status, null, 2) : formatPluginStatus(status));
388
+ return 0;
389
+ }
390
+ case "reload": {
391
+ const name = positionals[0];
392
+ const status = await callDaemon(io, "POST", "/api/v2/plugins/reload", name ? { name } : {});
393
+ io.out(values.json ? JSON.stringify(status, null, 2) : formatPluginStatus(status));
394
+ const failed = status.plugins.some((plugin) => (!name || plugin.name === name) && plugin.state !== "loaded");
395
+ return failed ? 1 : 0;
396
+ }
397
+ case "consent": {
398
+ const name = positionals[0];
399
+ if (!name)
400
+ throw new PluginCliError(`Name the plugin to consent to.\n${PLUGIN_USAGE}`, 2);
401
+ const home = io.stateHome();
402
+ const discovery = discoverPlugins(home);
403
+ if (discovery.specs.some((spec) => spec.name === name && spec.kind === "plugin")) {
404
+ io.out(`${name} is already allowed to run.`);
405
+ return 0;
406
+ }
407
+ const pending = discovery.awaitingConsent.find((plugin) => plugin.name === name);
408
+ if (!pending) {
409
+ const problem = discovery.problems.find((candidate) => candidate.name === name);
410
+ throw new PluginCliError(problem
411
+ ? `${name} cannot run: ${problem.error}`
412
+ : `No plugin named '${name}' in ${home}/plugins.`);
413
+ }
414
+ io.out(describeForConsent(pending));
415
+ if (!values.yes) {
416
+ if (!io.interactive())
417
+ throw new PluginCliError("Not a terminal: pass --yes to consent without a prompt.", 2);
418
+ const answer = (await io.ask("Allow this plugin to run? [y/N] ")).trim().toLowerCase();
419
+ if (answer !== "y" && answer !== "yes") {
420
+ io.out("Not allowed. Nothing changed.");
421
+ return 1;
422
+ }
423
+ }
424
+ // Hash again: consent covers what is on disk now, not what was shown a moment ago.
425
+ const hash = hashPluginDirectory(pending.path);
426
+ if (hash !== pending.hash)
427
+ throw new PluginCliError(`${name} changed while you were reviewing it. Run consent again.`);
428
+ grantConsent(home, name, hash);
429
+ io.out(`Allowed ${name}.`);
430
+ await reloadAfterConsentChange(io, name);
431
+ return 0;
432
+ }
433
+ case "example": {
434
+ const name = positionals[0];
435
+ if (!name) {
436
+ io.out([
437
+ "Example plugins (install one with `tmux-ide plugin example <name>`):",
438
+ ...Object.entries(PLUGIN_EXAMPLES).map(([example, { manifest }]) => ` ${example} ${manifest.description ?? ""}`),
439
+ ].join("\n"));
440
+ return 0;
441
+ }
442
+ const example = Object.hasOwn(PLUGIN_EXAMPLES, name) ? PLUGIN_EXAMPLES[name] : undefined;
443
+ if (!example)
444
+ throw new PluginCliError(`No example plugin named '${name}'. See \`tmux-ide plugin example\`.`, 2);
445
+ const dir = join(pluginPaths(io.stateHome()).plugins, name);
446
+ if (existsSync(dir))
447
+ throw new PluginCliError(`${dir} already exists. Remove it first to install the example again.`);
448
+ mkdirSync(dir, { recursive: true, mode: 0o755 });
449
+ writeFileSync(join(dir, "manifest.json"), `${JSON.stringify(example.manifest, null, 2)}\n`);
450
+ for (const [file, text] of Object.entries(example.files))
451
+ writeFileSync(join(dir, file), text);
452
+ io.out([
453
+ `Copied the ${name} example to ${dir}.`,
454
+ "It runs only after you review and allow it:",
455
+ ` tmux-ide plugin consent ${name}`,
456
+ ].join("\n"));
457
+ return 0;
458
+ }
459
+ case "revoke": {
460
+ const name = positionals[0];
461
+ if (!name)
462
+ throw new PluginCliError(`Name the plugin to revoke.\n${PLUGIN_USAGE}`, 2);
463
+ if (!revokeConsent(io.stateHome(), name)) {
464
+ io.out(`${name} was not allowed to run. Nothing changed.`);
465
+ return 0;
466
+ }
467
+ io.out(`Revoked ${name}.`);
468
+ await reloadAfterConsentChange(io, name);
469
+ return 0;
470
+ }
471
+ case "logs": {
472
+ const path = pluginLogPath(io.stateHome());
473
+ const plugin = positionals[0];
474
+ const limit = values.lines !== undefined ? Number(values.lines) : 50;
475
+ if (!Number.isInteger(limit) || limit < 0)
476
+ throw new PluginCliError("-n must be a whole number.", 2);
477
+ const entries = readPluginLog(path, { limit, ...(plugin ? { plugin } : {}) });
478
+ for (const entry of entries)
479
+ io.out(values.json ? JSON.stringify(entry) : formatPluginLogEntry(entry));
480
+ if (values.follow)
481
+ await followLog(path, plugin, io);
482
+ return 0;
483
+ }
484
+ default:
485
+ throw new PluginCliError(`Unknown plugin command '${sub}'.\n${PLUGIN_USAGE}`, 2);
486
+ }
487
+ }
488
+ export async function runPluginCommandLine(command, argv, rawIo) {
489
+ const io = terminalSafeIo(rawIo);
490
+ try {
491
+ return command === "lua" ? await luaCli(argv, io) : await pluginCli(argv, io);
492
+ }
493
+ catch (error) {
494
+ if (error instanceof PluginCliError) {
495
+ io.err(error.message);
496
+ return error.exitCode;
497
+ }
498
+ if (error instanceof TypeError &&
499
+ "code" in error &&
500
+ String(error.code).startsWith("ERR_PARSE_ARGS")) {
501
+ io.err(`${error.message}\n${command === "lua" ? LUA_USAGE : PLUGIN_USAGE}`);
502
+ return 2;
503
+ }
504
+ throw error;
505
+ }
506
+ }
507
+ /** The real terminal, filesystem and daemon. */
508
+ export async function defaultPluginCliIo() {
509
+ const { resolveCanonicalDaemonEndpoint, cliBridgeFetch } = await import("../lib/cli-action-bridge.js");
510
+ const { stateHome } = await import("../lib/state-home.js");
511
+ return {
512
+ out: (text) => process.stdout.write(`${text}\n`),
513
+ err: (text) => process.stderr.write(`${text}\n`),
514
+ readFile: (path) => readFileSync(path, "utf8"),
515
+ readStdin: () => readFileSync(0, "utf8"),
516
+ daemon: () => resolveCanonicalDaemonEndpoint(),
517
+ fetch: (...args) => cliBridgeFetch()(...args),
518
+ stateHome,
519
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
520
+ interactive: () => Boolean(process.stdin.isTTY && process.stdout.isTTY),
521
+ tmuxPane: () => process.env.TMUX_PANE || undefined,
522
+ tmuxSession: (pane) => {
523
+ try {
524
+ const name = execFileSync("tmux", ["display-message", "-p", "-t", pane, "#{session_name}"], {
525
+ encoding: "utf8",
526
+ timeout: 2000,
527
+ stdio: ["ignore", "pipe", "ignore"],
528
+ }).trim();
529
+ return name || undefined;
530
+ }
531
+ catch {
532
+ return undefined;
533
+ }
534
+ },
535
+ dispatchBuiltin: async (name, input) => {
536
+ const { ACTION_NAMES } = await import("@tmux-ide/contracts");
537
+ if (!ACTION_NAMES.includes(name))
538
+ throw new PluginCliError(`No command named '${name}'.`);
539
+ const { tryDispatchAction } = await import("../lib/cli-action-bridge.js");
540
+ const result = await tryDispatchAction(name, input);
541
+ if (result === null)
542
+ throw new PluginCliError("The daemon did not run the command.");
543
+ return result;
544
+ },
545
+ ask: async (question) => {
546
+ const { createInterface } = await import("node:readline/promises");
547
+ const prompt = createInterface({ input: process.stdin, output: process.stdout });
548
+ try {
549
+ return await prompt.question(question);
550
+ }
551
+ finally {
552
+ prompt.close();
553
+ }
554
+ },
555
+ };
556
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Consent for installed plugins.
3
+ *
4
+ * A plugin directory under `plugins/` runs only after its owner consented to
5
+ * that exact content: consent records a SHA-256 over every file in the plugin
6
+ * directory, and any change to any file (manifest included) means the plugin
7
+ * asks again. `init.lua` is the user's own file and needs no consent.
8
+ *
9
+ * Consent lives in `<state home>/consent/plugins.json` (mode 0600). Consent
10
+ * is the boundary: a plugin granted programs, a shell or `panes.send` can
11
+ * usually do anything its owner's account can, including change this file
12
+ * by other means. The OS sandbox (exec-sandbox.ts) only keeps programs from
13
+ * editing it directly and from reading it.
14
+ */
15
+ import { createHash } from "node:crypto";
16
+ import { lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, renameSync, writeFileSync, } from "node:fs";
17
+ import { dirname, join } from "node:path";
18
+ import { z } from "zod";
19
+ export const CONSENT_DIR = "consent";
20
+ export const CONSENT_FILE = "plugins.json";
21
+ /** Plugins larger than this are refused rather than hashed. */
22
+ export const MAX_PLUGIN_FILES = 2000;
23
+ export const MAX_PLUGIN_BYTES = 32 * 1024 * 1024;
24
+ const ConsentFileSchemaZ = z
25
+ .object({
26
+ version: z.literal(1),
27
+ plugins: z.record(z.string(), z.object({ hash: z.string().regex(/^sha256:[0-9a-f]{64}$/u), at: z.string() }).strict()),
28
+ })
29
+ .strict();
30
+ export function consentPath(stateHome) {
31
+ return join(stateHome, CONSENT_DIR, CONSENT_FILE);
32
+ }
33
+ /**
34
+ * Hash every file under `dir`: relative path, type and content, in sorted
35
+ * order. Symlinks are hashed by their target text and never followed.
36
+ */
37
+ export function hashPluginDirectory(dir) {
38
+ const hash = createHash("sha256");
39
+ let files = 0;
40
+ let bytes = 0;
41
+ const walk = (relative) => {
42
+ const absolute = join(dir, relative);
43
+ for (const name of readdirSync(absolute).sort()) {
44
+ const childRelative = relative ? `${relative}/${name}` : name;
45
+ const child = join(dir, childRelative);
46
+ const stat = lstatSync(child);
47
+ files += 1;
48
+ if (files > MAX_PLUGIN_FILES)
49
+ throw new Error(`plugin has more than ${MAX_PLUGIN_FILES} files`);
50
+ if (stat.isSymbolicLink()) {
51
+ hash.update(`L\0${childRelative}\0${readlinkSync(child)}\0`);
52
+ }
53
+ else if (stat.isDirectory()) {
54
+ hash.update(`D\0${childRelative}\0`);
55
+ walk(childRelative);
56
+ }
57
+ else if (stat.isFile()) {
58
+ bytes += stat.size;
59
+ if (bytes > MAX_PLUGIN_BYTES)
60
+ throw new Error("plugin is larger than 32 MiB");
61
+ const content = readFileSync(child);
62
+ hash.update(`F\0${childRelative}\0${content.byteLength}\0`);
63
+ hash.update(content);
64
+ }
65
+ }
66
+ };
67
+ walk("");
68
+ return `sha256:${hash.digest("hex")}`;
69
+ }
70
+ export function readConsent(stateHome) {
71
+ try {
72
+ const parsed = ConsentFileSchemaZ.safeParse(JSON.parse(readFileSync(consentPath(stateHome), "utf8")));
73
+ if (parsed.success)
74
+ return parsed.data;
75
+ }
76
+ catch {
77
+ // Missing or unreadable: nothing is consented.
78
+ }
79
+ return { version: 1, plugins: {} };
80
+ }
81
+ export function consentState(consent, name, hash) {
82
+ const recorded = consent.plugins[name];
83
+ if (!recorded)
84
+ return "new";
85
+ return recorded.hash === hash ? "consented" : "changed";
86
+ }
87
+ function writeConsent(stateHome, consent) {
88
+ const path = consentPath(stateHome);
89
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
90
+ const temporary = `${path}.${process.pid}.tmp`;
91
+ writeFileSync(temporary, `${JSON.stringify(consent, null, 2)}\n`, { mode: 0o600 });
92
+ renameSync(temporary, path);
93
+ }
94
+ /** Record consent for `name` at exactly `hash`. */
95
+ export function grantConsent(stateHome, name, hash, at = new Date()) {
96
+ const consent = readConsent(stateHome);
97
+ consent.plugins[name] = { hash, at: at.toISOString() };
98
+ writeConsent(stateHome, consent);
99
+ }
100
+ export function revokeConsent(stateHome, name) {
101
+ const consent = readConsent(stateHome);
102
+ if (!consent.plugins[name])
103
+ return false;
104
+ delete consent.plugins[name];
105
+ writeConsent(stateHome, consent);
106
+ return true;
107
+ }