tmux-ide 2.9.20 → 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 (89) hide show
  1. package/bin/cli.js +14684 -3865
  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/lib/cli-action-bridge.js +15 -0
  12. package/packages/daemon/dist/lib/daemon-embed.js +24 -1
  13. package/packages/daemon/dist/lib/headless-daemon.js +1 -0
  14. package/packages/daemon/dist/lib/worktree.js +18 -0
  15. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  16. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  17. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  18. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  19. package/packages/daemon/dist/plugins/action-catalog.js +129 -0
  20. package/packages/daemon/dist/plugins/action-cli.js +212 -0
  21. package/packages/daemon/dist/plugins/api-table.js +303 -0
  22. package/packages/daemon/dist/plugins/cli.js +556 -0
  23. package/packages/daemon/dist/plugins/consent.js +107 -0
  24. package/packages/daemon/dist/plugins/daemon-plugins.js +132 -0
  25. package/packages/daemon/dist/plugins/discovery.js +142 -0
  26. package/packages/daemon/dist/plugins/examples/worktree-tasks.js +115 -0
  27. package/packages/daemon/dist/plugins/exec-sandbox.js +202 -0
  28. package/packages/daemon/dist/plugins/host/actions-prelude.js +279 -0
  29. package/packages/daemon/dist/plugins/host/entry.js +4 -0
  30. package/packages/daemon/dist/plugins/host/host-api-prelude.js +232 -0
  31. package/packages/daemon/dist/plugins/host/lua-state.js +493 -0
  32. package/packages/daemon/dist/plugins/host/main.js +322 -0
  33. package/packages/daemon/dist/plugins/host/sandbox.js +299 -0
  34. package/packages/daemon/dist/plugins/host-calls.js +279 -0
  35. package/packages/daemon/dist/plugins/manifest.js +69 -0
  36. package/packages/daemon/dist/plugins/plugin-exec.js +261 -0
  37. package/packages/daemon/dist/plugins/plugin-log.js +54 -0
  38. package/packages/daemon/dist/plugins/plugin-store.js +74 -0
  39. package/packages/daemon/dist/plugins/protocol.js +252 -0
  40. package/packages/daemon/dist/plugins/safe-files.js +97 -0
  41. package/packages/daemon/dist/plugins/supervisor.js +790 -0
  42. package/packages/daemon/dist/plugins/worktree-calls.js +154 -0
  43. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +27 -0
  44. package/packages/daemon/dist/tui/mirror/runtime/application-home-experience.js +2 -0
  45. package/packages/daemon/dist/tui/mirror/runtime/application-palette-command-owner.js +30 -2
  46. package/packages/daemon/dist/tui/mirror/runtime/application-plugin-commands.js +152 -0
  47. package/packages/daemon/dist/tui/mirror/runtime/application-plugin-form.js +251 -0
  48. package/packages/daemon/dist/tui/mirror/workspace/application-command-description.js +14 -0
  49. package/packages/daemon/dist/tui/mirror/workspace/palette-list-layout.js +5 -0
  50. package/packages/daemon/src/command-center/command-catalog-routes.ts +116 -0
  51. package/packages/daemon/src/command-center/plugin-routes.ts +110 -0
  52. package/packages/daemon/src/command-center/server.ts +15 -0
  53. package/packages/daemon/src/lib/cli-action-bridge.ts +19 -0
  54. package/packages/daemon/src/lib/daemon-embed.ts +42 -0
  55. package/packages/daemon/src/lib/headless-daemon.ts +1 -0
  56. package/packages/daemon/src/lib/worktree.ts +16 -0
  57. package/packages/daemon/src/plugins/action-catalog.ts +141 -0
  58. package/packages/daemon/src/plugins/action-cli.ts +248 -0
  59. package/packages/daemon/src/plugins/api-table.ts +346 -0
  60. package/packages/daemon/src/plugins/cli.ts +630 -0
  61. package/packages/daemon/src/plugins/consent.ts +125 -0
  62. package/packages/daemon/src/plugins/daemon-plugins.ts +182 -0
  63. package/packages/daemon/src/plugins/discovery.ts +176 -0
  64. package/packages/daemon/src/plugins/examples/worktree-tasks.ts +120 -0
  65. package/packages/daemon/src/plugins/exec-sandbox.ts +264 -0
  66. package/packages/daemon/src/plugins/host/actions-prelude.ts +280 -0
  67. package/packages/daemon/src/plugins/host/entry.ts +5 -0
  68. package/packages/daemon/src/plugins/host/host-api-prelude.ts +233 -0
  69. package/packages/daemon/src/plugins/host/lua-state.ts +557 -0
  70. package/packages/daemon/src/plugins/host/main.ts +359 -0
  71. package/packages/daemon/src/plugins/host/sandbox.ts +301 -0
  72. package/packages/daemon/src/plugins/host-calls.ts +343 -0
  73. package/packages/daemon/src/plugins/manifest.ts +74 -0
  74. package/packages/daemon/src/plugins/plugin-exec.ts +326 -0
  75. package/packages/daemon/src/plugins/plugin-log.ts +63 -0
  76. package/packages/daemon/src/plugins/plugin-store.ts +80 -0
  77. package/packages/daemon/src/plugins/protocol.ts +275 -0
  78. package/packages/daemon/src/plugins/safe-files.ts +105 -0
  79. package/packages/daemon/src/plugins/supervisor.ts +954 -0
  80. package/packages/daemon/src/plugins/worktree-calls.ts +183 -0
  81. package/packages/daemon/src/tui/mirror/runtime/application-fleet-switcher.tsx +3 -1
  82. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +32 -0
  83. package/packages/daemon/src/tui/mirror/runtime/application-home-experience.ts +2 -0
  84. package/packages/daemon/src/tui/mirror/runtime/application-palette-command-owner.ts +42 -2
  85. package/packages/daemon/src/tui/mirror/runtime/application-palette-preview.tsx +7 -1
  86. package/packages/daemon/src/tui/mirror/runtime/application-plugin-commands.ts +229 -0
  87. package/packages/daemon/src/tui/mirror/runtime/application-plugin-form.ts +312 -0
  88. package/packages/daemon/src/tui/mirror/workspace/application-command-description.ts +44 -2
  89. package/packages/daemon/src/tui/mirror/workspace/palette-list-layout.ts +4 -0
@@ -0,0 +1,183 @@
1
+ /**
2
+ * `ide.worktree.list|create|open|remove`: git worktrees and their sessions,
3
+ * for plugins granted the `worktree` capability.
4
+ *
5
+ * The daemon runs its own `tmux-ide worktree … --json` (the same code and
6
+ * gates as the CLI), outside the plugin sandbox, with arguments it checked:
7
+ * a branch or ref that git would accept and cannot pass for an option, and
8
+ * a session that exists, by exact name, on the daemon's tmux server. The
9
+ * plugin never gets a program it could aim elsewhere. Sessions it opens are
10
+ * plain: the worktree's own tmux-ide layout (commands from that branch)
11
+ * never runs. `remove` never passes `--force`, so a worktree with changes
12
+ * is refused; plugins mark actions that remove as dangerous so a person
13
+ * confirms them.
14
+ */
15
+ import { spawn } from "node:child_process";
16
+ import { homedir } from "node:os";
17
+ import { z } from "zod";
18
+
19
+ export const WORKTREE_OPERATIONS = ["list", "create", "open", "remove"] as const;
20
+ export type WorktreeOperation = (typeof WORKTREE_OPERATIONS)[number];
21
+
22
+ /** A branch or ref: git-valid, and never something argv parsing reads as an option. */
23
+ const REF = z
24
+ .string()
25
+ .min(1)
26
+ .max(200)
27
+ .regex(/^[A-Za-z0-9_][A-Za-z0-9._/-]*$/u, "must be letters, digits and . _ / - only")
28
+ .refine(
29
+ (ref) =>
30
+ !ref.includes("..") &&
31
+ !ref.includes("//") &&
32
+ !ref.endsWith("/") &&
33
+ !ref.endsWith(".") &&
34
+ !ref.endsWith(".lock") &&
35
+ !ref.split("/").some((part) => part.startsWith(".")),
36
+ "is not a valid git branch name",
37
+ );
38
+
39
+ /**
40
+ * A tmux session name tmux reads literally: letters, digits, space and
41
+ * `_ - @ + ,` only. Nothing tmux takes as a pattern (`* ? [`), a format
42
+ * (`#{`), target syntax (`: . = ~ $ %`) or an option (a leading `-`).
43
+ */
44
+ const SESSION = z
45
+ .string()
46
+ .min(1)
47
+ .max(200)
48
+ .regex(/^[\p{L}\p{N}_@+][\p{L}\p{N} _@+,-]*$/u, "is not a plain tmux session name");
49
+
50
+ const RequestSchemaZ = z
51
+ .object({
52
+ session: SESSION,
53
+ branch: REF.optional(),
54
+ from: REF.optional(),
55
+ })
56
+ .strict();
57
+
58
+ export interface WorktreeCallDependencies {
59
+ /** Run tmux against the daemon's server and return stdout. */
60
+ readonly tmux: (args: readonly string[]) => Promise<string>;
61
+ /** Whether the calling plugin may still act; checked right before the CLI runs. */
62
+ readonly stillActive?: () => boolean;
63
+ /** Run the tmux-ide CLI with `args` and `env`; resolves with its exit and output. */
64
+ readonly runCli: (
65
+ args: readonly string[],
66
+ env: NodeJS.ProcessEnv,
67
+ ) => Promise<{ code: number | null; stdout: string; stderr: string }>;
68
+ }
69
+
70
+ export class WorktreeCallError extends Error {}
71
+
72
+ function fail(message: string): never {
73
+ throw new WorktreeCallError(message);
74
+ }
75
+
76
+ /** Check a request and run the worktree operation; resolves with tmux-ide's JSON answer. */
77
+ export async function worktreeCall(
78
+ operation: unknown,
79
+ raw: unknown,
80
+ deps: WorktreeCallDependencies,
81
+ ): Promise<unknown> {
82
+ if (!WORKTREE_OPERATIONS.includes(operation as WorktreeOperation))
83
+ fail("E_INVALID: ide.worktree supports list, create, open and remove");
84
+ const op = operation as WorktreeOperation;
85
+ const parsed = RequestSchemaZ.safeParse(raw);
86
+ if (!parsed.success) {
87
+ const issue = parsed.error.issues[0];
88
+ fail(
89
+ `E_INVALID: ide.worktree.${op} ${issue?.path.join(".") || "request"} ${issue?.message ?? "is invalid"}`,
90
+ );
91
+ }
92
+ const { session, branch, from } = parsed.data;
93
+ if (op !== "list" && !branch) fail(`E_INVALID: ide.worktree.${op} needs a branch`);
94
+ if (from && op !== "create") fail(`E_INVALID: only ide.worktree.create takes from`);
95
+
96
+ // The session must exist on the daemon's tmux server, by exact name
97
+ // (`=name`; display-message alone answers even for an unknown session).
98
+ // The CLI then talks to that same server (TMUX names its socket), finds
99
+ // the repository from that session's directory, and fails rather than
100
+ // fall back to its own directory.
101
+ let where: string;
102
+ try {
103
+ await deps.tmux(["has-session", "-t", `=${session}`]);
104
+ // "|" cannot be in a session name (see SESSION), so the first one splits.
105
+ // (Not a tab: tmux prints control characters as "_" under LANG=C.)
106
+ const line = (
107
+ await deps.tmux([
108
+ "display-message",
109
+ "-p",
110
+ "-t",
111
+ `=${session}:`,
112
+ "#{session_name}|#{socket_path},#{pid}",
113
+ ])
114
+ ).trim();
115
+ const split = line.indexOf("|");
116
+ const name = split < 0 ? line : line.slice(0, split);
117
+ const socket = split < 0 ? "" : line.slice(split + 1);
118
+ if (name !== session || !socket || !/^\/.+,\d+$/u.test(socket)) throw new Error("mismatch");
119
+ where = socket;
120
+ } catch {
121
+ fail(`E_NOT_FOUND: no tmux session '${session}'`);
122
+ }
123
+ if (deps.stillActive && !deps.stillActive())
124
+ fail("E_UNAVAILABLE: the plugin was stopped before this finished");
125
+
126
+ const args = ["worktree", op];
127
+ if (branch) args.push(branch);
128
+ if (from) args.push("--from", from);
129
+ // --plain: a plugin never starts the worktree's own layout, whose commands
130
+ // come from that branch (which `from` may name).
131
+ if (op === "create" || op === "open") args.push("--plain");
132
+ // `=name:`: the exact session (a bare `=name` names no pane for tmux).
133
+ // No git hook runs either: `git worktree add` would run post-checkout, and
134
+ // a relative core.hooksPath takes the hook from the new worktree's branch.
135
+ args.push("--session", `=${session}:`, "--require-session", "--no-git-hooks", "--json");
136
+ const env: NodeJS.ProcessEnv = { ...process.env, TMUX: `${where},0` };
137
+ delete env.TMUX_PANE;
138
+ const result = await deps.runCli(args, env);
139
+ if (result.code !== 0) {
140
+ const message = (result.stderr.trim() || result.stdout.trim()).split("\n").slice(-3).join(" ");
141
+ fail(`E_FAILED: ${message || `tmux-ide worktree ${op} failed`}`.slice(0, 2000));
142
+ }
143
+ try {
144
+ return JSON.parse(result.stdout) as unknown;
145
+ } catch {
146
+ fail("E_FAILED: tmux-ide worktree sent an unexpected answer");
147
+ }
148
+ }
149
+
150
+ const OUTPUT_CAP = 1024 * 1024;
151
+
152
+ /** Run `command` (the tmux-ide CLI argv prefix) with `args`, for up to `timeoutMs`. */
153
+ export function cliRunner(
154
+ command: readonly string[],
155
+ timeoutMs = 60_000,
156
+ ): WorktreeCallDependencies["runCli"] {
157
+ return (args, env) =>
158
+ new Promise((resolve, reject) => {
159
+ const [file, ...prefix] = command;
160
+ const child = spawn(file!, [...prefix, ...args], {
161
+ cwd: homedir(),
162
+ env,
163
+ stdio: ["ignore", "pipe", "pipe"],
164
+ });
165
+ let stdout = "";
166
+ let stderr = "";
167
+ child.stdout.on("data", (chunk: Buffer) => {
168
+ if (stdout.length < OUTPUT_CAP) stdout += chunk.toString("utf8");
169
+ });
170
+ child.stderr.on("data", (chunk: Buffer) => {
171
+ if (stderr.length < OUTPUT_CAP) stderr += chunk.toString("utf8");
172
+ });
173
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
174
+ child.on("error", (error) => {
175
+ clearTimeout(timer);
176
+ reject(new WorktreeCallError(`E_UNAVAILABLE: could not run tmux-ide: ${error.message}`));
177
+ });
178
+ child.on("close", (code) => {
179
+ clearTimeout(timer);
180
+ resolve({ code, stdout, stderr });
181
+ });
182
+ });
183
+ }
@@ -45,7 +45,9 @@ export function ApplicationFleetSwitcher(props: {
45
45
  }),
46
46
  );
47
47
  const fallbackRow = (c: ApplicationPaletteCommand) =>
48
- typeof c === "object" ? props.rows.find((r) => r.key === c.sessionName) : undefined;
48
+ typeof c === "object" && "sessionName" in c
49
+ ? props.rows.find((r) => r.key === c.sessionName)
50
+ : undefined;
49
51
  const commands = () =>
50
52
  source().filter(
51
53
  (c) =>
@@ -20,6 +20,8 @@ import type { OpenTuiSessionOwner } from "./open-tui-session-owner.ts";
20
20
  import type { ApplicationShellBinding } from "./application-shell-binding.ts";
21
21
  import type { createApplicationTerminalInteractionController } from "./application-terminal-interaction-controller.ts";
22
22
  import { createApplicationPaletteCommandOwner } from "./application-palette-command-owner.ts";
23
+ import type { ApplicationPluginCommands } from "./application-plugin-commands.ts";
24
+ import { createApplicationPluginForm, pluginPaletteContext } from "./application-plugin-form.ts";
23
25
  import { createApplicationPaneRenameOwner } from "./application-pane-rename-owner.ts";
24
26
  import {
25
27
  applicationPaletteCommands,
@@ -212,6 +214,8 @@ export function createApplicationHomeNavigationOwner(options: {
212
214
  source: "keyboard" | "mouse",
213
215
  ) => Promise<unknown> | void;
214
216
  readonly focusedPane: Accessor<string | null>;
217
+ /** Plugin command source (the local daemon in production); absent means no plugin commands. */
218
+ readonly pluginCommands?: ApplicationPluginCommands;
215
219
  readonly catalog: {
216
220
  readonly snapshot: Accessor<ApplicationHomeCatalogSnapshot>;
217
221
  readonly sessionNames: Accessor<string[]>;
@@ -288,7 +292,31 @@ export function createApplicationHomeNavigationOwner(options: {
288
292
  setNote: options.setNote,
289
293
  observer: options.observer,
290
294
  });
295
+ // Plugin commands come from the local daemon's command catalog; a command
296
+ // with parameters opens a step-by-step form inside the palette.
297
+ const pluginCommands = options.pluginCommands;
298
+ let paletteOwner: ReturnType<typeof createApplicationPaletteCommandOwner> | null = null;
299
+ const pluginForm =
300
+ pluginCommands &&
301
+ createApplicationPluginForm({
302
+ service: pluginCommands,
303
+ context: () =>
304
+ pluginPaletteContext(options.sessionOwner()?.sessionName() ?? null, options.focusedPane()),
305
+ query: () => paletteOwner?.query() ?? "",
306
+ setNote: options.setNote,
307
+ close: () => paletteOwner?.setOpen(false, "keyboard"),
308
+ stepChanged: () => paletteOwner?.resetForStep(),
309
+ });
291
310
  const paletteCommands = createApplicationPaletteCommandOwner({
311
+ ...(pluginCommands && pluginForm
312
+ ? {
313
+ plugins: {
314
+ form: pluginForm,
315
+ refresh: () => void pluginCommands.refresh(),
316
+ watch: () => pluginCommands.watch(),
317
+ },
318
+ }
319
+ : {}),
292
320
  commands: () => [
293
321
  ...(options.fleetCommands
294
322
  ? [
@@ -305,12 +333,15 @@ export function createApplicationHomeNavigationOwner(options: {
305
333
  : ("hide-sidebar" as const),
306
334
  ]
307
335
  : []),
336
+ ...(pluginCommands?.commands() ?? []),
308
337
  ],
309
338
  isOpen: () =>
310
339
  Boolean(options.shell().semantic?.focus.palette.open ?? options.shell().localPaletteOpen),
311
340
  targetKey: () =>
312
341
  `${applicationGenerationNavigationKey(options.sessionOwner()?.snapshot() ?? null)}:${options.focusedPane()}`,
313
342
  disabledReason: (command) => {
343
+ if (typeof command === "object" && command.kind === "plugin-form")
344
+ return command.disabledReason ?? null;
314
345
  if (typeof command === "object" && command.fleet?.disabled)
315
346
  return "Machine or session unavailable";
316
347
  if (
@@ -354,6 +385,7 @@ export function createApplicationHomeNavigationOwner(options: {
354
385
  openSession: (name, source) => options.startGeneration(name, false, source),
355
386
  onNavigationIntent: homeAgents.cancel,
356
387
  });
388
+ paletteOwner = paletteCommands;
357
389
  const paletteCommandList = paletteCommands.commands;
358
390
  return {
359
391
  homeAgents: options.fleetHome ? { ...homeAgents, presentation: options.fleetHome } : homeAgents,
@@ -1,3 +1,4 @@
1
+ import { createApplicationPluginCommands } from "./application-plugin-commands.ts";
1
2
  import { createEffect, type Accessor } from "solid-js";
2
3
  import { createApplicationHomeFleetOwner } from "./application-home-fleet.ts";
3
4
  import { createApplicationHomeNavigationOwner } from "./application-home-agents-owner.ts";
@@ -63,6 +64,7 @@ export function createApplicationHomeExperience(
63
64
  fleetCommands: machines.paletteCommands,
64
65
  openFleet: machines.openPalette,
65
66
  openSessions: () => machines.showSwitcher(false),
67
+ pluginCommands: createApplicationPluginCommands(),
66
68
  });
67
69
  const tour = createLazyApplicationGuidedTour(
68
70
  {
@@ -5,6 +5,7 @@ import type { ApplicationPaletteCommand } from "./application-palette-input.ts";
5
5
  import type { ApplicationShellBinding } from "./application-shell-binding.ts";
6
6
  import { applicationPaletteCommands } from "./application-palette-input.ts";
7
7
  import { createApplicationPaletteSearchOwner } from "./application-palette-search-owner.ts";
8
+ import type { ApplicationPluginForm } from "./application-plugin-form.ts";
8
9
 
9
10
  type Source = "keyboard" | "mouse";
10
11
 
@@ -39,14 +40,26 @@ export function createApplicationPaletteCommandOwner(options: {
39
40
  readonly isOpen?: () => boolean;
40
41
  readonly disabledReason?: (command: ApplicationPaletteCommand) => string | null;
41
42
  readonly targetKey?: () => string;
43
+ /** Plugin commands and their parameter form; absent when plugins are unavailable. */
44
+ readonly plugins?: {
45
+ readonly form: ApplicationPluginForm;
46
+ /** Refresh the plugin command list; called whenever the palette opens. */
47
+ readonly refresh: () => void;
48
+ /** Follow catalog changes while the palette is open; returns a stop function. */
49
+ readonly watch?: () => () => void;
50
+ };
42
51
  }) {
43
52
  const [referencePage, setReferencePage] = createSignal<"shortcuts" | "changes" | "help">();
44
53
  const [closeArmed, setCloseArmed] = createSignal(false);
45
54
  const [busy, setBusy] = createSignal(false);
46
55
  let armedTarget: string | undefined;
56
+ let stopWatch: (() => void) | null = null;
47
57
  let openRevision = 0;
58
+ const baseCommands = options.commands ?? (() => applicationPaletteCommands(null));
48
59
  const search = createApplicationPaletteSearchOwner({
49
- commands: options.commands ?? (() => applicationPaletteCommands(null)),
60
+ // While a plugin form is open the list is the current step's entries.
61
+ commands: () =>
62
+ options.plugins?.form.active() ? options.plugins.form.entries() : baseCommands(),
50
63
  open: options.isOpen ?? (() => false),
51
64
  activate: (command, source) => activate(command, source),
52
65
  close: () => setOpen(false, "keyboard"),
@@ -56,7 +69,14 @@ export function createApplicationPaletteCommandOwner(options: {
56
69
  setReferencePage(undefined);
57
70
  openRevision += 1;
58
71
  setCloseArmed(false);
59
- if (open) search.reset(options.activeSurface() === "home" ? 0 : 1);
72
+ options.plugins?.form.cancel();
73
+ stopWatch?.();
74
+ stopWatch = null;
75
+ if (open) {
76
+ options.plugins?.refresh();
77
+ stopWatch = options.plugins?.watch?.() ?? null;
78
+ search.reset(options.activeSurface() === "home" ? 0 : 1);
79
+ }
60
80
  void options.binding
61
81
  .setPaletteOpen(open, options.commandSource(source, "command-palette"))
62
82
  .catch(() => options.setNote("Commands could not be updated. Try again."));
@@ -74,6 +94,22 @@ export function createApplicationPaletteCommandOwner(options: {
74
94
  );
75
95
  return;
76
96
  }
97
+ if (typeof command === "object" && command.kind === "plugin-form") {
98
+ if (command.disabledReason) {
99
+ options.setNote(command.disabledReason);
100
+ return;
101
+ }
102
+ options.plugins?.form.choose(command);
103
+ return;
104
+ }
105
+ if (typeof command === "object" && command.kind === "plugin-command") {
106
+ if (!options.plugins) {
107
+ options.setNote("Plugin commands are unavailable.");
108
+ return;
109
+ }
110
+ options.plugins.form.start(command);
111
+ return;
112
+ }
77
113
  if (command === "switch-session") {
78
114
  if (!options.openSessions) {
79
115
  options.setNote("Session switching is unavailable.");
@@ -192,6 +228,10 @@ export function createApplicationPaletteCommandOwner(options: {
192
228
  };
193
229
  return {
194
230
  ...search,
231
+ keyboardHint: () =>
232
+ options.plugins?.form.active() ? options.plugins.form.hint() : search.keyboardHint(),
233
+ /** Clear the search line and selection for a new form step. */
234
+ resetForStep: () => search.reset(0),
195
235
  referencePage,
196
236
  setReferencePage,
197
237
  busy,
@@ -25,6 +25,12 @@ const rememberWindow = (key: string, window: string) => {
25
25
  };
26
26
 
27
27
  /** F5 browsing is passive and pinned to the highlighted command's exact authority. */
28
+
29
+ const sessionNameOf = (command: unknown): string | undefined =>
30
+ command && typeof command === "object" && "sessionName" in command
31
+ ? String((command as { sessionName: unknown }).sessionName)
32
+ : undefined;
33
+
28
34
  export function ApplicationPalettePreview(props: {
29
35
  command: ApplicationPaletteCommand | undefined;
30
36
  width: number;
@@ -148,7 +154,7 @@ export function ApplicationPalettePreview(props: {
148
154
  const heading = () => {
149
155
  const snapshot = state().snapshot;
150
156
  const window = snapshot?.windows.find((w) => w.id === snapshot.selectedWindowId);
151
- return `${paneId() ? command()?.label + " · " : ""}${target()?.hostLabel ?? "Session preview"} · ${command()?.sessionName ?? "Select a session"}${window ? ` · ${window.index}: ${window.name}` : ""}`;
157
+ return `${paneId() ? command()?.label + " · " : ""}${target()?.hostLabel ?? "Session preview"} · ${sessionNameOf(command()) ?? "Select a session"}${window ? ` · ${window.index}: ${window.name}` : ""}`;
152
158
  };
153
159
  const hostColor = () => {
154
160
  revision();
@@ -0,0 +1,229 @@
1
+ /**
2
+ * Plugin commands for the TUI palette: the plugin half of the daemon's
3
+ * command catalog, plus invoking a command and asking for a parameter's
4
+ * choices. Always the LOCAL canonical daemon, like the fleet preferences.
5
+ *
6
+ * The catalog is fetched when the palette opens, so a plugin reload shows up
7
+ * the next time the palette is opened.
8
+ */
9
+ import {
10
+ CommandCatalogResourceSchemaZ,
11
+ CommandInvokeResultSchemaZ,
12
+ CommandParamOptionsResultSchemaZ,
13
+ type CommandInvocationContext,
14
+ type CommandInvokeResult,
15
+ type CommandParamOptionsResult,
16
+ } from "@tmux-ide/contracts";
17
+ import { createSignal } from "solid-js";
18
+ import WebSocket from "ws";
19
+ import {
20
+ canonicalDaemonUrl,
21
+ readCanonicalDaemonInfo,
22
+ type CanonicalDaemonInfo,
23
+ } from "../../../lib/canonical-daemon.ts";
24
+ import type { ApplicationPluginPaletteCommand } from "../workspace/application-command-description.ts";
25
+
26
+ /** The bits of a WebSocket the catalog watch uses. */
27
+ export interface CatalogEventSocket {
28
+ addEventListener(type: "open" | "close" | "error", listener: () => void): void;
29
+ addEventListener(type: "message", listener: (event: { data: unknown }) => void): void;
30
+ send(data: string): void;
31
+ close(code?: number, reason?: string): void;
32
+ }
33
+
34
+ export interface PluginCommandTransport {
35
+ readonly daemon: () => CanonicalDaemonInfo | null;
36
+ readonly fetch: typeof fetch;
37
+ /** Opens the daemon's event socket; absent means no live updates. */
38
+ readonly socket?: (url: string, ownerToken: string) => CatalogEventSocket;
39
+ }
40
+
41
+ const defaultTransport: PluginCommandTransport = {
42
+ daemon: readCanonicalDaemonInfo,
43
+ fetch: (...args) => fetch(...args),
44
+ socket: (url, ownerToken) =>
45
+ new WebSocket(url, {
46
+ headers: { Authorization: `Bearer ${ownerToken}` },
47
+ }) as unknown as CatalogEventSocket,
48
+ };
49
+
50
+ async function request(
51
+ transport: PluginCommandTransport,
52
+ method: "GET" | "POST",
53
+ path: string,
54
+ body: unknown,
55
+ signal: AbortSignal,
56
+ ): Promise<unknown> {
57
+ const daemon = transport.daemon();
58
+ if (!daemon?.authToken) throw new Error("No local tmux-ide daemon is running.");
59
+ const response = await transport.fetch(
60
+ canonicalDaemonUrl("http", daemon.bindHostname, daemon.port) + path,
61
+ {
62
+ method,
63
+ redirect: "error",
64
+ signal,
65
+ headers: {
66
+ Authorization: `Bearer ${daemon.authToken}`,
67
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
68
+ },
69
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
70
+ },
71
+ );
72
+ const payload: unknown = await response.json().catch(() => null);
73
+ if (!response.ok) {
74
+ const message =
75
+ payload && typeof payload === "object" && "error" in payload
76
+ ? String((payload as { error: unknown }).error)
77
+ : `The daemon answered ${response.status}.`;
78
+ throw new Error(message);
79
+ }
80
+ return payload;
81
+ }
82
+
83
+ export function createApplicationPluginCommands(
84
+ transport: PluginCommandTransport = defaultTransport,
85
+ ) {
86
+ const [commands, setCommands] = createSignal<readonly ApplicationPluginPaletteCommand[]>([]);
87
+ let inflight: AbortController | null = null;
88
+ const refresh = async (): Promise<void> => {
89
+ inflight?.abort();
90
+ const controller = new AbortController();
91
+ inflight = controller;
92
+ try {
93
+ const parsed = CommandCatalogResourceSchemaZ.safeParse(
94
+ await request(
95
+ transport,
96
+ "GET",
97
+ "/api/resources/command-catalog",
98
+ undefined,
99
+ AbortSignal.any([controller.signal, AbortSignal.timeout(3000)]),
100
+ ),
101
+ );
102
+ if (!parsed.success || controller.signal.aborted) return;
103
+ setCommands(
104
+ parsed.data.entries.flatMap((entry) =>
105
+ entry.plugin
106
+ ? [
107
+ {
108
+ kind: "plugin-command" as const,
109
+ id: entry.descriptor.id,
110
+ label: entry.descriptor.label,
111
+ category: entry.descriptor.category,
112
+ plugin: entry.plugin,
113
+ dangerous: entry.descriptor.dangerous,
114
+ params: entry.params,
115
+ },
116
+ ]
117
+ : [],
118
+ ),
119
+ );
120
+ } catch {
121
+ // No daemon, or plugins off: the palette simply shows no plugin commands.
122
+ } finally {
123
+ if (inflight === controller) inflight = null;
124
+ }
125
+ };
126
+ return {
127
+ commands,
128
+ /** Fetch the catalog again; keeps the last list if the daemon is unreachable. */
129
+ refresh,
130
+ /**
131
+ * Follow the daemon's command-catalog invalidations while the palette is
132
+ * open, so a plugin reload shows up without reopening it. Returns a stop
133
+ * function; does nothing without a daemon or a socket.
134
+ */
135
+ watch(): () => void {
136
+ const daemon = transport.daemon();
137
+ if (!daemon?.authToken || !transport.socket) return () => {};
138
+ let socket: CatalogEventSocket;
139
+ try {
140
+ socket = transport.socket(
141
+ canonicalDaemonUrl("ws", daemon.bindHostname, daemon.port, "/ws/events?mode=semantic"),
142
+ daemon.authToken,
143
+ );
144
+ } catch {
145
+ return () => {};
146
+ }
147
+ let stopped = false;
148
+ socket.addEventListener("error", () => {});
149
+ socket.addEventListener("open", () => {
150
+ socket.send(
151
+ JSON.stringify({
152
+ type: "subscribe",
153
+ sessions: [],
154
+ interests: [{ resource: "command-catalog", workspaceName: null }],
155
+ legacyEvents: false,
156
+ }),
157
+ );
158
+ });
159
+ socket.addEventListener("message", (event) => {
160
+ if (stopped || (typeof event.data !== "string" && !Buffer.isBuffer(event.data))) return;
161
+ let frame: unknown;
162
+ try {
163
+ frame = JSON.parse(String(event.data));
164
+ } catch {
165
+ return;
166
+ }
167
+ if (
168
+ frame &&
169
+ typeof frame === "object" &&
170
+ (frame as { type?: unknown }).type === "resource.changed" &&
171
+ (frame as { resource?: unknown }).resource === "command-catalog"
172
+ )
173
+ void refresh();
174
+ });
175
+ return () => {
176
+ if (stopped) return;
177
+ stopped = true;
178
+ socket.close(1000, "palette closed");
179
+ };
180
+ },
181
+ async invoke(
182
+ id: string,
183
+ args: Record<string, string | number | boolean>,
184
+ context: CommandInvocationContext,
185
+ confirmed: boolean,
186
+ ): Promise<CommandInvokeResult> {
187
+ try {
188
+ const parsed = CommandInvokeResultSchemaZ.safeParse(
189
+ await request(
190
+ transport,
191
+ "POST",
192
+ "/api/v2/commands/invoke",
193
+ { id, args, context, ...(confirmed ? { confirmed: true } : {}) },
194
+ AbortSignal.timeout(60_000),
195
+ ),
196
+ );
197
+ return parsed.success
198
+ ? parsed.data
199
+ : { ok: false, error: "The daemon sent an unexpected answer." };
200
+ } catch (error) {
201
+ return { ok: false, error: (error as Error).message };
202
+ }
203
+ },
204
+ async paramOptions(
205
+ id: string,
206
+ param: string,
207
+ context: CommandInvocationContext,
208
+ ): Promise<CommandParamOptionsResult> {
209
+ try {
210
+ const parsed = CommandParamOptionsResultSchemaZ.safeParse(
211
+ await request(
212
+ transport,
213
+ "POST",
214
+ "/api/v2/commands/param-options",
215
+ { id, param, context },
216
+ AbortSignal.timeout(30_000),
217
+ ),
218
+ );
219
+ return parsed.success
220
+ ? parsed.data
221
+ : { ok: false, error: "The daemon sent an unexpected answer." };
222
+ } catch (error) {
223
+ return { ok: false, error: (error as Error).message };
224
+ }
225
+ },
226
+ };
227
+ }
228
+
229
+ export type ApplicationPluginCommands = ReturnType<typeof createApplicationPluginCommands>;