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,251 @@
1
+ /**
2
+ * The step-by-step form a plugin command with parameters opens inside the
3
+ * palette. Each step is one parameter: the palette's search line is the
4
+ * input, and its list holds the step's entries (a choice per option, or one
5
+ * "Use …" entry for free text). A dangerous command ends with a confirm step.
6
+ *
7
+ * Arguments are checked again by the plugin; this only collects them.
8
+ */
9
+ import { terminalSafe, } from "@tmux-ide/contracts";
10
+ import { createSignal } from "solid-js";
11
+ const quote = (value) => (typeof value === "string" ? `“${value}”` : String(value));
12
+ function resultNote(label, result) {
13
+ if (!result.ok)
14
+ return `${label}: ${result.error}`;
15
+ if (typeof result.value === "string" && result.value.trim())
16
+ return `${label}: ${result.value}`;
17
+ return `${label}: done`;
18
+ }
19
+ /**
20
+ * The context a palette invocation sends. The TUI's focused pane id is its
21
+ * own mirror id, not the tmux `%N` id plugins pass to ide.exec{context}, so
22
+ * only a real tmux pane id is sent as `pane`.
23
+ */
24
+ export function pluginPaletteContext(session, focusedPane) {
25
+ const pane = focusedPane && /^%\d{1,9}$/u.test(focusedPane) ? focusedPane : null;
26
+ return {
27
+ source: "palette",
28
+ ...(session ? { session } : {}),
29
+ ...(pane ? { pane } : {}),
30
+ };
31
+ }
32
+ export function createApplicationPluginForm(options) {
33
+ const [state, setState] = createSignal(null);
34
+ let generation = 0;
35
+ // Notes carry plugin text (labels, results, errors) to the terminal.
36
+ const setNote = (note) => options.setNote(note === null ? null : terminalSafe(note, 500));
37
+ const run = (command, args) => {
38
+ setState(null);
39
+ options.close();
40
+ setNote(`${command.label}…`);
41
+ void options.service
42
+ .invoke(command.id, args, options.context(), command.dangerous)
43
+ .then((result) => setNote(resultNote(command.label, result)));
44
+ };
45
+ const loadOptions = (current, param) => {
46
+ if (!param.dynamicChoices && !param.dynamicDefault)
47
+ return;
48
+ if (current.options[param.name])
49
+ return;
50
+ const marker = current.generation;
51
+ setState({ ...current, options: { ...current.options, [param.name]: { phase: "loading" } } });
52
+ void options.service
53
+ .paramOptions(current.command.id, param.name, options.context())
54
+ .then((result) => {
55
+ const latest = state();
56
+ if (!latest || latest.generation !== marker)
57
+ return;
58
+ setState({
59
+ ...latest,
60
+ options: {
61
+ ...latest.options,
62
+ [param.name]: result.ok
63
+ ? {
64
+ phase: "ready",
65
+ ...(result.choices ? { choices: result.choices } : {}),
66
+ ...(result.default !== undefined ? { default: result.default } : {}),
67
+ }
68
+ : { phase: "error", error: result.error },
69
+ },
70
+ });
71
+ });
72
+ };
73
+ const enterStep = (next) => {
74
+ const { command } = next;
75
+ if (next.step >= command.params.length) {
76
+ // Past the last parameter: confirm a dangerous command, else run it.
77
+ if (command.dangerous && next.step === command.params.length) {
78
+ setState(next);
79
+ options.stepChanged();
80
+ return;
81
+ }
82
+ run(command, { ...next.values });
83
+ return;
84
+ }
85
+ setState(next);
86
+ options.stepChanged();
87
+ loadOptions(next, command.params[next.step]);
88
+ };
89
+ const currentParam = (current) => current.command.params[current.step] ?? null;
90
+ const defaultFor = (current, param) => current.options[param.name]?.default ?? param.default;
91
+ const choicesFor = (current, param) => current.options[param.name]?.choices ?? param.choices ?? [];
92
+ const advance = (current, param, value) => {
93
+ const values = { ...current.values };
94
+ if (value === undefined)
95
+ delete values[param.name];
96
+ else
97
+ values[param.name] = value;
98
+ enterStep({ ...current, step: current.step + 1, values });
99
+ };
100
+ return {
101
+ active: () => state() !== null,
102
+ /**
103
+ * Start a plugin command. One without parameters and not dangerous runs
104
+ * at once; otherwise the palette turns into its form.
105
+ */
106
+ start(command) {
107
+ generation += 1;
108
+ if (command.params.length === 0 && !command.dangerous) {
109
+ run(command, {});
110
+ return;
111
+ }
112
+ enterStep({ command, step: 0, values: {}, options: {}, generation });
113
+ },
114
+ cancel() {
115
+ if (!state())
116
+ return;
117
+ generation += 1;
118
+ setState(null);
119
+ },
120
+ entries() {
121
+ const current = state();
122
+ if (!current)
123
+ return [];
124
+ const param = currentParam(current);
125
+ if (!param) {
126
+ return [
127
+ {
128
+ kind: "plugin-form",
129
+ key: "run",
130
+ label: `Run ${current.command.label}`,
131
+ detail: "This cannot be undone",
132
+ },
133
+ { kind: "plugin-form", key: "cancel", label: "Cancel", detail: "Do nothing" },
134
+ ];
135
+ }
136
+ const detail = param.description ?? param.label;
137
+ const loaded = current.options[param.name];
138
+ const out = [];
139
+ if (loaded?.phase === "loading") {
140
+ out.push({
141
+ kind: "plugin-form",
142
+ key: "loading",
143
+ label: "Loading choices…",
144
+ detail,
145
+ disabledReason: "Still loading choices",
146
+ });
147
+ return out;
148
+ }
149
+ if (loaded?.phase === "error") {
150
+ out.push({
151
+ kind: "plugin-form",
152
+ key: "error",
153
+ label: loaded.error ?? "Choices are unavailable",
154
+ detail,
155
+ disabledReason: "The plugin could not list choices",
156
+ });
157
+ }
158
+ const fallback = defaultFor(current, param);
159
+ if (param.type === "choice") {
160
+ for (const choice of choicesFor(current, param)) {
161
+ out.push({
162
+ kind: "plugin-form",
163
+ key: `choice:${choice.value}`,
164
+ label: choice.value === fallback ? `${choice.label} (default)` : choice.label,
165
+ detail,
166
+ });
167
+ }
168
+ }
169
+ else if (param.type === "boolean") {
170
+ for (const value of [true, false]) {
171
+ out.push({
172
+ kind: "plugin-form",
173
+ key: `bool:${value}`,
174
+ label: `${value ? "Yes" : "No"}${fallback === value ? " (default)" : ""}`,
175
+ detail,
176
+ });
177
+ }
178
+ }
179
+ else {
180
+ const typed = options.query();
181
+ out.push({
182
+ kind: "plugin-form",
183
+ key: "submit",
184
+ label: typed
185
+ ? `Use ${quote(typed)}`
186
+ : fallback !== undefined
187
+ ? `Use default ${quote(fallback)}`
188
+ : `Type the ${param.label.toLowerCase()}`,
189
+ detail,
190
+ ...(!typed && fallback === undefined && param.required
191
+ ? { disabledReason: `${param.label} is required` }
192
+ : {}),
193
+ });
194
+ }
195
+ if (!param.required)
196
+ out.push({ kind: "plugin-form", key: "skip", label: "Leave empty", detail });
197
+ return out;
198
+ },
199
+ /** The person activated one of the current step's entries. */
200
+ choose(entry) {
201
+ const current = state();
202
+ if (!current)
203
+ return;
204
+ const param = currentParam(current);
205
+ if (!param) {
206
+ if (entry.key === "run")
207
+ run(current.command, { ...current.values });
208
+ else {
209
+ setState(null);
210
+ options.close();
211
+ setNote(`${current.command.label}: cancelled`);
212
+ }
213
+ return;
214
+ }
215
+ if (entry.key === "skip")
216
+ return advance(current, param, undefined);
217
+ if (entry.key.startsWith("choice:"))
218
+ return advance(current, param, entry.key.slice(7));
219
+ if (entry.key.startsWith("bool:"))
220
+ return advance(current, param, entry.key === "bool:true");
221
+ if (entry.key !== "submit")
222
+ return;
223
+ const typed = options.query();
224
+ const raw = typed || defaultFor(current, param);
225
+ if (raw === undefined || raw === "") {
226
+ setNote(`${param.label} is required`);
227
+ return;
228
+ }
229
+ if (param.type === "number") {
230
+ const number = typeof raw === "number" ? raw : Number(raw);
231
+ if (!Number.isFinite(number) || (typeof raw === "string" && raw.trim() === "")) {
232
+ setNote(`${param.label} must be a number`);
233
+ return;
234
+ }
235
+ return advance(current, param, number);
236
+ }
237
+ advance(current, param, String(raw));
238
+ },
239
+ /** Keyboard hint while the form is open. */
240
+ hint() {
241
+ const current = state();
242
+ if (!current)
243
+ return "";
244
+ const param = currentParam(current);
245
+ const total = current.command.params.length;
246
+ return terminalSafe(param
247
+ ? `${current.command.label} · ${param.label} (${current.step + 1}/${total}) · Enter to choose · Esc to cancel`
248
+ : `${current.command.label} · confirm · Enter to choose · Esc to cancel`, 500);
249
+ },
250
+ };
251
+ }
@@ -1,4 +1,5 @@
1
1
  import { CHROME_ACTIONS } from "./application-action-descriptions.js";
2
+ import { terminalSafe } from "@tmux-ide/contracts";
2
3
  import { fuzzyTermsMatch as commandSearchMatch } from "../../team/fuzzy.js";
3
4
  export { fuzzyTermsMatch as commandSearchMatch } from "../../team/fuzzy.js";
4
5
  import { PANE_ACTION_MENU_ITEMS } from "./pane-action-menu-model.js";
@@ -32,6 +33,19 @@ export function applicationCommandDescription(command) {
32
33
  };
33
34
  if (command === "shortcuts" || command === "whats-new")
34
35
  return { id: command, ...PALETTE_REFERENCE_COMMANDS[command], detail: "Help and reference" };
36
+ if (typeof command === "object" && command.kind === "plugin-command")
37
+ return {
38
+ id: JSON.stringify([command.kind, command.id]),
39
+ // Plugin text: plain text only, even if something upstream let it through.
40
+ label: terminalSafe(command.params.length > 0 || command.dangerous ? `${command.label}…` : command.label, 200),
41
+ detail: terminalSafe(`${command.category} · ${command.plugin} plugin`, 200),
42
+ };
43
+ if (typeof command === "object" && command.kind === "plugin-form")
44
+ return {
45
+ id: JSON.stringify([command.kind, command.key]),
46
+ label: terminalSafe(command.label, 200),
47
+ detail: terminalSafe(command.detail, 500),
48
+ };
35
49
  if (typeof command === "object" && command.kind === "open-machine")
36
50
  return {
37
51
  id: JSON.stringify([
@@ -1,6 +1,11 @@
1
+ import { terminalSafe } from "@tmux-ide/contracts";
1
2
  export function paletteSection(command) {
2
3
  if (command === "switch-session")
3
4
  return "Sessions";
5
+ if (typeof command === "object" && command.kind === "plugin-command")
6
+ return terminalSafe(command.category, 80);
7
+ if (typeof command === "object" && command.kind === "plugin-form")
8
+ return "Choose";
4
9
  if (typeof command === "object")
5
10
  return command.kind === "jump-agent"
6
11
  ? "Agents"
@@ -0,0 +1,116 @@
1
+ /**
2
+ * The command catalog and plugin action invocation, owner-only and never for
3
+ * browsers (the same gate as the plugin routes):
4
+ * GET /api/resources/command-catalog built-in and plugin commands
5
+ * POST /api/v2/commands/invoke run a plugin action
6
+ * POST /api/v2/commands/param-options one parameter's choices and default
7
+ *
8
+ * Built-in actions keep their own typed route, `/api/v2/action/:name`; the
9
+ * catalog lists them so the CLI and palettes see one list.
10
+ */
11
+ import {
12
+ COMMAND_CATALOG_VERSION,
13
+ CommandInvokeRequestSchemaZ,
14
+ CommandParamOptionsRequestSchemaZ,
15
+ type CommandCatalogEntry,
16
+ type CommandCatalogResource,
17
+ type CommandDescriptor,
18
+ type CommandInvocationContext,
19
+ type CommandInvokeResult,
20
+ type CommandParamOptionsResult,
21
+ } from "@tmux-ide/contracts";
22
+ import type { Hono } from "hono";
23
+ import { bodyLimit } from "hono/body-limit";
24
+ import { ownerOnlyNonBrowserGuard } from "./plugin-routes.ts";
25
+
26
+ export interface CommandCatalogBackend {
27
+ actionCatalog(): { revision: number; entries: CommandCatalogEntry[] };
28
+ invokeAction(
29
+ id: string,
30
+ args: Record<string, string | number | boolean>,
31
+ context: CommandInvocationContext,
32
+ options: { confirmed?: boolean },
33
+ ): Promise<CommandInvokeResult>;
34
+ actionParamOptions(
35
+ id: string,
36
+ param: string,
37
+ context: CommandInvocationContext,
38
+ ): Promise<CommandParamOptionsResult>;
39
+ }
40
+
41
+ export function buildCommandCatalog(
42
+ builtins: readonly CommandDescriptor[],
43
+ plugins: CommandCatalogBackend | null,
44
+ ): CommandCatalogResource {
45
+ const pluginCatalog = plugins?.actionCatalog() ?? { revision: 0, entries: [] };
46
+ return {
47
+ version: COMMAND_CATALOG_VERSION,
48
+ revision: pluginCatalog.revision,
49
+ entries: [
50
+ ...builtins.map((descriptor) => ({ descriptor, params: [] })),
51
+ ...pluginCatalog.entries,
52
+ ],
53
+ };
54
+ }
55
+
56
+ export function mountCommandCatalogRoutes(
57
+ app: Hono,
58
+ options: {
59
+ ownerToken: string | null;
60
+ builtins: () => readonly CommandDescriptor[];
61
+ backend: CommandCatalogBackend | null;
62
+ },
63
+ ): void {
64
+ const guard = ownerOnlyNonBrowserGuard(options.ownerToken);
65
+
66
+ app.get("/api/resources/command-catalog", (c) => {
67
+ const gate = guard(c);
68
+ if (gate) return gate;
69
+ c.header("Cache-Control", "no-store");
70
+ return c.json(buildCommandCatalog(options.builtins(), options.backend));
71
+ });
72
+
73
+ app.post("/api/v2/commands/invoke", bodyLimit({ maxSize: 256 * 1024 }), async (c) => {
74
+ const gate = guard(c);
75
+ if (gate) return gate;
76
+ c.header("Cache-Control", "no-store");
77
+ let body: unknown;
78
+ try {
79
+ body = await c.req.json();
80
+ } catch {
81
+ return c.json({ error: "Invalid invoke request" }, 400);
82
+ }
83
+ const parsed = CommandInvokeRequestSchemaZ.safeParse(body);
84
+ if (!parsed.success) return c.json({ error: "Invalid invoke request" }, 400);
85
+ if (!parsed.data.id.startsWith("plugin."))
86
+ return c.json({ error: "Built-in commands use /api/v2/action/:name" }, 404);
87
+ if (!options.backend) return c.json({ error: "Plugins are not enabled in this daemon" }, 503);
88
+ const { id, args, context, confirmed } = parsed.data;
89
+ const result = await options.backend.invokeAction(id, args, context, {
90
+ confirmed: confirmed === true,
91
+ });
92
+ return c.json(result);
93
+ });
94
+
95
+ app.post("/api/v2/commands/param-options", bodyLimit({ maxSize: 16 * 1024 }), async (c) => {
96
+ const gate = guard(c);
97
+ if (gate) return gate;
98
+ c.header("Cache-Control", "no-store");
99
+ let body: unknown;
100
+ try {
101
+ body = await c.req.json();
102
+ } catch {
103
+ return c.json({ error: "Invalid options request" }, 400);
104
+ }
105
+ const parsed = CommandParamOptionsRequestSchemaZ.safeParse(body);
106
+ if (!parsed.success) return c.json({ error: "Invalid options request" }, 400);
107
+ if (!options.backend) return c.json({ error: "Plugins are not enabled in this daemon" }, 503);
108
+ return c.json(
109
+ await options.backend.actionParamOptions(
110
+ parsed.data.id,
111
+ parsed.data.param,
112
+ parsed.data.context,
113
+ ),
114
+ );
115
+ });
116
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Owner-only routes for plugins:
3
+ * GET /api/v2/plugins status of the host and every plugin
4
+ * POST /api/v2/plugins/reload { name? }: discover again and reload
5
+ * POST /api/v2/lua/run { code, chunkName?, budgetMs? }: run once
6
+ *
7
+ * `lua/run` executes code with the owner's authority, so every route needs
8
+ * the owner capability, never the shared remote-access token. The check is
9
+ * `ownerAuthorityGate`, the same one behind `/api/v2/capabilities` and the
10
+ * owner-only actions such as `project.launch`, which also run user code.
11
+ *
12
+ * None of these routes serve browsers: a request that carries `Origin` or
13
+ * any `Sec-Fetch-*` header is refused before the credential is looked at,
14
+ * so the daemon's permissive CORS policy cannot expose them to a web page.
15
+ */
16
+ import type { Context, Hono } from "hono";
17
+ import { bodyLimit } from "hono/body-limit";
18
+ import { z } from "zod";
19
+ import { ownerAuthorityGate } from "./owner-authority.ts";
20
+ import type { LuaRunResult, PluginSupervisorStatus } from "../plugins/supervisor.ts";
21
+
22
+ export interface PluginRouteBackend {
23
+ status(): PluginSupervisorStatus;
24
+ reload(name?: string): Promise<PluginSupervisorStatus>;
25
+ run(code: string, options: { chunkName?: string; budgetMs?: number }): Promise<LuaRunResult>;
26
+ }
27
+
28
+ const ReloadRequestZ = z.strictObject({ name: z.string().min(1).max(64).optional() });
29
+ const RunRequestZ = z.strictObject({
30
+ code: z.string().max(1024 * 1024),
31
+ chunkName: z
32
+ .string()
33
+ .min(1)
34
+ .max(200)
35
+ .regex(/^[=@][^\0\n]*$/u)
36
+ .optional(),
37
+ budgetMs: z.number().int().min(10).max(600_000).optional(),
38
+ });
39
+
40
+ /**
41
+ * The gate every plugin and command-catalog route uses: refuse anything a
42
+ * browser sent, then require the owner capability.
43
+ */
44
+ export function ownerOnlyNonBrowserGuard(
45
+ ownerToken: string | null,
46
+ ): (c: Context) => Response | null {
47
+ const authorize = ownerAuthorityGate(ownerToken, {
48
+ whenOwnerless: "unavailable",
49
+ unavailableMessage: "Plugins are unavailable",
50
+ mismatchMessage: "Plugins require owner authority",
51
+ });
52
+ const refuseBrowser = (c: Context): Response | null => {
53
+ const headers = c.req.header();
54
+ const fromBrowser = Object.keys(headers).some(
55
+ (name) => name === "origin" || name.startsWith("sec-fetch-"),
56
+ );
57
+ return fromBrowser ? c.json({ error: "Plugins cannot be used from a browser" }, 403) : null;
58
+ };
59
+ return (c) => refuseBrowser(c) ?? authorize(c);
60
+ }
61
+
62
+ export function mountPluginRoutes(
63
+ app: Hono,
64
+ options: { ownerToken: string | null; backend: PluginRouteBackend | null },
65
+ ): void {
66
+ const guard = ownerOnlyNonBrowserGuard(options.ownerToken);
67
+ const unavailable = { error: "Plugins are not enabled in this daemon" };
68
+
69
+ app.get("/api/v2/plugins", (c) => {
70
+ const gate = guard(c);
71
+ if (gate) return gate;
72
+ c.header("Cache-Control", "no-store");
73
+ if (!options.backend) return c.json(unavailable, 503);
74
+ return c.json({ ok: true, ...options.backend.status() });
75
+ });
76
+
77
+ app.post("/api/v2/plugins/reload", bodyLimit({ maxSize: 4 * 1024 }), async (c) => {
78
+ const gate = guard(c);
79
+ if (gate) return gate;
80
+ c.header("Cache-Control", "no-store");
81
+ if (!options.backend) return c.json(unavailable, 503);
82
+ let body: unknown;
83
+ try {
84
+ const text = await c.req.text();
85
+ body = text ? JSON.parse(text) : {};
86
+ } catch {
87
+ return c.json({ error: "Invalid reload request" }, 400);
88
+ }
89
+ const parsed = ReloadRequestZ.safeParse(body);
90
+ if (!parsed.success) return c.json({ error: "Invalid reload request" }, 400);
91
+ return c.json({ ok: true, ...(await options.backend.reload(parsed.data.name)) });
92
+ });
93
+
94
+ app.post("/api/v2/lua/run", bodyLimit({ maxSize: 1024 * 1024 + 4096 }), async (c) => {
95
+ const gate = guard(c);
96
+ if (gate) return gate;
97
+ c.header("Cache-Control", "no-store");
98
+ if (!options.backend) return c.json(unavailable, 503);
99
+ let body: unknown;
100
+ try {
101
+ body = await c.req.json();
102
+ } catch {
103
+ return c.json({ error: "Invalid run request" }, 400);
104
+ }
105
+ const parsed = RunRequestZ.safeParse(body);
106
+ if (!parsed.success) return c.json({ error: "Invalid run request" }, 400);
107
+ const { code, ...runOptions } = parsed.data;
108
+ return c.json({ result: await options.backend.run(code, runOptions) });
109
+ });
110
+ }
@@ -147,6 +147,8 @@ import { FilesAuthority } from "./resources/workspace-files-authority.ts";
147
147
  import { ChangesAuthority } from "./resources/workspace-changes-authority.ts";
148
148
  import { loadApplicationShellAppWindows } from "../lib/application-shell-app-windows.ts";
149
149
  import { daemonActionCommandRegistry } from "./actions/command-definitions.ts";
150
+ import { mountPluginRoutes, type PluginRouteBackend } from "./plugin-routes.ts";
151
+ import { mountCommandCatalogRoutes, type CommandCatalogBackend } from "./command-catalog-routes.ts";
150
152
  import { MissionRepository, type MissionRepositorySnapshot } from "../lib/mission-repository.ts";
151
153
  import { projectDesktopMissionWorkspace } from "./resources/desktop-missions.ts";
152
154
  import {
@@ -194,6 +196,8 @@ export interface CreateAppOptions {
194
196
  appWindowMutationBackend?: import("./actions/handlers/app-window-mutate.ts").AppWindowMutationBackend;
195
197
  workspaceMultiplexerBackend?: import("./actions/handlers/workspace-multiplexer.ts").WorkspaceMultiplexerBackend;
196
198
  workspaceRegistry?: import("../lib/workspace-registry.ts").WorkspaceRegistry;
199
+ /** The canonical daemon's plugin supervisor; absent in other daemons. */
200
+ pluginBackend?: (PluginRouteBackend & CommandCatalogBackend) | null;
197
201
  terminalAttachmentIssueBackend?: TerminalAttachmentIssueBackend | null;
198
202
  /** Catalog + startup-barrier facts for the startup readiness ladder. */
199
203
  startupReadinessAttachmentBackend?: StartupReadinessAttachmentAuthority | null;
@@ -441,6 +445,8 @@ function matchLogChannel(channel: string): ((entry: LogEntry) => boolean) | null
441
445
  return (entry) => entry.component.startsWith("hq") || entry.component.startsWith("remote");
442
446
  case "watchdog":
443
447
  return (entry) => entry.component.startsWith("watchdog");
448
+ case "plugins":
449
+ return (entry) => entry.component.startsWith("plugin.");
444
450
  default:
445
451
  return null;
446
452
  }
@@ -605,6 +611,15 @@ export function createApp(options: CreateAppOptions = {}): Hono {
605
611
  daemon: daemonInstanceIdentity,
606
612
  ownerToken: options.remoteAccess?.ownerToken ?? null,
607
613
  });
614
+ mountPluginRoutes(app, {
615
+ ownerToken: options.remoteAccess?.ownerToken ?? null,
616
+ backend: options.pluginBackend ?? null,
617
+ });
618
+ mountCommandCatalogRoutes(app, {
619
+ ownerToken: options.remoteAccess?.ownerToken ?? null,
620
+ builtins: () => daemonActionCommandRegistry.descriptors(),
621
+ backend: options.pluginBackend ?? null,
622
+ });
608
623
 
609
624
  // --- Auth routes (always available, bypassed by middleware) ---
610
625
 
@@ -182,9 +182,9 @@ function check(
182
182
  type TmuxProbe = (args: readonly string[]) => string;
183
183
  const UNKNOWN = (command: string) => new RegExp(`^unknown command: ${command}$`, "mu");
184
184
 
185
- type NativeAnswer = "full" | "stock" | "partial" | "no-server" | "unknown";
186
- /** The same reading of the server as the mirror's: stock only when it refuses both
187
- * native commands by name, and full only with the split capability it requires. */
185
+ type NativeAnswer = "full" | "stock" | "older" | "partial" | "no-server" | "unknown";
186
+ /** The same reading of the server as the mirror's: the stock resize when it refuses
187
+ * the split command by name, and full only with the split capability it requires. */
188
188
  function nativeCommands(probe: TmuxProbe): NativeAnswer {
189
189
  const ask = (command: string) => {
190
190
  try {
@@ -201,7 +201,12 @@ function nativeCommands(probe: TmuxProbe): NativeAnswer {
201
201
  return "no-server";
202
202
  const refused = (answer: { failure?: string }, command: string) =>
203
203
  answer.failure !== undefined && UNKNOWN(command).test(answer.failure);
204
- if (refused(split, "tmux-ide-resize-split") && refused(events, "tmux-ide-events")) return "stock";
204
+ if (refused(split, "tmux-ide-resize-split")) {
205
+ if (refused(events, "tmux-ide-events")) return "stock";
206
+ // The journal answers: a tmux-ide tmux built before the split command.
207
+ if (events.output !== undefined) return "older";
208
+ return "unknown";
209
+ }
205
210
  if (split.output !== undefined && events.output !== undefined) {
206
211
  try {
207
212
  return nativeSplitCapability(split.output) ? "full" : "partial";
@@ -220,13 +225,15 @@ export function tmuxFeaturesRow(probeServer: TmuxProbe, probeBinary: TmuxProbe):
220
225
  const details: Record<NativeAnswer, string> = {
221
226
  full: "bundled tmux: full features",
222
227
  stock: "stock tmux: reduced features",
228
+ older:
229
+ "older tmux-ide tmux: reduced features (restart it with tmux-ide's own tmux for every feature; that ends its sessions)",
223
230
  partial: "this tmux has only some tmux-ide commands: no pane dividers",
224
231
  "no-server": "could not read the tmux server's features",
225
232
  unknown: "could not read the tmux server's features",
226
233
  };
227
234
  return {
228
235
  label: "tmux features",
229
- pass: answer === "full" || answer === "stock",
236
+ pass: answer === "full" || answer === "stock" || answer === "older",
230
237
  detail: details[answer],
231
238
  optional: true,
232
239
  };
@@ -254,3 +254,22 @@ export async function tryDispatchAction<Name extends ActionName>(
254
254
  }
255
255
  return null;
256
256
  }
257
+
258
+ /**
259
+ * The running canonical daemon's base URL and owner token, for CLI commands
260
+ * that call daemon routes other than the action dispatcher.
261
+ */
262
+ export async function resolveCanonicalDaemonEndpoint(
263
+ options: { cwd?: string; autostart?: boolean } = {},
264
+ ): Promise<{ baseUrl: string; ownerToken: string | null } | null> {
265
+ const bridgeDeps = deps;
266
+ return resolveCanonicalDaemon(bridgeDeps, {
267
+ autostart: options.autostart ?? true,
268
+ cwd: options.cwd ?? bridgeDeps.cwd(),
269
+ });
270
+ }
271
+
272
+ /** `fetch`, replaceable in tests through {@link __setCliActionBridgeDepsForTests}. */
273
+ export function cliBridgeFetch(): typeof fetch {
274
+ return deps.fetch;
275
+ }