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,154 @@
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
+ export const WORKTREE_OPERATIONS = ["list", "create", "open", "remove"];
19
+ /** A branch or ref: git-valid, and never something argv parsing reads as an option. */
20
+ const REF = z
21
+ .string()
22
+ .min(1)
23
+ .max(200)
24
+ .regex(/^[A-Za-z0-9_][A-Za-z0-9._/-]*$/u, "must be letters, digits and . _ / - only")
25
+ .refine((ref) => !ref.includes("..") &&
26
+ !ref.includes("//") &&
27
+ !ref.endsWith("/") &&
28
+ !ref.endsWith(".") &&
29
+ !ref.endsWith(".lock") &&
30
+ !ref.split("/").some((part) => part.startsWith(".")), "is not a valid git branch name");
31
+ /**
32
+ * A tmux session name tmux reads literally: letters, digits, space and
33
+ * `_ - @ + ,` only. Nothing tmux takes as a pattern (`* ? [`), a format
34
+ * (`#{`), target syntax (`: . = ~ $ %`) or an option (a leading `-`).
35
+ */
36
+ const SESSION = z
37
+ .string()
38
+ .min(1)
39
+ .max(200)
40
+ .regex(/^[\p{L}\p{N}_@+][\p{L}\p{N} _@+,-]*$/u, "is not a plain tmux session name");
41
+ const RequestSchemaZ = z
42
+ .object({
43
+ session: SESSION,
44
+ branch: REF.optional(),
45
+ from: REF.optional(),
46
+ })
47
+ .strict();
48
+ export class WorktreeCallError extends Error {
49
+ }
50
+ function fail(message) {
51
+ throw new WorktreeCallError(message);
52
+ }
53
+ /** Check a request and run the worktree operation; resolves with tmux-ide's JSON answer. */
54
+ export async function worktreeCall(operation, raw, deps) {
55
+ if (!WORKTREE_OPERATIONS.includes(operation))
56
+ fail("E_INVALID: ide.worktree supports list, create, open and remove");
57
+ const op = operation;
58
+ const parsed = RequestSchemaZ.safeParse(raw);
59
+ if (!parsed.success) {
60
+ const issue = parsed.error.issues[0];
61
+ fail(`E_INVALID: ide.worktree.${op} ${issue?.path.join(".") || "request"} ${issue?.message ?? "is invalid"}`);
62
+ }
63
+ const { session, branch, from } = parsed.data;
64
+ if (op !== "list" && !branch)
65
+ fail(`E_INVALID: ide.worktree.${op} needs a branch`);
66
+ if (from && op !== "create")
67
+ fail(`E_INVALID: only ide.worktree.create takes from`);
68
+ // The session must exist on the daemon's tmux server, by exact name
69
+ // (`=name`; display-message alone answers even for an unknown session).
70
+ // The CLI then talks to that same server (TMUX names its socket), finds
71
+ // the repository from that session's directory, and fails rather than
72
+ // fall back to its own directory.
73
+ let where;
74
+ try {
75
+ await deps.tmux(["has-session", "-t", `=${session}`]);
76
+ // "|" cannot be in a session name (see SESSION), so the first one splits.
77
+ // (Not a tab: tmux prints control characters as "_" under LANG=C.)
78
+ const line = (await deps.tmux([
79
+ "display-message",
80
+ "-p",
81
+ "-t",
82
+ `=${session}:`,
83
+ "#{session_name}|#{socket_path},#{pid}",
84
+ ])).trim();
85
+ const split = line.indexOf("|");
86
+ const name = split < 0 ? line : line.slice(0, split);
87
+ const socket = split < 0 ? "" : line.slice(split + 1);
88
+ if (name !== session || !socket || !/^\/.+,\d+$/u.test(socket))
89
+ throw new Error("mismatch");
90
+ where = socket;
91
+ }
92
+ catch {
93
+ fail(`E_NOT_FOUND: no tmux session '${session}'`);
94
+ }
95
+ if (deps.stillActive && !deps.stillActive())
96
+ fail("E_UNAVAILABLE: the plugin was stopped before this finished");
97
+ const args = ["worktree", op];
98
+ if (branch)
99
+ args.push(branch);
100
+ if (from)
101
+ args.push("--from", from);
102
+ // --plain: a plugin never starts the worktree's own layout, whose commands
103
+ // come from that branch (which `from` may name).
104
+ if (op === "create" || op === "open")
105
+ args.push("--plain");
106
+ // `=name:`: the exact session (a bare `=name` names no pane for tmux).
107
+ // No git hook runs either: `git worktree add` would run post-checkout, and
108
+ // a relative core.hooksPath takes the hook from the new worktree's branch.
109
+ args.push("--session", `=${session}:`, "--require-session", "--no-git-hooks", "--json");
110
+ const env = { ...process.env, TMUX: `${where},0` };
111
+ delete env.TMUX_PANE;
112
+ const result = await deps.runCli(args, env);
113
+ if (result.code !== 0) {
114
+ const message = (result.stderr.trim() || result.stdout.trim()).split("\n").slice(-3).join(" ");
115
+ fail(`E_FAILED: ${message || `tmux-ide worktree ${op} failed`}`.slice(0, 2000));
116
+ }
117
+ try {
118
+ return JSON.parse(result.stdout);
119
+ }
120
+ catch {
121
+ fail("E_FAILED: tmux-ide worktree sent an unexpected answer");
122
+ }
123
+ }
124
+ const OUTPUT_CAP = 1024 * 1024;
125
+ /** Run `command` (the tmux-ide CLI argv prefix) with `args`, for up to `timeoutMs`. */
126
+ export function cliRunner(command, timeoutMs = 60_000) {
127
+ return (args, env) => new Promise((resolve, reject) => {
128
+ const [file, ...prefix] = command;
129
+ const child = spawn(file, [...prefix, ...args], {
130
+ cwd: homedir(),
131
+ env,
132
+ stdio: ["ignore", "pipe", "pipe"],
133
+ });
134
+ let stdout = "";
135
+ let stderr = "";
136
+ child.stdout.on("data", (chunk) => {
137
+ if (stdout.length < OUTPUT_CAP)
138
+ stdout += chunk.toString("utf8");
139
+ });
140
+ child.stderr.on("data", (chunk) => {
141
+ if (stderr.length < OUTPUT_CAP)
142
+ stderr += chunk.toString("utf8");
143
+ });
144
+ const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
145
+ child.on("error", (error) => {
146
+ clearTimeout(timer);
147
+ reject(new WorktreeCallError(`E_UNAVAILABLE: could not run tmux-ide: ${error.message}`));
148
+ });
149
+ child.on("close", (code) => {
150
+ clearTimeout(timer);
151
+ resolve({ code, stdout, stderr });
152
+ });
153
+ });
154
+ }
@@ -588,7 +588,8 @@ export class SessionChannel {
588
588
  pane.descriptor?.runtimeSessionId !== identity.runtimeSessionId ||
589
589
  pane.descriptor?.windowId !== resolved.runtimeWindowId ||
590
590
  this.panesBySemantic.get(pane.semanticId) !== pane ||
591
- (!stock && (!birth || !/^[1-9]\d*$/u.test(birth))) ||
591
+ // A stock server has no birth ids; a server that has them must give valid ones.
592
+ ((!stock || birth) && (!birth || !/^[1-9]\d*$/u.test(birth))) ||
592
593
  !layout.leaves.some((visible) => visible.id === leaf.id &&
593
594
  visible.left === leaf.left &&
594
595
  visible.top === leaf.top &&
@@ -598,7 +599,7 @@ export class SessionChannel {
598
599
  return Object.freeze({
599
600
  runtimePaneId: pane.runtimeId,
600
601
  semanticPaneId: pane.semanticId,
601
- nativePaneBirthId: stock ? "" : birth,
602
+ nativePaneBirthId: birth || "",
602
603
  });
603
604
  });
604
605
  return Object.freeze({
@@ -44,7 +44,7 @@ export class WindowSplitAuthority {
44
44
  snapshot.panes.forEach((pane) => {
45
45
  if (!/^%(0|[1-9][0-9]{0,9})$/u.test(pane.runtimePaneId) ||
46
46
  Number(pane.runtimePaneId.slice(1)) > 0xffffffff ||
47
- (!this.options.stock &&
47
+ (!(this.options.stock && pane.nativePaneBirthId === "") &&
48
48
  !NativeJournalUint64SchemaZ.refine((birth) => birth !== "0").safeParse(pane.nativePaneBirthId).success))
49
49
  throw new WindowSplitLayoutUnavailable();
50
50
  });
@@ -5,6 +5,7 @@ import { createHomeAgentSelectionOwner } from "./application-home-agent-selectio
5
5
  import { createApplicationHomeAgentNavigator } from "./application-home-agent-navigation.js";
6
6
  import { applicationGenerationNavigationKey, createApplicationAgentNavigator, } from "./application-generation-starter.js";
7
7
  import { createApplicationPaletteCommandOwner } from "./application-palette-command-owner.js";
8
+ import { createApplicationPluginForm, pluginPaletteContext } from "./application-plugin-form.js";
8
9
  import { createApplicationPaneRenameOwner } from "./application-pane-rename-owner.js";
9
10
  import { applicationPaletteCommands, applicationPaletteCommandSource, } from "./application-palette-input.js";
10
11
  /** Observe the existing client, never open a second shell or poll for readiness. */
@@ -200,7 +201,29 @@ export function createApplicationHomeNavigationOwner(options) {
200
201
  setNote: options.setNote,
201
202
  observer: options.observer,
202
203
  });
204
+ // Plugin commands come from the local daemon's command catalog; a command
205
+ // with parameters opens a step-by-step form inside the palette.
206
+ const pluginCommands = options.pluginCommands;
207
+ let paletteOwner = null;
208
+ const pluginForm = pluginCommands &&
209
+ createApplicationPluginForm({
210
+ service: pluginCommands,
211
+ context: () => pluginPaletteContext(options.sessionOwner()?.sessionName() ?? null, options.focusedPane()),
212
+ query: () => paletteOwner?.query() ?? "",
213
+ setNote: options.setNote,
214
+ close: () => paletteOwner?.setOpen(false, "keyboard"),
215
+ stepChanged: () => paletteOwner?.resetForStep(),
216
+ });
203
217
  const paletteCommands = createApplicationPaletteCommandOwner({
218
+ ...(pluginCommands && pluginForm
219
+ ? {
220
+ plugins: {
221
+ form: pluginForm,
222
+ refresh: () => void pluginCommands.refresh(),
223
+ watch: () => pluginCommands.watch(),
224
+ },
225
+ }
226
+ : {}),
204
227
  commands: () => [
205
228
  ...(options.fleetCommands
206
229
  ? [
@@ -215,10 +238,13 @@ export function createApplicationHomeNavigationOwner(options) {
215
238
  : "hide-sidebar",
216
239
  ]
217
240
  : []),
241
+ ...(pluginCommands?.commands() ?? []),
218
242
  ],
219
243
  isOpen: () => Boolean(options.shell().semantic?.focus.palette.open ?? options.shell().localPaletteOpen),
220
244
  targetKey: () => `${applicationGenerationNavigationKey(options.sessionOwner()?.snapshot() ?? null)}:${options.focusedPane()}`,
221
245
  disabledReason: (command) => {
246
+ if (typeof command === "object" && command.kind === "plugin-form")
247
+ return command.disabledReason ?? null;
222
248
  if (typeof command === "object" && command.fleet?.disabled)
223
249
  return "Machine or session unavailable";
224
250
  if (typeof command === "object" ||
@@ -262,6 +288,7 @@ export function createApplicationHomeNavigationOwner(options) {
262
288
  openSession: (name, source) => options.startGeneration(name, false, source),
263
289
  onNavigationIntent: homeAgents.cancel,
264
290
  });
291
+ paletteOwner = paletteCommands;
265
292
  const paletteCommandList = paletteCommands.commands;
266
293
  return {
267
294
  homeAgents: options.fleetHome ? { ...homeAgents, presentation: options.fleetHome } : homeAgents,
@@ -1,3 +1,4 @@
1
+ import { createApplicationPluginCommands } from "./application-plugin-commands.js";
1
2
  import { createEffect } from "solid-js";
2
3
  import { createApplicationHomeFleetOwner } from "./application-home-fleet.js";
3
4
  import { createApplicationHomeNavigationOwner } from "./application-home-agents-owner.js";
@@ -33,6 +34,7 @@ export function createApplicationHomeExperience(options) {
33
34
  fleetCommands: machines.paletteCommands,
34
35
  openFleet: machines.openPalette,
35
36
  openSessions: () => machines.showSwitcher(false),
37
+ pluginCommands: createApplicationPluginCommands(),
36
38
  });
37
39
  const tour = createLazyApplicationGuidedTour({
38
40
  ...options,
@@ -6,9 +6,12 @@ export function createApplicationPaletteCommandOwner(options) {
6
6
  const [closeArmed, setCloseArmed] = createSignal(false);
7
7
  const [busy, setBusy] = createSignal(false);
8
8
  let armedTarget;
9
+ let stopWatch = null;
9
10
  let openRevision = 0;
11
+ const baseCommands = options.commands ?? (() => applicationPaletteCommands(null));
10
12
  const search = createApplicationPaletteSearchOwner({
11
- commands: options.commands ?? (() => applicationPaletteCommands(null)),
13
+ // While a plugin form is open the list is the current step's entries.
14
+ commands: () => options.plugins?.form.active() ? options.plugins.form.entries() : baseCommands(),
12
15
  open: options.isOpen ?? (() => false),
13
16
  activate: (command, source) => activate(command, source),
14
17
  close: () => setOpen(false, "keyboard"),
@@ -18,8 +21,14 @@ export function createApplicationPaletteCommandOwner(options) {
18
21
  setReferencePage(undefined);
19
22
  openRevision += 1;
20
23
  setCloseArmed(false);
21
- if (open)
24
+ options.plugins?.form.cancel();
25
+ stopWatch?.();
26
+ stopWatch = null;
27
+ if (open) {
28
+ options.plugins?.refresh();
29
+ stopWatch = options.plugins?.watch?.() ?? null;
22
30
  search.reset(options.activeSurface() === "home" ? 0 : 1);
31
+ }
23
32
  void options.binding
24
33
  .setPaletteOpen(open, options.commandSource(source, "command-palette"))
25
34
  .catch(() => options.setNote("Commands could not be updated. Try again."));
@@ -32,6 +41,22 @@ export function createApplicationPaletteCommandOwner(options) {
32
41
  setReferencePage(command === "help" ? "help" : command === "shortcuts" ? "shortcuts" : "changes");
33
42
  return;
34
43
  }
44
+ if (typeof command === "object" && command.kind === "plugin-form") {
45
+ if (command.disabledReason) {
46
+ options.setNote(command.disabledReason);
47
+ return;
48
+ }
49
+ options.plugins?.form.choose(command);
50
+ return;
51
+ }
52
+ if (typeof command === "object" && command.kind === "plugin-command") {
53
+ if (!options.plugins) {
54
+ options.setNote("Plugin commands are unavailable.");
55
+ return;
56
+ }
57
+ options.plugins.form.start(command);
58
+ return;
59
+ }
35
60
  if (command === "switch-session") {
36
61
  if (!options.openSessions) {
37
62
  options.setNote("Session switching is unavailable.");
@@ -150,6 +175,9 @@ export function createApplicationPaletteCommandOwner(options) {
150
175
  };
151
176
  return {
152
177
  ...search,
178
+ keyboardHint: () => options.plugins?.form.active() ? options.plugins.form.hint() : search.keyboardHint(),
179
+ /** Clear the search line and selection for a new form step. */
180
+ resetForStep: () => search.reset(0),
153
181
  referencePage,
154
182
  setReferencePage,
155
183
  busy,
@@ -0,0 +1,152 @@
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 { CommandCatalogResourceSchemaZ, CommandInvokeResultSchemaZ, CommandParamOptionsResultSchemaZ, } from "@tmux-ide/contracts";
10
+ import { createSignal } from "solid-js";
11
+ import WebSocket from "ws";
12
+ import { canonicalDaemonUrl, readCanonicalDaemonInfo, } from "../../../lib/canonical-daemon.js";
13
+ const defaultTransport = {
14
+ daemon: readCanonicalDaemonInfo,
15
+ fetch: (...args) => fetch(...args),
16
+ socket: (url, ownerToken) => new WebSocket(url, {
17
+ headers: { Authorization: `Bearer ${ownerToken}` },
18
+ }),
19
+ };
20
+ async function request(transport, method, path, body, signal) {
21
+ const daemon = transport.daemon();
22
+ if (!daemon?.authToken)
23
+ throw new Error("No local tmux-ide daemon is running.");
24
+ const response = await transport.fetch(canonicalDaemonUrl("http", daemon.bindHostname, daemon.port) + path, {
25
+ method,
26
+ redirect: "error",
27
+ signal,
28
+ headers: {
29
+ Authorization: `Bearer ${daemon.authToken}`,
30
+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),
31
+ },
32
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
33
+ });
34
+ const payload = await response.json().catch(() => null);
35
+ if (!response.ok) {
36
+ const message = payload && typeof payload === "object" && "error" in payload
37
+ ? String(payload.error)
38
+ : `The daemon answered ${response.status}.`;
39
+ throw new Error(message);
40
+ }
41
+ return payload;
42
+ }
43
+ export function createApplicationPluginCommands(transport = defaultTransport) {
44
+ const [commands, setCommands] = createSignal([]);
45
+ let inflight = null;
46
+ const refresh = async () => {
47
+ inflight?.abort();
48
+ const controller = new AbortController();
49
+ inflight = controller;
50
+ try {
51
+ const parsed = CommandCatalogResourceSchemaZ.safeParse(await request(transport, "GET", "/api/resources/command-catalog", undefined, AbortSignal.any([controller.signal, AbortSignal.timeout(3000)])));
52
+ if (!parsed.success || controller.signal.aborted)
53
+ return;
54
+ setCommands(parsed.data.entries.flatMap((entry) => entry.plugin
55
+ ? [
56
+ {
57
+ kind: "plugin-command",
58
+ id: entry.descriptor.id,
59
+ label: entry.descriptor.label,
60
+ category: entry.descriptor.category,
61
+ plugin: entry.plugin,
62
+ dangerous: entry.descriptor.dangerous,
63
+ params: entry.params,
64
+ },
65
+ ]
66
+ : []));
67
+ }
68
+ catch {
69
+ // No daemon, or plugins off: the palette simply shows no plugin commands.
70
+ }
71
+ finally {
72
+ if (inflight === controller)
73
+ inflight = null;
74
+ }
75
+ };
76
+ return {
77
+ commands,
78
+ /** Fetch the catalog again; keeps the last list if the daemon is unreachable. */
79
+ refresh,
80
+ /**
81
+ * Follow the daemon's command-catalog invalidations while the palette is
82
+ * open, so a plugin reload shows up without reopening it. Returns a stop
83
+ * function; does nothing without a daemon or a socket.
84
+ */
85
+ watch() {
86
+ const daemon = transport.daemon();
87
+ if (!daemon?.authToken || !transport.socket)
88
+ return () => { };
89
+ let socket;
90
+ try {
91
+ socket = transport.socket(canonicalDaemonUrl("ws", daemon.bindHostname, daemon.port, "/ws/events?mode=semantic"), daemon.authToken);
92
+ }
93
+ catch {
94
+ return () => { };
95
+ }
96
+ let stopped = false;
97
+ socket.addEventListener("error", () => { });
98
+ socket.addEventListener("open", () => {
99
+ socket.send(JSON.stringify({
100
+ type: "subscribe",
101
+ sessions: [],
102
+ interests: [{ resource: "command-catalog", workspaceName: null }],
103
+ legacyEvents: false,
104
+ }));
105
+ });
106
+ socket.addEventListener("message", (event) => {
107
+ if (stopped || (typeof event.data !== "string" && !Buffer.isBuffer(event.data)))
108
+ return;
109
+ let frame;
110
+ try {
111
+ frame = JSON.parse(String(event.data));
112
+ }
113
+ catch {
114
+ return;
115
+ }
116
+ if (frame &&
117
+ typeof frame === "object" &&
118
+ frame.type === "resource.changed" &&
119
+ frame.resource === "command-catalog")
120
+ void refresh();
121
+ });
122
+ return () => {
123
+ if (stopped)
124
+ return;
125
+ stopped = true;
126
+ socket.close(1000, "palette closed");
127
+ };
128
+ },
129
+ async invoke(id, args, context, confirmed) {
130
+ try {
131
+ const parsed = CommandInvokeResultSchemaZ.safeParse(await request(transport, "POST", "/api/v2/commands/invoke", { id, args, context, ...(confirmed ? { confirmed: true } : {}) }, AbortSignal.timeout(60_000)));
132
+ return parsed.success
133
+ ? parsed.data
134
+ : { ok: false, error: "The daemon sent an unexpected answer." };
135
+ }
136
+ catch (error) {
137
+ return { ok: false, error: error.message };
138
+ }
139
+ },
140
+ async paramOptions(id, param, context) {
141
+ try {
142
+ const parsed = CommandParamOptionsResultSchemaZ.safeParse(await request(transport, "POST", "/api/v2/commands/param-options", { id, param, context }, AbortSignal.timeout(30_000)));
143
+ return parsed.success
144
+ ? parsed.data
145
+ : { ok: false, error: "The daemon sent an unexpected answer." };
146
+ }
147
+ catch (error) {
148
+ return { ok: false, error: error.message };
149
+ }
150
+ },
151
+ };
152
+ }