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