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,359 @@
1
+ /**
2
+ * The plugin host process: `tmux-ide __plugin-host`.
3
+ *
4
+ * Started and supervised by the daemon (see ../supervisor.ts). Reads commands
5
+ * from stdin, writes events to file descriptor 3. Each plugin has its own Lua
6
+ * state. Loads and unloads run strictly in the order received; one-off runs
7
+ * each have their own queue.
8
+ */
9
+ import { readFileSync, statSync, writeSync } from "node:fs";
10
+ import { randomUUID } from "node:crypto";
11
+ import { createInterface } from "node:readline";
12
+ import {
13
+ DEFAULT_PLUGIN_LIMITS,
14
+ HOST_CALL_METHODS,
15
+ HostCommandSchemaZ,
16
+ MAX_PROTOCOL_LINE_BYTES,
17
+ PLUGIN_API_VERSION,
18
+ PLUGIN_HOST_PROTOCOL_VERSION,
19
+ RUN_STATE_NAME,
20
+ type HostCommand,
21
+ type HostEvent,
22
+ type PluginLimits,
23
+ type PluginLogLevel,
24
+ type PluginSpec,
25
+ } from "../protocol.ts";
26
+ import { hashPluginDirectory } from "../consent.ts";
27
+ import { MAX_SOURCE_BYTES, PluginLuaState, PluginRunError } from "./lua-state.ts";
28
+
29
+ export const HEARTBEAT_INTERVAL_MS = 1000;
30
+ const EVENT_FD = 3;
31
+ const LOAD_QUEUE = "\0loads";
32
+
33
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
34
+
35
+ /** Write one event line synchronously, so it is on the wire before Lua runs. */
36
+ export function writeEventLine(fd: number, event: HostEvent): void {
37
+ const buffer = Buffer.from(`${JSON.stringify(event)}\n`, "utf8");
38
+ let offset = 0;
39
+ let spins = 0;
40
+ while (offset < buffer.length) {
41
+ try {
42
+ offset += writeSync(fd, buffer, offset, buffer.length - offset);
43
+ } catch (error) {
44
+ const code = (error as NodeJS.ErrnoException).code;
45
+ if (code === "EAGAIN" && spins < 2000) {
46
+ spins += 1;
47
+ Atomics.wait(sleeper, 0, 0, 1);
48
+ continue;
49
+ }
50
+ if (code === "EPIPE" || code === "EBADF") process.exit(0);
51
+ throw error;
52
+ }
53
+ }
54
+ }
55
+
56
+ interface LogBudget {
57
+ windowStart: number;
58
+ count: number;
59
+ dropped: number;
60
+ }
61
+
62
+ export class PluginHost {
63
+ readonly #emit: (event: HostEvent) => void;
64
+ readonly #states = new Map<string, PluginLuaState>();
65
+ readonly #queues = new Map<string, Promise<void>>();
66
+ readonly #logBudgets = new Map<string, LogBudget>();
67
+ readonly #calls = new Map<
68
+ string,
69
+ { resolve(value: unknown): void; reject(error: Error): void }
70
+ >();
71
+ #productVersion = "0.0.0";
72
+ #limits: PluginLimits = DEFAULT_PLUGIN_LIMITS;
73
+
74
+ constructor(emit: (event: HostEvent) => void) {
75
+ this.#emit = emit;
76
+ }
77
+
78
+ /** Run `task` after every earlier task for the same plugin has settled. */
79
+ #enqueue(name: string, task: () => Promise<void>): Promise<void> {
80
+ const previous = this.#queues.get(name) ?? Promise.resolve();
81
+ const next = previous.then(task, task);
82
+ this.#queues.set(name, next);
83
+ void next.finally(() => {
84
+ if (this.#queues.get(name) === next) this.#queues.delete(name);
85
+ });
86
+ return next;
87
+ }
88
+
89
+ #log(plugin: string, level: PluginLogLevel, message: string, fields?: Record<string, unknown>) {
90
+ const now = Date.now();
91
+ let budget = this.#logBudgets.get(plugin);
92
+ if (!budget || now - budget.windowStart >= 1000) {
93
+ if (budget && budget.dropped > 0)
94
+ this.#emit({
95
+ type: "log",
96
+ plugin,
97
+ level: "warn",
98
+ message: `dropped ${budget.dropped} log lines (limit ${this.#limits.logLinesPerSecond}/s)`,
99
+ });
100
+ budget = { windowStart: now, count: 0, dropped: 0 };
101
+ this.#logBudgets.set(plugin, budget);
102
+ }
103
+ if (budget.count >= this.#limits.logLinesPerSecond) {
104
+ budget.dropped += 1;
105
+ return;
106
+ }
107
+ budget.count += 1;
108
+ this.#emit({
109
+ type: "log",
110
+ plugin,
111
+ level,
112
+ message: message.slice(0, 8192),
113
+ ...(fields ? { fields: fields as Record<string, never> } : {}),
114
+ });
115
+ }
116
+
117
+ async #createState(
118
+ spec: Pick<PluginSpec, "name" | "includeRoots" | "moduleRoots" | "settings">,
119
+ onLog?: (level: PluginLogLevel, message: string) => void,
120
+ ): Promise<PluginLuaState> {
121
+ return PluginLuaState.create({
122
+ spec,
123
+ apiVersion: PLUGIN_API_VERSION,
124
+ productVersion: this.#productVersion,
125
+ limits: this.#limits,
126
+ hostFunctions: Object.fromEntries(
127
+ HOST_CALL_METHODS.map((method) => [
128
+ method,
129
+ (args: unknown[], origin?: string) => this.#call(spec.name, method, args, origin),
130
+ ]),
131
+ ),
132
+ hooks: {
133
+ busy: () => this.#emit({ type: "busy", plugin: spec.name }),
134
+ idle: () => this.#emit({ type: "idle", plugin: spec.name }),
135
+ log: (level, message, fields) =>
136
+ onLog ? onLog(level, message) : this.#log(spec.name, level, message, fields),
137
+ trip: (kind) => this.#emit({ type: "trip", plugin: spec.name, kind }),
138
+ actions: (json) => this.#emit({ type: "actions", plugin: spec.name, actions: json }),
139
+ },
140
+ });
141
+ }
142
+
143
+ /** Ask the daemon to run a host function for `plugin`; resolves with its JSON result. */
144
+ #call(plugin: string, method: string, args: unknown[], origin?: string): Promise<unknown> {
145
+ const id = randomUUID();
146
+ return new Promise((resolve, reject) => {
147
+ this.#calls.set(id, { resolve, reject });
148
+ this.#emit({
149
+ type: "call",
150
+ id,
151
+ plugin,
152
+ method,
153
+ args: JSON.stringify(args),
154
+ ...(origin ? { origin } : {}),
155
+ });
156
+ });
157
+ }
158
+
159
+ #callResult(command: Extract<HostCommand, { type: "call-result" }>): void {
160
+ const pending = this.#calls.get(command.id);
161
+ if (!pending) return;
162
+ this.#calls.delete(command.id);
163
+ if (!command.ok) {
164
+ pending.reject(new Error(command.error ?? "E_FAILED: the host call failed"));
165
+ return;
166
+ }
167
+ try {
168
+ pending.resolve(command.value === undefined ? undefined : JSON.parse(command.value));
169
+ } catch {
170
+ pending.reject(new Error("E_FAILED: the daemon sent a malformed result"));
171
+ }
172
+ }
173
+
174
+ async #load(spec: PluginSpec): Promise<void> {
175
+ this.#unload(spec.name);
176
+ try {
177
+ if (spec.kind === "plugin") {
178
+ // Consent covers exact content. Re-hash here so a file changed after
179
+ // the daemon checked consent does not run.
180
+ if (!spec.contentHash || hashPluginDirectory(spec.includeRoots[0]!) !== spec.contentHash)
181
+ throw new Error("E_DENIED: the plugin changed since it was consented to; consent again");
182
+ }
183
+ const size = statSync(spec.entry).size;
184
+ if (size > MAX_SOURCE_BYTES) throw new Error(`E_INVALID: ${spec.entry} is larger than 1 MiB`);
185
+ const source = readFileSync(spec.entry, "utf8");
186
+ const state = await this.#createState(spec);
187
+ this.#states.set(spec.name, state);
188
+ const chunkName = spec.kind === "init" ? "@init.lua" : `@${spec.name}/init.lua`;
189
+ await state.runSource(source, chunkName, {
190
+ budgetMs: this.#limits.callbackBudgetMs,
191
+ wallClockMs: this.#limits.wallClockMs,
192
+ });
193
+ this.#emit({ type: "loaded", plugin: spec.name, ok: true, memoryBytes: state.memoryUsed() });
194
+ } catch (error) {
195
+ const message = error instanceof Error ? error.message : String(error);
196
+ this.#log(spec.name, "error", `load failed: ${message}`);
197
+ // A plugin that failed to load keeps nothing: no state, no actions.
198
+ this.#unload(spec.name);
199
+ this.#emit({ type: "loaded", plugin: spec.name, ok: false, error: message.slice(0, 4096) });
200
+ }
201
+ }
202
+
203
+ #unload(name: string): void {
204
+ const state = this.#states.get(name);
205
+ if (!state) return;
206
+ this.#states.delete(name);
207
+ state.close();
208
+ // Its actions went with it.
209
+ this.#emit({ type: "actions", plugin: name, actions: "[]" });
210
+ }
211
+
212
+ #callbackLimits() {
213
+ return { budgetMs: this.#limits.callbackBudgetMs, wallClockMs: this.#limits.wallClockMs };
214
+ }
215
+
216
+ async #invoke(command: Extract<HostCommand, { type: "invoke" }>): Promise<void> {
217
+ const state = this.#states.get(command.plugin);
218
+ try {
219
+ if (!state) throw new Error(`E_NOT_FOUND: plugin '${command.plugin}' is not loaded`);
220
+ const value = await state.invokeAction(command.action, command.args, command.context, {
221
+ ...this.#callbackLimits(),
222
+ origin: command.id,
223
+ });
224
+ this.#emit({ type: "invoke-result", id: command.id, ok: true, value });
225
+ } catch (error) {
226
+ const message = error instanceof Error ? error.message : String(error);
227
+ this.#log(command.plugin, "error", `action ${command.action} failed: ${message}`);
228
+ this.#emit({
229
+ type: "invoke-result",
230
+ id: command.id,
231
+ ok: false,
232
+ error: message.slice(0, 8192),
233
+ });
234
+ }
235
+ }
236
+
237
+ async #paramOptions(command: Extract<HostCommand, { type: "param-options" }>): Promise<void> {
238
+ const state = this.#states.get(command.plugin);
239
+ try {
240
+ if (!state) throw new Error(`E_NOT_FOUND: plugin '${command.plugin}' is not loaded`);
241
+ const options = await state.paramOptions(command.action, command.param, command.context, {
242
+ ...this.#callbackLimits(),
243
+ origin: command.id,
244
+ });
245
+ this.#emit({ type: "param-options-result", id: command.id, ok: true, options });
246
+ } catch (error) {
247
+ const message = error instanceof Error ? error.message : String(error);
248
+ this.#emit({
249
+ type: "param-options-result",
250
+ id: command.id,
251
+ ok: false,
252
+ error: message.slice(0, 8192),
253
+ });
254
+ }
255
+ }
256
+
257
+ async #run(command: Extract<HostCommand, { type: "run" }>): Promise<void> {
258
+ const logs: { level: PluginLogLevel; message: string }[] = [];
259
+ let state: PluginLuaState | null = null;
260
+ try {
261
+ state = await this.#createState(
262
+ { name: RUN_STATE_NAME, includeRoots: [], moduleRoots: [], settings: {} },
263
+ (level, message) => {
264
+ if (logs.length < 1000) logs.push({ level, message: message.slice(0, 8192) });
265
+ },
266
+ );
267
+ const values = await state.runSource(command.code, command.chunkName, {
268
+ budgetMs: command.budgetMs,
269
+ wallClockMs: Math.max(this.#limits.wallClockMs, command.budgetMs * 2),
270
+ });
271
+ this.#emit({ type: "run-result", id: command.id, ok: true, values, logs });
272
+ } catch (error) {
273
+ const message =
274
+ error instanceof PluginRunError || error instanceof Error ? error.message : String(error);
275
+ this.#emit({
276
+ type: "run-result",
277
+ id: command.id,
278
+ ok: false,
279
+ error: message.slice(0, 8192),
280
+ logs,
281
+ });
282
+ } finally {
283
+ state?.close();
284
+ }
285
+ }
286
+
287
+ handle(command: HostCommand): Promise<void> | void {
288
+ switch (command.type) {
289
+ case "configure":
290
+ this.#productVersion = command.productVersion;
291
+ this.#limits = command.limits;
292
+ return;
293
+ // Loads and unloads share one queue: plugins load in the order the
294
+ // daemon sends them, so init.lua always runs after every plugin.
295
+ case "load":
296
+ return this.#enqueue(LOAD_QUEUE, () => this.#load(command.plugin));
297
+ case "unload":
298
+ return this.#enqueue(LOAD_QUEUE, async () => this.#unload(command.name));
299
+ case "run":
300
+ return this.#enqueue(`run:${command.id}`, () => this.#run(command));
301
+ // Callbacks of one plugin run in order; different plugins interleave.
302
+ case "invoke":
303
+ return this.#enqueue(`plugin:${command.plugin}`, () => this.#invoke(command));
304
+ case "param-options":
305
+ return this.#enqueue(`plugin:${command.plugin}`, () => this.#paramOptions(command));
306
+ case "call-result":
307
+ this.#callResult(command);
308
+ return;
309
+ case "shutdown":
310
+ this.shutdown();
311
+ return;
312
+ }
313
+ }
314
+
315
+ loadedPlugins(): string[] {
316
+ return [...this.#states.keys()];
317
+ }
318
+
319
+ shutdown(): void {
320
+ for (const name of [...this.#states.keys()]) this.#unload(name);
321
+ }
322
+ }
323
+
324
+ /** Entry point for `tmux-ide __plugin-host`. */
325
+ export async function runPluginHost(): Promise<void> {
326
+ const emit = (event: HostEvent) => writeEventLine(EVENT_FD, event);
327
+ const host = new PluginHost(emit);
328
+ emit({ type: "hello", protocolVersion: PLUGIN_HOST_PROTOCOL_VERSION, pid: process.pid });
329
+ let seq = 0;
330
+ const heartbeat = setInterval(
331
+ () => emit({ type: "heartbeat", seq: ++seq }),
332
+ HEARTBEAT_INTERVAL_MS,
333
+ );
334
+
335
+ const lines = createInterface({ input: process.stdin, crlfDelay: Infinity });
336
+ const finish = () => {
337
+ clearInterval(heartbeat);
338
+ host.shutdown();
339
+ process.exit(0);
340
+ };
341
+ lines.on("line", (line) => {
342
+ if (line.length === 0 || line.length > MAX_PROTOCOL_LINE_BYTES) return;
343
+ let raw: unknown;
344
+ try {
345
+ raw = JSON.parse(line);
346
+ } catch {
347
+ return;
348
+ }
349
+ const parsed = HostCommandSchemaZ.safeParse(raw);
350
+ if (!parsed.success) return;
351
+ if (parsed.data.type === "shutdown") {
352
+ finish();
353
+ return;
354
+ }
355
+ void host.handle(parsed.data);
356
+ });
357
+ // The daemon closed our stdin: it is gone or done with us.
358
+ lines.on("close", finish);
359
+ }
@@ -0,0 +1,301 @@
1
+ /**
2
+ * The Lua prelude every plugin state runs before any plugin code.
3
+ *
4
+ * Plugin code never sees the real globals. It runs in `env`, a table built
5
+ * from an allow-list, so nothing outside the list (io, os.execute, debug,
6
+ * package, dofile, loadfile, string.dump) is reachable. The real globals keep
7
+ * one table, `__ide_internal`, which the host's runner threads call into.
8
+ *
9
+ * Deadlines: every runner thread, and every coroutine plugin code creates,
10
+ * gets a count hook that asks the host whether the current callback's budget
11
+ * is spent and, if so, raises `E_TIMEOUT`. `pcall` can catch that error, so
12
+ * the hook keeps raising it on every check until the callback returns; a
13
+ * plugin that catches it in a loop forever is stopped by the host watchdog.
14
+ *
15
+ * Host functions the prelude expects as globals (removed once captured):
16
+ * __ide_over() → boolean, true once the budget is spent
17
+ * __ide_log(level, message, json?) → nil
18
+ * __ide_resolve(kind, name) → source, display path | nil, error
19
+ * __ide_info → { api, version, plugin, settings_json }
20
+ */
21
+ export const HOOK_INSTRUCTION_COUNT = 10_000;
22
+
23
+ export const TIMEOUT_MESSAGE = "E_TIMEOUT: the callback ran past its time budget";
24
+
25
+ export const SANDBOX_PRELUDE = String.raw`
26
+ local sethook = debug.sethook
27
+ local raw_load, raw_pcall, raw_error = load, pcall, error
28
+ local raw_type, raw_tostring, raw_select = type, tostring, select
29
+ local raw_pairs, raw_ipairs, raw_next = pairs, ipairs, next
30
+ local raw_setmetatable, raw_getmetatable = setmetatable, getmetatable
31
+ local raw_rawget, raw_rawset, raw_rawequal, raw_rawlen = rawget, rawset, rawequal, rawlen
32
+ local co_create, co_wrap = coroutine.create, coroutine.wrap
33
+ local s_format, s_byte, s_char, s_gsub, s_match, s_rep, s_sub =
34
+ string.format, string.byte, string.char, string.gsub, string.match, string.rep, string.sub
35
+ local t_concat, t_insert, t_sort = table.concat, table.insert, table.sort
36
+ local m_floor, m_huge, m_type = math.floor, math.huge, math.type
37
+
38
+ local co_running, co_yield = coroutine.running, coroutine.yield
39
+ local over = __ide_over
40
+ local host_log = __ide_log
41
+ local host_resolve = __ide_resolve
42
+ local host_begin = __ide_begin
43
+ local info = __ide_info
44
+ __ide_over, __ide_log, __ide_resolve, __ide_begin, __ide_info = nil, nil, nil, nil, nil
45
+
46
+ -- Runner threads the host started. Host calls yield to the host, so they
47
+ -- are only allowed directly on a runner, never inside a plugin coroutine.
48
+ local runners = raw_setmetatable({}, { __mode = "k" })
49
+
50
+ local HOOK_COUNT = ${HOOK_INSTRUCTION_COUNT}
51
+ local TIMEOUT = "${TIMEOUT_MESSAGE}"
52
+
53
+ local function hook()
54
+ if over() then raw_error(TIMEOUT, 0) end
55
+ end
56
+ local function arm() sethook(hook, "", HOOK_COUNT) end
57
+
58
+ -- The string metatable's __index is the real string table. Hide the
59
+ -- metatable itself so plugins cannot reach or change it.
60
+ raw_getmetatable("").__metatable = false
61
+ -- ("").dump reaches the real string table: remove dump there too.
62
+ string.dump = nil
63
+
64
+ ----------------------------------------------------------------- JSON encode
65
+
66
+ local function is_array(t)
67
+ local n = 0
68
+ for k in raw_pairs(t) do
69
+ if m_type(k) ~= "integer" or k < 1 then return false end
70
+ if k > n then n = k end
71
+ end
72
+ return true, n
73
+ end
74
+
75
+ local escapes = { ['"'] = '\\"', ['\\'] = '\\\\', ['\b'] = '\\b', ['\f'] = '\\f',
76
+ ['\n'] = '\\n', ['\r'] = '\\r', ['\t'] = '\\t' }
77
+ local function quote(s)
78
+ return '"' .. s_gsub(s, '[%c"\\]', function(c)
79
+ return escapes[c] or s_format("\\u%04x", s_byte(c))
80
+ end) .. '"'
81
+ end
82
+
83
+ local function encode(v, depth, seen)
84
+ local tv = raw_type(v)
85
+ if v == nil then return "null"
86
+ elseif tv == "boolean" then return v and "true" or "false"
87
+ elseif tv == "number" then
88
+ if v ~= v or v == m_huge or v == -m_huge then return "null" end
89
+ if m_type(v) == "integer" then return s_format("%d", v) end
90
+ return s_format("%.17g", v)
91
+ elseif tv == "string" then return quote(v)
92
+ elseif tv == "table" then
93
+ if seen[v] then raw_error("E_INVALID: cannot encode a table that contains itself", 0) end
94
+ if depth > 64 then raw_error("E_INVALID: table nested deeper than 64 levels", 0) end
95
+ seen[v] = true
96
+ local out = {}
97
+ local array, n = is_array(v)
98
+ if array and (n > 0 or raw_next(v) == nil) then
99
+ for i = 1, n do out[i] = encode(v[i], depth + 1, seen) end
100
+ seen[v] = nil
101
+ return "[" .. t_concat(out, ",") .. "]"
102
+ end
103
+ local keys = {}
104
+ for k in raw_pairs(v) do
105
+ local tk = raw_type(k)
106
+ if tk ~= "string" and tk ~= "number" then
107
+ raw_error("E_INVALID: object keys must be strings or numbers", 0)
108
+ end
109
+ keys[#keys + 1] = k
110
+ end
111
+ t_sort(keys, function(a, b) return raw_tostring(a) < raw_tostring(b) end)
112
+ for i, k in raw_ipairs(keys) do
113
+ out[i] = quote(raw_tostring(k)) .. ":" .. encode(v[k], depth + 1, seen)
114
+ end
115
+ seen[v] = nil
116
+ return "{" .. t_concat(out, ",") .. "}"
117
+ else
118
+ return quote("<" .. tv .. ">")
119
+ end
120
+ end
121
+ local function json_encode(v) return encode(v, 0, {}) end
122
+
123
+ ------------------------------------------------------------- plugin globals
124
+
125
+ local env = {}
126
+
127
+ local function copy(t, except)
128
+ local out = {}
129
+ for k, v in raw_pairs(t) do
130
+ if not (except and except[k]) then out[k] = v end
131
+ end
132
+ return out
133
+ end
134
+
135
+ for _, name in raw_ipairs({
136
+ "assert", "error", "ipairs", "next", "pairs", "pcall", "rawequal", "rawget",
137
+ "rawlen", "rawset", "select", "setmetatable", "getmetatable", "tonumber",
138
+ "tostring", "type", "xpcall", "_VERSION",
139
+ }) do env[name] = _G[name] end
140
+
141
+ env.string = copy(string, { dump = true })
142
+ env.table = copy(table)
143
+ env.math = copy(math)
144
+ env.utf8 = copy(utf8)
145
+ env.os = { time = os.time, clock = os.clock, date = os.date }
146
+
147
+ local coroutine_api = copy(coroutine)
148
+ coroutine_api.create = function(fn)
149
+ if raw_type(fn) ~= "function" then raw_error("bad argument #1 to 'create' (function expected)", 2) end
150
+ return co_create(function(...) arm() return fn(...) end)
151
+ end
152
+ coroutine_api.wrap = function(fn)
153
+ if raw_type(fn) ~= "function" then raw_error("bad argument #1 to 'wrap' (function expected)", 2) end
154
+ return co_wrap(function(...) arm() return fn(...) end)
155
+ end
156
+ env.coroutine = coroutine_api
157
+
158
+ env.collectgarbage = function(opt)
159
+ if opt == nil or opt == "collect" or opt == "count" or opt == "step" then
160
+ return collectgarbage(opt)
161
+ end
162
+ raw_error("collectgarbage: only 'collect', 'count' and 'step' are allowed", 2)
163
+ end
164
+
165
+ env.load = function(chunk, name, mode, chunk_env)
166
+ if raw_type(chunk) ~= "string" then return nil, "load accepts source text only" end
167
+ if mode ~= nil and mode ~= "t" then return nil, "load accepts source text only" end
168
+ return raw_load(chunk, name, "t", chunk_env or env)
169
+ end
170
+
171
+ ----------------------------------------------------------------- ide table
172
+
173
+ local function stringify_args(...)
174
+ local n = raw_select("#", ...)
175
+ local parts = {}
176
+ for i = 1, n do parts[i] = raw_tostring((raw_select(i, ...))) end
177
+ return t_concat(parts, "\t")
178
+ end
179
+
180
+ local function make_logger(level)
181
+ return function(message, fields)
182
+ local fields_json = nil
183
+ if fields ~= nil then
184
+ if raw_type(fields) ~= "table" then raw_error("E_INVALID: log fields must be a table", 2) end
185
+ fields_json = json_encode(fields)
186
+ end
187
+ host_log(level, raw_tostring(message), fields_json)
188
+ end
189
+ end
190
+
191
+ local features = { log = true, include = true, require = true }
192
+
193
+ local ide = {
194
+ api = info.api,
195
+ version = info.version,
196
+ plugin = { name = info.plugin },
197
+ settings = info.settings or {},
198
+ log = {
199
+ debug = make_logger("debug"),
200
+ info = make_logger("info"),
201
+ warn = make_logger("warn"),
202
+ error = make_logger("error"),
203
+ },
204
+ }
205
+ ide.has = function(feature) return features[feature] == true end
206
+
207
+ local function host_function(name)
208
+ return function(...)
209
+ if not runners[co_running()] then
210
+ raw_error("E_INVALID: ide." .. name .. " cannot be called inside a coroutine", 2)
211
+ end
212
+ host_begin(name, json_encode({ ... }))
213
+ local ok, value = co_yield()
214
+ if not ok then raw_error(value, 2) end
215
+ return value
216
+ end
217
+ end
218
+
219
+ local host = {}
220
+ for _, name in raw_ipairs(info.host_functions or {}) do
221
+ if s_sub(name, 1, 1) == "_" then
222
+ -- Names starting with "_" are for the preludes only (__ide_internal.host).
223
+ host[name] = host_function(name)
224
+ else
225
+ local target = ide
226
+ local parts = {}
227
+ for part in string.gmatch(name, "[^.]+") do parts[#parts + 1] = part end
228
+ for i = 1, #parts - 1 do
229
+ target[parts[i]] = target[parts[i]] or {}
230
+ target = target[parts[i]]
231
+ end
232
+ target[parts[#parts]] = host_function(name)
233
+ end
234
+ end
235
+
236
+ env.print = function(...) host_log("info", stringify_args(...), nil) end
237
+
238
+ local function run_source(kind, name, ...)
239
+ local source, path = host_resolve(kind, name)
240
+ if source == nil then raw_error(path, 0) end
241
+ local fn, err = raw_load(source, "@" .. path, "t", env)
242
+ if not fn then raw_error(err, 0) end
243
+ return fn(...)
244
+ end
245
+
246
+ ide.include = function(file)
247
+ if raw_type(file) ~= "string" then raw_error("E_INVALID: ide.include expects a file name", 2) end
248
+ return run_source("file", file)
249
+ end
250
+
251
+ local loaded = {}
252
+ local loading = {}
253
+ env.require = function(name)
254
+ if raw_type(name) ~= "string" or not s_match(name, "^[%w_][%w_%-]*[%.%w_%-]*$") then
255
+ raw_error("E_INVALID: bad module name", 2)
256
+ end
257
+ local value = loaded[name]
258
+ if value ~= nil then return value end
259
+ if loading[name] then raw_error("E_INVALID: module '" .. name .. "' requires itself", 2) end
260
+ loading[name] = true
261
+ local ok, result = raw_pcall(run_source, "module", name, name)
262
+ loading[name] = nil
263
+ if not ok then raw_error(result, 0) end
264
+ if result == nil then result = true end
265
+ loaded[name] = result
266
+ return result
267
+ end
268
+
269
+ env.ide = ide
270
+ env._G = env
271
+
272
+ ------------------------------------------------------------- host runners
273
+
274
+ local function pack_results(...)
275
+ local n = raw_select("#", ...)
276
+ local out = {}
277
+ for i = 1, n do out[i] = (raw_select(i, ...)) end
278
+ local parts = {}
279
+ for i = 1, n do parts[i] = encode(out[i], 0, {}) end
280
+ return "[" .. t_concat(parts, ",") .. "]"
281
+ end
282
+
283
+ __ide_internal = {
284
+ -- Run source text as plugin code. Returns the results as JSON text.
285
+ run_source = function(source, chunk_name)
286
+ runners[co_running()] = true
287
+ arm()
288
+ local fn, err = raw_load(source, chunk_name, "t", env)
289
+ if not fn then raw_error(err, 0) end
290
+ return pack_results(fn())
291
+ end,
292
+ json_encode = json_encode,
293
+ -- For the preludes that run after this one (see actions-prelude.ts).
294
+ arm = arm,
295
+ runners = runners,
296
+ ide = ide,
297
+ features = features,
298
+ host = host,
299
+ env = env,
300
+ }
301
+ `;