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