tmux-ide 2.9.20 → 2.9.22

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 (145) hide show
  1. package/bin/cli.js +16998 -4283
  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 +3 -0
  7. package/packages/contracts/src/pane-reader.ts +121 -0
  8. package/packages/contracts/src/pane-stream.ts +18 -0
  9. package/packages/contracts/src/plain-text.ts +61 -0
  10. package/packages/contracts/src/visual-theme-presets.ts +58 -2
  11. package/packages/daemon/dist/command-center/command-catalog-routes.js +78 -0
  12. package/packages/daemon/dist/command-center/plugin-routes.js +84 -0
  13. package/packages/daemon/dist/command-center/server.js +13 -0
  14. package/packages/daemon/dist/command-center/tmux-server-reader.js +41 -0
  15. package/packages/daemon/dist/command-center/tmux-servers.js +6 -0
  16. package/packages/daemon/dist/doctor.js +106 -43
  17. package/packages/daemon/dist/lib/cli-action-bridge.js +15 -0
  18. package/packages/daemon/dist/lib/cli-command.js +13 -0
  19. package/packages/daemon/dist/lib/daemon-embed.js +39 -1
  20. package/packages/daemon/dist/lib/headless-daemon.js +1 -0
  21. package/packages/daemon/dist/lib/pane-reader-files.js +226 -0
  22. package/packages/daemon/dist/lib/remote-tmux-command.js +8 -5
  23. package/packages/daemon/dist/lib/tmux-client-execution.js +73 -7
  24. package/packages/daemon/dist/lib/tmux-pane-reader.js +105 -0
  25. package/packages/daemon/dist/lib/tmux-server-features.js +38 -0
  26. package/packages/daemon/dist/lib/tmux-server-owner.js +9 -0
  27. package/packages/daemon/dist/lib/worktree.js +18 -0
  28. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  29. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  30. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  31. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  32. package/packages/daemon/dist/open-browser.js +26 -12
  33. package/packages/daemon/dist/open-reader.js +84 -0
  34. package/packages/daemon/dist/plugins/action-catalog.js +129 -0
  35. package/packages/daemon/dist/plugins/action-cli.js +212 -0
  36. package/packages/daemon/dist/plugins/api-table.js +303 -0
  37. package/packages/daemon/dist/plugins/cli.js +556 -0
  38. package/packages/daemon/dist/plugins/consent.js +107 -0
  39. package/packages/daemon/dist/plugins/daemon-plugins.js +124 -0
  40. package/packages/daemon/dist/plugins/discovery.js +142 -0
  41. package/packages/daemon/dist/plugins/examples/worktree-tasks.js +115 -0
  42. package/packages/daemon/dist/plugins/exec-sandbox.js +202 -0
  43. package/packages/daemon/dist/plugins/host/actions-prelude.js +279 -0
  44. package/packages/daemon/dist/plugins/host/entry.js +4 -0
  45. package/packages/daemon/dist/plugins/host/host-api-prelude.js +232 -0
  46. package/packages/daemon/dist/plugins/host/lua-state.js +493 -0
  47. package/packages/daemon/dist/plugins/host/main.js +322 -0
  48. package/packages/daemon/dist/plugins/host/sandbox.js +299 -0
  49. package/packages/daemon/dist/plugins/host-calls.js +279 -0
  50. package/packages/daemon/dist/plugins/manifest.js +69 -0
  51. package/packages/daemon/dist/plugins/plugin-exec.js +261 -0
  52. package/packages/daemon/dist/plugins/plugin-log.js +54 -0
  53. package/packages/daemon/dist/plugins/plugin-store.js +74 -0
  54. package/packages/daemon/dist/plugins/protocol.js +252 -0
  55. package/packages/daemon/dist/plugins/safe-files.js +97 -0
  56. package/packages/daemon/dist/plugins/supervisor.js +790 -0
  57. package/packages/daemon/dist/plugins/worktree-calls.js +154 -0
  58. package/packages/daemon/dist/restore.js +57 -40
  59. package/packages/daemon/dist/terminal/mirror/session-channel.js +4 -1
  60. package/packages/daemon/dist/terminal/pane-stream/pane-stream-websocket.js +12 -3
  61. package/packages/daemon/dist/terminal/protocol/reader-option.js +66 -0
  62. package/packages/daemon/dist/terminal/protocol/session-descriptor-discovery.js +7 -2
  63. package/packages/daemon/dist/tmux-upgrade/cli.js +106 -0
  64. package/packages/daemon/dist/tmux-upgrade/io.js +540 -0
  65. package/packages/daemon/dist/tmux-upgrade/plan.js +238 -0
  66. package/packages/daemon/dist/tmux-upgrade/run.js +199 -0
  67. package/packages/daemon/dist/tui/chrome/snapshot.js +3 -4
  68. package/packages/daemon/dist/tui/mirror/runtime/application-home-agent-navigation.js +64 -4
  69. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +62 -5
  70. package/packages/daemon/dist/tui/mirror/runtime/application-home-experience.js +2 -0
  71. package/packages/daemon/dist/tui/mirror/runtime/application-machine-agent-navigation.js +12 -8
  72. package/packages/daemon/dist/tui/mirror/runtime/application-palette-command-owner.js +30 -2
  73. package/packages/daemon/dist/tui/mirror/runtime/application-plugin-commands.js +152 -0
  74. package/packages/daemon/dist/tui/mirror/runtime/application-plugin-form.js +251 -0
  75. package/packages/daemon/dist/tui/mirror/runtime/application-terminal-interaction-controller.js +125 -111
  76. package/packages/daemon/dist/tui/mirror/workspace/application-command-description.js +14 -0
  77. package/packages/daemon/dist/tui/mirror/workspace/palette-list-layout.js +5 -0
  78. package/packages/daemon/src/command-center/command-catalog-routes.ts +116 -0
  79. package/packages/daemon/src/command-center/plugin-routes.ts +110 -0
  80. package/packages/daemon/src/command-center/server.ts +15 -0
  81. package/packages/daemon/src/command-center/tmux-server-reader.ts +62 -0
  82. package/packages/daemon/src/command-center/tmux-servers.ts +6 -0
  83. package/packages/daemon/src/doctor.ts +118 -45
  84. package/packages/daemon/src/lib/cli-action-bridge.ts +19 -0
  85. package/packages/daemon/src/lib/cli-command.ts +16 -0
  86. package/packages/daemon/src/lib/daemon-embed.ts +59 -0
  87. package/packages/daemon/src/lib/headless-daemon.ts +1 -0
  88. package/packages/daemon/src/lib/pane-reader-files.ts +294 -0
  89. package/packages/daemon/src/lib/remote-tmux-command.ts +13 -6
  90. package/packages/daemon/src/lib/tmux-client-execution.ts +79 -7
  91. package/packages/daemon/src/lib/tmux-pane-reader.ts +144 -0
  92. package/packages/daemon/src/lib/tmux-server-features.ts +43 -0
  93. package/packages/daemon/src/lib/tmux-server-owner.ts +9 -0
  94. package/packages/daemon/src/lib/worktree.ts +16 -0
  95. package/packages/daemon/src/open-browser.ts +59 -18
  96. package/packages/daemon/src/open-reader.ts +148 -0
  97. package/packages/daemon/src/plugins/action-catalog.ts +141 -0
  98. package/packages/daemon/src/plugins/action-cli.ts +248 -0
  99. package/packages/daemon/src/plugins/api-table.ts +346 -0
  100. package/packages/daemon/src/plugins/cli.ts +630 -0
  101. package/packages/daemon/src/plugins/consent.ts +125 -0
  102. package/packages/daemon/src/plugins/daemon-plugins.ts +172 -0
  103. package/packages/daemon/src/plugins/discovery.ts +176 -0
  104. package/packages/daemon/src/plugins/examples/worktree-tasks.ts +120 -0
  105. package/packages/daemon/src/plugins/exec-sandbox.ts +264 -0
  106. package/packages/daemon/src/plugins/host/actions-prelude.ts +280 -0
  107. package/packages/daemon/src/plugins/host/entry.ts +5 -0
  108. package/packages/daemon/src/plugins/host/host-api-prelude.ts +233 -0
  109. package/packages/daemon/src/plugins/host/lua-state.ts +557 -0
  110. package/packages/daemon/src/plugins/host/main.ts +359 -0
  111. package/packages/daemon/src/plugins/host/sandbox.ts +301 -0
  112. package/packages/daemon/src/plugins/host-calls.ts +343 -0
  113. package/packages/daemon/src/plugins/manifest.ts +74 -0
  114. package/packages/daemon/src/plugins/plugin-exec.ts +326 -0
  115. package/packages/daemon/src/plugins/plugin-log.ts +63 -0
  116. package/packages/daemon/src/plugins/plugin-store.ts +80 -0
  117. package/packages/daemon/src/plugins/protocol.ts +275 -0
  118. package/packages/daemon/src/plugins/safe-files.ts +105 -0
  119. package/packages/daemon/src/plugins/supervisor.ts +954 -0
  120. package/packages/daemon/src/plugins/worktree-calls.ts +183 -0
  121. package/packages/daemon/src/restore.ts +80 -44
  122. package/packages/daemon/src/terminal/mirror/events.ts +2 -0
  123. package/packages/daemon/src/terminal/mirror/session-channel.ts +6 -1
  124. package/packages/daemon/src/terminal/pane-stream/pane-stream-websocket.ts +15 -2
  125. package/packages/daemon/src/terminal/protocol/reader-option.ts +77 -0
  126. package/packages/daemon/src/terminal/protocol/session-descriptor-discovery.ts +10 -1
  127. package/packages/daemon/src/tmux-upgrade/cli.ts +118 -0
  128. package/packages/daemon/src/tmux-upgrade/io.ts +596 -0
  129. package/packages/daemon/src/tmux-upgrade/plan.ts +353 -0
  130. package/packages/daemon/src/tmux-upgrade/run.ts +325 -0
  131. package/packages/daemon/src/tui/chrome/snapshot.ts +3 -4
  132. package/packages/daemon/src/tui/mirror/runtime/application-fleet-switcher.tsx +3 -1
  133. package/packages/daemon/src/tui/mirror/runtime/application-home-agent-navigation.ts +110 -10
  134. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +90 -6
  135. package/packages/daemon/src/tui/mirror/runtime/application-home-experience.ts +2 -0
  136. package/packages/daemon/src/tui/mirror/runtime/application-machine-agent-navigation.ts +20 -9
  137. package/packages/daemon/src/tui/mirror/runtime/application-palette-command-owner.ts +42 -2
  138. package/packages/daemon/src/tui/mirror/runtime/application-palette-preview.tsx +7 -1
  139. package/packages/daemon/src/tui/mirror/runtime/application-plugin-commands.ts +229 -0
  140. package/packages/daemon/src/tui/mirror/runtime/application-plugin-form.ts +312 -0
  141. package/packages/daemon/src/tui/mirror/runtime/application-root-v2.tsx +2 -2
  142. package/packages/daemon/src/tui/mirror/runtime/application-terminal-interaction-controller.ts +149 -128
  143. package/packages/daemon/src/tui/mirror/workspace/application-command-description.ts +44 -2
  144. package/packages/daemon/src/tui/mirror/workspace/palette-list-layout.ts +4 -0
  145. package/packages/tmux-bridge/src/runner.ts +3 -1
@@ -0,0 +1,279 @@
1
+ /**
2
+ * What a plugin's host functions do on the daemon side. The Lua side calls
3
+ * `_exec`, `_panes` and the rest (see host/host-api-prelude.ts); the host
4
+ * forwards each call here, and this answers with plain JSON.
5
+ *
6
+ * Pane, window and session calls go through the daemon's own HTTP surface
7
+ * with the owner credential: the action dispatcher for workspace actions and
8
+ * the automation API for reading and typing into panes. Plugins therefore
9
+ * pass exactly the gates a CLI or the app would.
10
+ */
11
+ import { randomUUID } from "node:crypto";
12
+ import { join } from "node:path";
13
+ import { AutomationExecuteResponseSchemaZ, AutomationPaneEndpointSchemaZ, AutomationPanesResponseSchemaZ, AutomationReserveResponseSchemaZ, } from "@tmux-ide/contracts";
14
+ import { z } from "zod";
15
+ import { PluginPrograms, runPluginExec } from "./plugin-exec.js";
16
+ import { PluginStore, pluginStorePath } from "./plugin-store.js";
17
+ import { worktreeCall, WorktreeCallError, } from "./worktree-calls.js";
18
+ import { INIT_PLUGIN_NAME, RUN_STATE_NAME } from "./protocol.js";
19
+ /** Workspace actions a plugin may dispatch (all multiplexer verbs on panes, windows and sessions). */
20
+ export const PLUGIN_WORKSPACE_ACTIONS = new Set([
21
+ "workspace.window.split",
22
+ "workspace.window.kill",
23
+ "workspace.pane.kill",
24
+ "workspace.session.kill",
25
+ "workspace.rename",
26
+ "workspace.pane.zoom.toggle",
27
+ "workspace.pane.select",
28
+ "workspace.pane.swap",
29
+ "workspace.pane.resize",
30
+ ]);
31
+ export const NOTIFY_MAX_CHARS = 200;
32
+ export class HostCallError extends Error {
33
+ }
34
+ /** The daemon's HTTP port, which programs may not connect to on any address. */
35
+ function daemonPort(endpoint) {
36
+ if (!endpoint)
37
+ return [];
38
+ try {
39
+ const port = Number(new URL(endpoint.baseUrl).port);
40
+ return Number.isInteger(port) && port > 0 ? [port] : [];
41
+ }
42
+ catch {
43
+ return [];
44
+ }
45
+ }
46
+ function fail(message) {
47
+ throw new HostCallError(message);
48
+ }
49
+ const EndpointArgZ = AutomationPaneEndpointSchemaZ;
50
+ const PaneReadArgsZ = z.tuple([EndpointArgZ]);
51
+ const PaneSendArgsZ = z.tuple([
52
+ EndpointArgZ,
53
+ z
54
+ .string()
55
+ .min(1)
56
+ .max(16 * 1024),
57
+ z.boolean(),
58
+ ]);
59
+ const ActionArgsZ = z.tuple([z.string(), z.record(z.string(), z.json())]);
60
+ const NotifyArgsZ = z.tuple([
61
+ z.string().min(1).max(10_000),
62
+ z.enum(["info", "warn", "error"]).optional(),
63
+ ]);
64
+ const StoreKeyZ = z.string().min(1).max(200);
65
+ const ActionEnvelopeZ = z.discriminatedUnion("ok", [
66
+ z.object({ ok: z.literal(true), result: z.unknown().optional() }),
67
+ z.object({ ok: z.literal(false), error: z.object({ message: z.string() }) }),
68
+ ]);
69
+ /** Parse `#{socket_path}\t#{pid}\t#{session_id}\t#{pane_current_path}`. */
70
+ export function paneContextFromTmux(pane, line) {
71
+ const [socket, pid, session, cwd] = line.replace(/\n$/u, "").split("\t");
72
+ const index = /^\$(\d+)$/u.exec(session ?? "")?.[1];
73
+ if (!socket || !pid || !/^\d+$/u.test(pid) || index === undefined || !cwd)
74
+ return null;
75
+ return { tmux: `${socket},${pid},${index}`, pane, cwd };
76
+ }
77
+ export function createHostCallHandler(deps) {
78
+ const programs = new PluginPrograms();
79
+ const request = async (path, init) => {
80
+ const endpoint = deps.endpoint();
81
+ if (!endpoint)
82
+ fail("E_UNAVAILABLE: the daemon is not ready yet");
83
+ const response = await (deps.fetch ?? fetch)(`${endpoint.baseUrl}${path}`, {
84
+ ...init,
85
+ redirect: "error",
86
+ headers: {
87
+ Authorization: `Bearer ${endpoint.ownerToken}`,
88
+ "Content-Type": "application/json",
89
+ ...init.headers,
90
+ },
91
+ });
92
+ const body = await response.json().catch(() => null);
93
+ if (!response.ok) {
94
+ const error = body && typeof body === "object" && "error" in body ? body.error : null;
95
+ const message = typeof error === "string"
96
+ ? error
97
+ : error && typeof error === "object" && "message" in error
98
+ ? String(error.message)
99
+ : error && typeof error === "object" && "code" in error
100
+ ? String(error.code)
101
+ : `HTTP ${response.status}`;
102
+ fail(`E_FAILED: ${message}`);
103
+ }
104
+ return body;
105
+ };
106
+ /** Refuse to go on for a plugin stopped (disabled, unloaded, revoked) meanwhile. */
107
+ const stillActive = (caller) => {
108
+ if (caller.active && !caller.active())
109
+ fail("E_UNAVAILABLE: the plugin was stopped before this finished");
110
+ };
111
+ const automation = async (caller, intent) => {
112
+ stillActive(caller);
113
+ const reserved = AutomationReserveResponseSchemaZ.parse(await request("/api/v1/automation/reserve", {
114
+ method: "POST",
115
+ body: JSON.stringify({ version: 1, intent, origin: "sdk" }),
116
+ }));
117
+ // A send is reserved, then executed; nothing types after a stop.
118
+ stillActive(caller);
119
+ return AutomationExecuteResponseSchemaZ.parse(await request("/api/v1/automation/execute", {
120
+ method: "POST",
121
+ body: JSON.stringify({ version: 1, intent, origin: "sdk", handle: reserved.handle }),
122
+ }));
123
+ };
124
+ const resolvePane = async (pane) => {
125
+ try {
126
+ const line = await deps.tmux([
127
+ "display-message",
128
+ "-p",
129
+ "-t",
130
+ pane,
131
+ "#{socket_path}\t#{pid}\t#{session_id}\t#{pane_current_path}",
132
+ ]);
133
+ return paneContextFromTmux(pane, line);
134
+ }
135
+ catch {
136
+ return null;
137
+ }
138
+ };
139
+ const store = (plugin) => {
140
+ if (plugin === RUN_STATE_NAME)
141
+ fail("E_UNAVAILABLE: `lua run` has no store");
142
+ return new PluginStore(pluginStorePath(deps.stateHome, plugin));
143
+ };
144
+ const methods = {
145
+ async _exec(caller, args) {
146
+ const policy = {
147
+ programs: caller.capabilities.exec,
148
+ shell: caller.capabilities.shell,
149
+ panes: caller.capabilities.panes,
150
+ };
151
+ return (deps.exec ?? runPluginExec)(args[0], {
152
+ policy,
153
+ sandbox: {
154
+ stateHome: deps.stateHome,
155
+ writable: join(deps.stateHome, "plugin-data", caller.plugin),
156
+ unreadable: deps.unreadable?.() ?? [],
157
+ tmuxSockets: caller.capabilities.panes ? [] : ((await deps.tmuxSocketDirs?.()) ?? []),
158
+ privateSockets: deps.privateSockets?.() ?? [],
159
+ daemonPorts: daemonPort(deps.endpoint()),
160
+ },
161
+ baseEnv: deps.baseEnv(),
162
+ resolvePane,
163
+ secrets: deps.secrets,
164
+ ...(deps.execMaxTimeoutMs === undefined ? {} : { maxTimeoutMs: deps.execMaxTimeoutMs }),
165
+ track: (child) => programs.track(caller.plugin, child, caller.origin),
166
+ ...(caller.active ? { stillAllowed: caller.active } : {}),
167
+ });
168
+ },
169
+ async _panes() {
170
+ const panes = AutomationPanesResponseSchemaZ.parse(await request("/api/v1/automation/panes", { method: "GET" }));
171
+ return panes.panes.map((pane) => ({
172
+ endpoint: pane.endpoint,
173
+ title: pane.title,
174
+ session: pane.sessionName,
175
+ }));
176
+ },
177
+ async _pane_read(caller, args) {
178
+ const [target] = PaneReadArgsZ.parse(args);
179
+ const result = await automation(caller, { kind: "read", target, source: null });
180
+ return result.read?.availability === "available" ? result.read.text : null;
181
+ },
182
+ async _pane_send(caller, args) {
183
+ if (!caller.capabilities.panes)
184
+ fail("E_DENIED: typing into a pane needs the manifest capability 'panes.send'");
185
+ const [target, text, enter] = PaneSendArgsZ.parse(args);
186
+ await automation(caller, { kind: "send", target, source: null, text, enter });
187
+ return true;
188
+ },
189
+ async _action(caller, args) {
190
+ const [name, input] = ActionArgsZ.parse(args);
191
+ if (!PLUGIN_WORKSPACE_ACTIONS.has(name))
192
+ fail(`E_DENIED: plugins may not run '${name}'`);
193
+ stillActive(caller);
194
+ const body = await request(`/api/v2/action/${encodeURIComponent(name)}`, {
195
+ method: "POST",
196
+ headers: { "X-Tmux-Ide-Operation-Id": randomUUID() },
197
+ body: JSON.stringify(input),
198
+ });
199
+ // The dispatcher answers 200 with an { ok: false, error } envelope for
200
+ // refusals it reaches after the gate.
201
+ const envelope = ActionEnvelopeZ.safeParse(body);
202
+ if (!envelope.success)
203
+ fail("E_FAILED: the daemon sent an unexpected answer");
204
+ if (!envelope.data.ok)
205
+ fail(`E_FAILED: ${envelope.data.error.message}`);
206
+ return envelope.data.result ?? null;
207
+ },
208
+ async _worktree(caller, args) {
209
+ if (!caller.capabilities.worktree)
210
+ fail("E_DENIED: ide.worktree needs the manifest capability 'worktree'");
211
+ if (!deps.runCli)
212
+ fail("E_UNAVAILABLE: ide.worktree is not available here");
213
+ try {
214
+ return await worktreeCall(args[0], args[1], {
215
+ tmux: deps.tmux,
216
+ runCli: deps.runCli,
217
+ ...(caller.active ? { stillActive: caller.active } : {}),
218
+ });
219
+ }
220
+ catch (error) {
221
+ if (error instanceof WorktreeCallError)
222
+ fail(error.message);
223
+ throw error;
224
+ }
225
+ },
226
+ async _notify(caller, args) {
227
+ const [text, level = "info"] = NotifyArgsZ.parse(args);
228
+ const clipped = text.replace(/\s+/gu, " ").trim().slice(0, NOTIFY_MAX_CHARS);
229
+ if (!clipped)
230
+ return false;
231
+ await deps.notify(caller.plugin, clipped, level);
232
+ return true;
233
+ },
234
+ async _store_get(caller, args) {
235
+ return store(caller.plugin).get(StoreKeyZ.parse(args[0]));
236
+ },
237
+ async _store_set(caller, args) {
238
+ store(caller.plugin).set(StoreKeyZ.parse(args[0]), args[1]);
239
+ return true;
240
+ },
241
+ async _store_keys(caller) {
242
+ return store(caller.plugin).keys();
243
+ },
244
+ };
245
+ return {
246
+ methods: Object.keys(methods),
247
+ /**
248
+ * Kill the programs `plugin` started (or every plugin's) that still run;
249
+ * with `origin`, only those started for that request.
250
+ */
251
+ stopPrograms(plugin, origin) {
252
+ return programs.kill(plugin, origin);
253
+ },
254
+ runningPrograms(plugin) {
255
+ return programs.running(plugin);
256
+ },
257
+ async handle(caller, method, args) {
258
+ const fn = Object.hasOwn(methods, method) ? methods[method] : undefined;
259
+ if (!fn)
260
+ fail(`E_INVALID: no host function '${method}'`);
261
+ try {
262
+ return await fn(caller, args);
263
+ }
264
+ catch (error) {
265
+ if (error instanceof HostCallError)
266
+ throw error;
267
+ if (error instanceof z.ZodError)
268
+ fail(`E_INVALID: bad arguments to ${method.slice(1)}`);
269
+ throw new HostCallError(error.message);
270
+ }
271
+ },
272
+ };
273
+ }
274
+ /** What init.lua and `lua run` may do: everything a plugin could be granted. */
275
+ export function ownerCapabilities(plugin) {
276
+ return plugin === INIT_PLUGIN_NAME || plugin === RUN_STATE_NAME
277
+ ? { exec: "any", shell: true, panes: true, worktree: true }
278
+ : null;
279
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * `manifest.json` in each plugin directory. JSON, so the daemon and the
3
+ * installer can read what a plugin asks for without running any Lua.
4
+ */
5
+ import { plainTextSchema } from "@tmux-ide/contracts";
6
+ import { z } from "zod";
7
+ import { PLUGIN_API_VERSION, PluginNameSchemaZ } from "./protocol.js";
8
+ const SettingSchemaZ = z
9
+ .object({
10
+ type: z.enum(["string", "integer", "number", "boolean"]),
11
+ default: z.union([z.string(), z.number(), z.boolean()]).optional(),
12
+ description: plainTextSchema(0, 500).optional(),
13
+ optional: z.boolean().optional(),
14
+ minimum: z.number().optional(),
15
+ maximum: z.number().optional(),
16
+ })
17
+ .strict();
18
+ export const PluginManifestSchemaZ = z
19
+ .object({
20
+ name: PluginNameSchemaZ,
21
+ version: z.string().regex(/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/u, "version must be semver"),
22
+ description: plainTextSchema(0, 500).optional(),
23
+ /** The Lua API versions this plugin works with: `^1.0` or `1.0`. */
24
+ api: z.string().regex(/^\^?\d+\.\d+$/u, "api must look like ^1.0"),
25
+ entry: z
26
+ .string()
27
+ .regex(/^[\w-]+(?:\/[\w-]+)*\.lua$/u, "entry must be a relative .lua path")
28
+ .default("init.lua"),
29
+ capabilities: z
30
+ .object({
31
+ exec: z
32
+ .array(z.string().regex(/^[\w.+-]{1,64}$/u))
33
+ .max(32)
34
+ .optional(),
35
+ sidebar: z.boolean().optional(),
36
+ status: z.boolean().optional(),
37
+ keys: z.boolean().optional(),
38
+ /** Run any shell command line (ide.exec with shell = true). */
39
+ shell: z.boolean().optional(),
40
+ /** Type into panes (pane:send) and run programs in one (ide.exec context). */
41
+ "panes.send": z.boolean().optional(),
42
+ /** ide.worktree: create, open and remove git worktrees and their sessions. */
43
+ worktree: z.boolean().optional(),
44
+ })
45
+ .strict()
46
+ .default({}),
47
+ settings: z.record(z.string().regex(/^[a-z_][a-z0-9_]{0,63}$/u), SettingSchemaZ).default({}),
48
+ })
49
+ .strict();
50
+ /**
51
+ * Whether this host's API version satisfies a manifest's `api` range.
52
+ * `^X.Y` and `X.Y` both mean: major X, minor at least Y.
53
+ */
54
+ export function apiSatisfies(range, hostVersion = PLUGIN_API_VERSION) {
55
+ const wanted = /^\^?(\d+)\.(\d+)$/u.exec(range);
56
+ const have = /^(\d+)\.(\d+)$/u.exec(hostVersion);
57
+ if (!wanted || !have)
58
+ return false;
59
+ return Number(wanted[1]) === Number(have[1]) && Number(have[2]) >= Number(wanted[2]);
60
+ }
61
+ /** Default setting values declared by a manifest. */
62
+ export function manifestDefaults(manifest) {
63
+ const out = {};
64
+ for (const [key, setting] of Object.entries(manifest.settings)) {
65
+ if (setting.default !== undefined)
66
+ out[key] = setting.default;
67
+ }
68
+ return out;
69
+ }
@@ -0,0 +1,261 @@
1
+ /**
2
+ * `ide.exec`: a plugin runs a program, on the daemon's side of the wire.
3
+ *
4
+ * - Only programs the plugin's manifest lists under `capabilities.exec`, and
5
+ * that the owner consented to. A bare program name, looked up on the
6
+ * daemon's own PATH (absolute entries only), never on one the plugin sets.
7
+ * - No shell unless the plugin asks for `shell = true`, which needs the
8
+ * manifest's `capabilities.shell` (shown at consent as "any command").
9
+ * - A minimal environment, never the daemon's; a plugin may add only
10
+ * locale, terminal and colour variables and its own `PLUGIN_*` ones, so it
11
+ * cannot change PATH or inject a library (DYLD_*, LD_*) or interpreter
12
+ * option (NODE_OPTIONS, PYTHONPATH, GIT_*, …).
13
+ * - With `context = "%N"` the program runs as if typed in that tmux pane
14
+ * (its cwd, TMUX and TMUX_PANE); that needs the `panes.send` capability.
15
+ * - Inside the OS sandbox (exec-sandbox.ts), with a timeout that kills the
16
+ * whole process group, capped at the callback's wall clock, and a cap on
17
+ * captured output. The daemon also kills a plugin's programs when the
18
+ * plugin fails, unloads, is disabled or loses consent.
19
+ * - Output is redacted before it goes back to Lua.
20
+ */
21
+ import { spawn as nodeSpawn } from "node:child_process";
22
+ import { existsSync, statSync } from "node:fs";
23
+ import { isAbsolute } from "node:path";
24
+ import { z } from "zod";
25
+ import { redactText } from "../lib/log-sanitize.js";
26
+ import { findOnPath, sandboxedArgv } from "./exec-sandbox.js";
27
+ import { ensureRealDirectory } from "./safe-files.js";
28
+ export const EXEC_DEFAULT_TIMEOUT_MS = 30_000;
29
+ export const EXEC_MAX_TIMEOUT_MS = 600_000;
30
+ export const EXEC_OUTPUT_CAP_BYTES = 1024 * 1024;
31
+ const PROGRAM_NAME = /^[\w.+-]{1,64}$/u;
32
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/u;
33
+ /**
34
+ * The variables a plugin may set for a program it runs. Everything else
35
+ * could change what runs (PATH, DYLD_INSERT_LIBRARIES, LD_PRELOAD,
36
+ * NODE_OPTIONS, PYTHONPATH, GIT_SSH_COMMAND, BASH_ENV, …) and is refused.
37
+ */
38
+ const ALLOWED_ENV = /^(?:LANG|LANGUAGE|LC_[A-Z]+|TZ|TERM|COLORTERM|NO_COLOR|FORCE_COLOR|CLICOLOR|CLICOLOR_FORCE|COLUMNS|LINES|PLUGIN_[A-Z0-9_]+)$/u;
39
+ export const ExecRequestSchemaZ = z
40
+ .object({
41
+ cmd: z
42
+ .string()
43
+ .min(1)
44
+ .max(64 * 1024),
45
+ args: z
46
+ .array(z.string().max(64 * 1024))
47
+ .max(256)
48
+ .default([]),
49
+ cwd: z.string().min(1).max(4096).optional(),
50
+ env: z.record(z.string().regex(ENV_NAME), z.string().max(64 * 1024)).optional(),
51
+ stdin: z
52
+ .string()
53
+ .max(1024 * 1024)
54
+ .optional(),
55
+ timeout_ms: z.number().int().min(1).max(EXEC_MAX_TIMEOUT_MS).optional(),
56
+ /** A tmux pane id like `%12`: run as if typed there. */
57
+ context: z
58
+ .string()
59
+ .regex(/^%\d{1,9}$/u, "must be a tmux pane id like %3; ctx.pane is set only when the caller knows one")
60
+ .optional(),
61
+ shell: z.boolean().optional(),
62
+ })
63
+ .strict();
64
+ export class ExecError extends Error {
65
+ }
66
+ function fail(message) {
67
+ throw new ExecError(message);
68
+ }
69
+ /** Validate the request and work out the argv, cwd and environment. */
70
+ export async function prepareExec(raw, deps) {
71
+ const parsed = ExecRequestSchemaZ.safeParse(raw);
72
+ if (!parsed.success) {
73
+ const issue = parsed.error.issues[0];
74
+ fail(`E_INVALID: ide.exec ${issue?.path.join(".") || "request"}: ${issue?.message ?? "invalid"}`);
75
+ }
76
+ const request = parsed.data;
77
+ const env = { ...deps.baseEnv };
78
+ for (const [key, value] of Object.entries(request.env ?? {})) {
79
+ if (!ALLOWED_ENV.test(key))
80
+ fail(`E_DENIED: ide.exec may not set ${key}; plugins may set LANG, LC_*, TZ, TERM, colour variables, COLUMNS, LINES and PLUGIN_*`);
81
+ env[key] = value;
82
+ }
83
+ let command;
84
+ if (request.shell) {
85
+ if (!deps.policy.shell)
86
+ fail("E_DENIED: this plugin may not run shell commands (manifest capability 'shell')");
87
+ command = ["/bin/sh", "-c", request.cmd, "sh", ...request.args];
88
+ }
89
+ else {
90
+ if (!PROGRAM_NAME.test(request.cmd))
91
+ fail("E_INVALID: ide.exec cmd must be a program name like 'git', not a path or command line");
92
+ if (deps.policy.programs !== "any" && !deps.policy.programs.includes(request.cmd))
93
+ fail(`E_DENIED: this plugin may not run '${request.cmd}' (manifest capability 'exec')`);
94
+ // The daemon's PATH, never one from the request.
95
+ const resolved = findOnPath(request.cmd, deps.baseEnv.PATH ?? "");
96
+ if (!resolved)
97
+ fail(`E_NOT_FOUND: '${request.cmd}' is not on PATH`);
98
+ command = [resolved, ...request.args];
99
+ }
100
+ // Without panes.send a program gets no hint where the tmux server is (and
101
+ // the sandbox keeps it from the socket directories anyway).
102
+ if (!deps.policy.panes)
103
+ delete env.TMUX_TMPDIR;
104
+ let cwd = env.HOME ?? "/";
105
+ if (request.context) {
106
+ if (!deps.policy.panes)
107
+ fail("E_DENIED: running a program in a pane (context) needs the manifest capability 'panes.send'");
108
+ const pane = await deps.resolvePane(request.context);
109
+ if (!pane)
110
+ fail(`E_NOT_FOUND: no tmux pane ${request.context}`);
111
+ env.TMUX = pane.tmux;
112
+ env.TMUX_PANE = pane.pane;
113
+ cwd = pane.cwd;
114
+ }
115
+ if (request.cwd !== undefined) {
116
+ if (!isAbsolute(request.cwd))
117
+ fail("E_INVALID: ide.exec cwd must be an absolute path");
118
+ cwd = request.cwd;
119
+ }
120
+ if (!existsSync(cwd) || !statSync(cwd).isDirectory())
121
+ fail(`E_NOT_FOUND: ide.exec cwd ${cwd} is not a directory`);
122
+ try {
123
+ ensureRealDirectory(deps.sandbox.writable);
124
+ }
125
+ catch (error) {
126
+ fail(`E_UNAVAILABLE: the plugin's data directory is unusable: ${error.message}`);
127
+ }
128
+ const plan = (deps.plan ?? sandboxedArgv)(command, deps.sandbox);
129
+ if (!plan.ok)
130
+ fail(`E_UNAVAILABLE: ${plan.reason}`);
131
+ return {
132
+ argv: plan.argv,
133
+ cwd,
134
+ env,
135
+ stdin: request.stdin,
136
+ timeoutMs: Math.min(request.timeout_ms ?? EXEC_DEFAULT_TIMEOUT_MS, deps.maxTimeoutMs ?? EXEC_MAX_TIMEOUT_MS),
137
+ };
138
+ }
139
+ class Capture {
140
+ #chunks = [];
141
+ #bytes = 0;
142
+ truncated = false;
143
+ add(chunk) {
144
+ const room = EXEC_OUTPUT_CAP_BYTES - this.#bytes;
145
+ if (room <= 0) {
146
+ this.truncated = true;
147
+ return;
148
+ }
149
+ const kept = chunk.length > room ? chunk.subarray(0, room) : chunk;
150
+ if (kept.length < chunk.length)
151
+ this.truncated = true;
152
+ this.#chunks.push(kept);
153
+ this.#bytes += kept.length;
154
+ }
155
+ text() {
156
+ return Buffer.concat(this.#chunks).toString("utf8");
157
+ }
158
+ }
159
+ /** Kill `child` and everything it started (it leads its own process group). */
160
+ export function killGroup(child) {
161
+ if (child.pid === undefined)
162
+ return;
163
+ try {
164
+ process.kill(-child.pid, "SIGKILL");
165
+ }
166
+ catch {
167
+ child.kill("SIGKILL");
168
+ }
169
+ }
170
+ export async function runPluginExec(raw, deps) {
171
+ const prepared = await prepareExec(raw, deps);
172
+ if (deps.stillAllowed && !deps.stillAllowed())
173
+ throw new ExecError("E_UNAVAILABLE: the plugin was stopped before its program started");
174
+ const spawn = deps.spawn ?? nodeSpawn;
175
+ const [file, ...args] = prepared.argv;
176
+ return new Promise((resolve, reject) => {
177
+ let child;
178
+ try {
179
+ child = spawn(file, args, {
180
+ cwd: prepared.cwd,
181
+ env: prepared.env,
182
+ stdio: ["pipe", "pipe", "pipe"],
183
+ // Its own process group, so a timeout kills everything it started.
184
+ detached: true,
185
+ });
186
+ }
187
+ catch (error) {
188
+ reject(new ExecError(`E_UNAVAILABLE: could not start the program: ${error.message}`));
189
+ return;
190
+ }
191
+ const forget = deps.track?.(child) ?? (() => { });
192
+ const stdout = new Capture();
193
+ const stderr = new Capture();
194
+ let timedOut = false;
195
+ const timer = setTimeout(() => {
196
+ timedOut = true;
197
+ killGroup(child);
198
+ }, prepared.timeoutMs);
199
+ child.stdout?.on("data", (chunk) => stdout.add(chunk));
200
+ child.stderr?.on("data", (chunk) => stderr.add(chunk));
201
+ child.stdin?.on("error", () => { });
202
+ child.on("error", (error) => {
203
+ clearTimeout(timer);
204
+ forget();
205
+ reject(new ExecError(`E_UNAVAILABLE: could not start the program: ${error.message}`));
206
+ });
207
+ child.on("close", (code, signal) => {
208
+ clearTimeout(timer);
209
+ forget();
210
+ const secrets = deps.secrets();
211
+ resolve({
212
+ code,
213
+ signal,
214
+ stdout: redactText(stdout.text(), secrets),
215
+ stderr: redactText(stderr.text(), secrets),
216
+ timed_out: timedOut,
217
+ truncated: stdout.truncated || stderr.truncated,
218
+ });
219
+ });
220
+ child.stdin?.end(prepared.stdin ?? "");
221
+ });
222
+ }
223
+ /** Programs plugins started and that still run, by plugin. */
224
+ export class PluginPrograms {
225
+ #byPlugin = new Map();
226
+ /**
227
+ * Remember `child` as `plugin`'s, started for request `origin` (or by a
228
+ * timer or load when there is none); returns the call that forgets it.
229
+ */
230
+ track(plugin, child, origin) {
231
+ let running = this.#byPlugin.get(plugin);
232
+ if (!running)
233
+ this.#byPlugin.set(plugin, (running = new Map()));
234
+ running.set(child, origin);
235
+ return () => {
236
+ running.delete(child);
237
+ if (running.size === 0 && this.#byPlugin.get(plugin) === running)
238
+ this.#byPlugin.delete(plugin);
239
+ };
240
+ }
241
+ /**
242
+ * Kill `plugin`'s programs, or every plugin's; with `origin`, only the ones
243
+ * started for that request. Returns how many.
244
+ */
245
+ kill(plugin, origin) {
246
+ const groups = plugin === undefined ? [...this.#byPlugin.values()] : [this.#byPlugin.get(plugin)];
247
+ let killed = 0;
248
+ for (const running of groups) {
249
+ for (const [child, started] of running ?? []) {
250
+ if (origin !== undefined && started !== origin)
251
+ continue;
252
+ killGroup(child);
253
+ killed += 1;
254
+ }
255
+ }
256
+ return killed;
257
+ }
258
+ running(plugin) {
259
+ return this.#byPlugin.get(plugin)?.size ?? 0;
260
+ }
261
+ }
@@ -0,0 +1,54 @@
1
+ /**
2
+ * `<state home>/logs/plugins.log`: one JSON line per plugin log entry, with
3
+ * the same one-generation rotation as the fleet events log.
4
+ */
5
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
7
+ export const PLUGIN_LOG_MAX_BYTES = 1024 * 1024;
8
+ export function pluginLogPath(stateHome) {
9
+ return join(stateHome, "logs", "plugins.log");
10
+ }
11
+ export function appendPluginLog(path, entry) {
12
+ try {
13
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
14
+ if (existsSync(path) && statSync(path).size > PLUGIN_LOG_MAX_BYTES) {
15
+ renameSync(path, `${path}.1`);
16
+ }
17
+ appendFileSync(path, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
18
+ }
19
+ catch {
20
+ // A lost log line is never fatal to the daemon.
21
+ }
22
+ }
23
+ /** The last `limit` entries, oldest first, optionally for one plugin. */
24
+ export function readPluginLog(path, options = {}) {
25
+ const limit = options.limit ?? 200;
26
+ const out = [];
27
+ for (const file of [`${path}.1`, path]) {
28
+ let text;
29
+ try {
30
+ text = readFileSync(file, "utf8");
31
+ }
32
+ catch {
33
+ continue;
34
+ }
35
+ for (const line of text.split("\n")) {
36
+ if (!line)
37
+ continue;
38
+ try {
39
+ const entry = JSON.parse(line);
40
+ if (!options.plugin || entry.plugin === options.plugin)
41
+ out.push(entry);
42
+ }
43
+ catch {
44
+ // Skip a torn line.
45
+ }
46
+ }
47
+ }
48
+ return out.slice(-limit);
49
+ }
50
+ export function formatPluginLogEntry(entry) {
51
+ const time = /T(\d{2}:\d{2}:\d{2})/u.exec(entry.ts)?.[1] ?? entry.ts;
52
+ const fields = entry.fields ? ` ${JSON.stringify(entry.fields)}` : "";
53
+ return `${time} ${entry.plugin} ${entry.level.padEnd(5)} ${entry.message}${fields}`;
54
+ }