tmux-ide 2.9.18 → 2.9.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/bin/cli.js +14703 -3882
  2. package/package.json +3 -2
  3. package/packages/contracts/src/command-catalog.ts +116 -0
  4. package/packages/contracts/src/commands.ts +5 -4
  5. package/packages/contracts/src/daemon-events.ts +2 -1
  6. package/packages/contracts/src/index.ts +2 -0
  7. package/packages/contracts/src/plain-text.ts +61 -0
  8. package/packages/daemon/dist/command-center/command-catalog-routes.js +78 -0
  9. package/packages/daemon/dist/command-center/plugin-routes.js +84 -0
  10. package/packages/daemon/dist/command-center/server.js +13 -0
  11. package/packages/daemon/dist/doctor.js +12 -5
  12. package/packages/daemon/dist/lib/cli-action-bridge.js +15 -0
  13. package/packages/daemon/dist/lib/daemon-embed.js +24 -1
  14. package/packages/daemon/dist/lib/headless-daemon.js +1 -0
  15. package/packages/daemon/dist/lib/native-split-capability.js +13 -15
  16. package/packages/daemon/dist/lib/worktree.js +18 -0
  17. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Info.plist +2 -2
  18. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/MacOS/tmux-ide-notifier +0 -0
  19. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/Resources/Assets.car +0 -0
  20. package/packages/daemon/dist/native/TmuxIdeNotifier.app/Contents/_CodeSignature/CodeResources +2 -2
  21. package/packages/daemon/dist/plugins/action-catalog.js +129 -0
  22. package/packages/daemon/dist/plugins/action-cli.js +212 -0
  23. package/packages/daemon/dist/plugins/api-table.js +303 -0
  24. package/packages/daemon/dist/plugins/cli.js +556 -0
  25. package/packages/daemon/dist/plugins/consent.js +107 -0
  26. package/packages/daemon/dist/plugins/daemon-plugins.js +132 -0
  27. package/packages/daemon/dist/plugins/discovery.js +142 -0
  28. package/packages/daemon/dist/plugins/examples/worktree-tasks.js +115 -0
  29. package/packages/daemon/dist/plugins/exec-sandbox.js +202 -0
  30. package/packages/daemon/dist/plugins/host/actions-prelude.js +279 -0
  31. package/packages/daemon/dist/plugins/host/entry.js +4 -0
  32. package/packages/daemon/dist/plugins/host/host-api-prelude.js +232 -0
  33. package/packages/daemon/dist/plugins/host/lua-state.js +493 -0
  34. package/packages/daemon/dist/plugins/host/main.js +322 -0
  35. package/packages/daemon/dist/plugins/host/sandbox.js +299 -0
  36. package/packages/daemon/dist/plugins/host-calls.js +279 -0
  37. package/packages/daemon/dist/plugins/manifest.js +69 -0
  38. package/packages/daemon/dist/plugins/plugin-exec.js +261 -0
  39. package/packages/daemon/dist/plugins/plugin-log.js +54 -0
  40. package/packages/daemon/dist/plugins/plugin-store.js +74 -0
  41. package/packages/daemon/dist/plugins/protocol.js +252 -0
  42. package/packages/daemon/dist/plugins/safe-files.js +97 -0
  43. package/packages/daemon/dist/plugins/supervisor.js +790 -0
  44. package/packages/daemon/dist/plugins/worktree-calls.js +154 -0
  45. package/packages/daemon/dist/terminal/mirror/session-channel.js +3 -2
  46. package/packages/daemon/dist/terminal/mirror/window-split-authority.js +1 -1
  47. package/packages/daemon/dist/tui/mirror/runtime/application-home-agents-owner.js +27 -0
  48. package/packages/daemon/dist/tui/mirror/runtime/application-home-experience.js +2 -0
  49. package/packages/daemon/dist/tui/mirror/runtime/application-palette-command-owner.js +30 -2
  50. package/packages/daemon/dist/tui/mirror/runtime/application-plugin-commands.js +152 -0
  51. package/packages/daemon/dist/tui/mirror/runtime/application-plugin-form.js +251 -0
  52. package/packages/daemon/dist/tui/mirror/workspace/application-command-description.js +14 -0
  53. package/packages/daemon/dist/tui/mirror/workspace/palette-list-layout.js +5 -0
  54. package/packages/daemon/src/command-center/command-catalog-routes.ts +116 -0
  55. package/packages/daemon/src/command-center/plugin-routes.ts +110 -0
  56. package/packages/daemon/src/command-center/server.ts +15 -0
  57. package/packages/daemon/src/doctor.ts +12 -5
  58. package/packages/daemon/src/lib/cli-action-bridge.ts +19 -0
  59. package/packages/daemon/src/lib/daemon-embed.ts +42 -0
  60. package/packages/daemon/src/lib/headless-daemon.ts +1 -0
  61. package/packages/daemon/src/lib/native-split-capability.ts +12 -13
  62. package/packages/daemon/src/lib/worktree.ts +16 -0
  63. package/packages/daemon/src/plugins/action-catalog.ts +141 -0
  64. package/packages/daemon/src/plugins/action-cli.ts +248 -0
  65. package/packages/daemon/src/plugins/api-table.ts +346 -0
  66. package/packages/daemon/src/plugins/cli.ts +630 -0
  67. package/packages/daemon/src/plugins/consent.ts +125 -0
  68. package/packages/daemon/src/plugins/daemon-plugins.ts +182 -0
  69. package/packages/daemon/src/plugins/discovery.ts +176 -0
  70. package/packages/daemon/src/plugins/examples/worktree-tasks.ts +120 -0
  71. package/packages/daemon/src/plugins/exec-sandbox.ts +264 -0
  72. package/packages/daemon/src/plugins/host/actions-prelude.ts +280 -0
  73. package/packages/daemon/src/plugins/host/entry.ts +5 -0
  74. package/packages/daemon/src/plugins/host/host-api-prelude.ts +233 -0
  75. package/packages/daemon/src/plugins/host/lua-state.ts +557 -0
  76. package/packages/daemon/src/plugins/host/main.ts +359 -0
  77. package/packages/daemon/src/plugins/host/sandbox.ts +301 -0
  78. package/packages/daemon/src/plugins/host-calls.ts +343 -0
  79. package/packages/daemon/src/plugins/manifest.ts +74 -0
  80. package/packages/daemon/src/plugins/plugin-exec.ts +326 -0
  81. package/packages/daemon/src/plugins/plugin-log.ts +63 -0
  82. package/packages/daemon/src/plugins/plugin-store.ts +80 -0
  83. package/packages/daemon/src/plugins/protocol.ts +275 -0
  84. package/packages/daemon/src/plugins/safe-files.ts +105 -0
  85. package/packages/daemon/src/plugins/supervisor.ts +954 -0
  86. package/packages/daemon/src/plugins/worktree-calls.ts +183 -0
  87. package/packages/daemon/src/terminal/mirror/session-channel.ts +3 -2
  88. package/packages/daemon/src/terminal/mirror/window-split-authority.ts +3 -2
  89. package/packages/daemon/src/tui/mirror/runtime/application-fleet-switcher.tsx +3 -1
  90. package/packages/daemon/src/tui/mirror/runtime/application-home-agents-owner.ts +32 -0
  91. package/packages/daemon/src/tui/mirror/runtime/application-home-experience.ts +2 -0
  92. package/packages/daemon/src/tui/mirror/runtime/application-palette-command-owner.ts +42 -2
  93. package/packages/daemon/src/tui/mirror/runtime/application-palette-preview.tsx +7 -1
  94. package/packages/daemon/src/tui/mirror/runtime/application-plugin-commands.ts +229 -0
  95. package/packages/daemon/src/tui/mirror/runtime/application-plugin-form.ts +312 -0
  96. package/packages/daemon/src/tui/mirror/workspace/application-command-description.ts +44 -2
  97. package/packages/daemon/src/tui/mirror/workspace/palette-list-layout.ts +4 -0
@@ -0,0 +1,557 @@
1
+ /**
2
+ * One plugin's Lua state.
3
+ *
4
+ * Every state gets its own wasmoon factory, so its own WebAssembly module and
5
+ * memory. Engines from one factory share a module, and a fatal abort in one
6
+ * would leave the others in an unknown state.
7
+ *
8
+ * Code runs on runner threads driven by {@link PluginLuaState.runThread}, not
9
+ * wasmoon's own `run`: the budget is spent only while Lua runs, so a callback
10
+ * that awaits the host for a second has not used a second of its budget.
11
+ */
12
+ import { readFileSync, realpathSync, statSync } from "node:fs";
13
+ import { isAbsolute, join, normalize, relative, sep } from "node:path";
14
+ import { LuaFactory, LuaMultiReturn, LuaReturn, LUA_REGISTRYINDEX, type LuaEngine } from "wasmoon";
15
+ import type { PluginLimits, PluginLogLevel, PluginSpec, PluginTripKind } from "../protocol.ts";
16
+ import { ACTIONS_PRELUDE } from "./actions-prelude.ts";
17
+ import { HOST_API_PRELUDE } from "./host-api-prelude.ts";
18
+ import { SANDBOX_PRELUDE, TIMEOUT_MESSAGE } from "./sandbox.ts";
19
+
20
+ /** Largest file `ide.include` or `require` will read. */
21
+ export const MAX_SOURCE_BYTES = 1024 * 1024;
22
+
23
+ export interface PluginStateHooks {
24
+ /** A Lua slice is about to run synchronously (sent before it starts). */
25
+ busy(): void;
26
+ idle(): void;
27
+ log(level: PluginLogLevel, message: string, fields?: Record<string, unknown>): void;
28
+ trip(kind: PluginTripKind): void;
29
+ /** The plugin's action list changed; `json` is its plain descriptor list. */
30
+ actions?(json: string): void;
31
+ }
32
+
33
+ export class PluginRunError extends Error {
34
+ readonly trip: PluginTripKind | null;
35
+ constructor(message: string, trip: PluginTripKind | null) {
36
+ super(message);
37
+ this.name = "PluginRunError";
38
+ this.trip = trip;
39
+ }
40
+ }
41
+
42
+ function isInside(child: string, parent: string): boolean {
43
+ const rel = relative(parent, child);
44
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
45
+ }
46
+
47
+ /**
48
+ * Resolve a file name or module name to a readable file inside one of `roots`.
49
+ * Refuses absolute names, `..` segments, and symlinks that lead outside a root.
50
+ */
51
+ export function resolveSource(
52
+ kind: "file" | "module",
53
+ name: string,
54
+ roots: readonly string[],
55
+ ): { ok: true; source: string; display: string } | { ok: false; error: string } {
56
+ let candidates: string[];
57
+ if (kind === "module") {
58
+ if (!/^[\w-]+(?:\.[\w-]+)*$/u.test(name))
59
+ return { ok: false, error: `E_INVALID: bad module name '${name}'` };
60
+ const base = name.split(".").join("/");
61
+ candidates = [`${base}.lua`, `${base}/init.lua`];
62
+ } else {
63
+ if (isAbsolute(name) || name.includes("\0"))
64
+ return { ok: false, error: `E_INVALID: '${name}' must be a relative path` };
65
+ const normalized = normalize(name);
66
+ if (normalized.split(/[\\/]/u).includes(".."))
67
+ return { ok: false, error: `E_INVALID: '${name}' may not leave its directory` };
68
+ if (!normalized.endsWith(".lua"))
69
+ return { ok: false, error: `E_INVALID: '${name}' is not a .lua file` };
70
+ candidates = [normalized];
71
+ }
72
+ for (const root of roots) {
73
+ let realRoot: string;
74
+ try {
75
+ realRoot = realpathSync(root);
76
+ } catch {
77
+ continue;
78
+ }
79
+ for (const candidate of candidates) {
80
+ const path = join(root, candidate);
81
+ let real: string;
82
+ try {
83
+ real = realpathSync(path);
84
+ } catch {
85
+ continue;
86
+ }
87
+ if (!isInside(real, realRoot))
88
+ return { ok: false, error: `E_DENIED: '${name}' resolves outside ${root}` };
89
+ const stat = statSync(real);
90
+ if (!stat.isFile()) continue;
91
+ if (stat.size > MAX_SOURCE_BYTES)
92
+ return { ok: false, error: `E_INVALID: '${name}' is larger than 1 MiB` };
93
+ const display = relative(root, path).split(sep).join("/");
94
+ return { ok: true, source: readFileSync(real, "utf8"), display };
95
+ }
96
+ }
97
+ return {
98
+ ok: false,
99
+ error:
100
+ kind === "module"
101
+ ? `E_NOT_FOUND: module '${name}' not found`
102
+ : `E_NOT_FOUND: '${name}' not found`,
103
+ };
104
+ }
105
+
106
+ /** The least time between two timer callbacks of one plugin. */
107
+ export const TIMER_GAP_MS = 10;
108
+
109
+ export const WALL_CLOCK_MESSAGE = "E_TIMEOUT: the callback took longer than its wall-clock limit";
110
+ export const FOREIGN_YIELD_MESSAGE =
111
+ "E_INVALID: a callback may only yield to wait for the host; it yielded something else";
112
+
113
+ /** Host functions a state exposes as `ide.<name>`: each returns a promise Lua waits on. */
114
+ /** `origin` names the request whose callback made the call, when there is one. */
115
+ export type HostFunctions = Readonly<
116
+ Record<string, (args: unknown[], origin?: string) => Promise<unknown>>
117
+ >;
118
+
119
+ /** Limits for one callback, and the request it answers (an invoke or param-options id). */
120
+ export interface CallbackLimits {
121
+ readonly budgetMs: number;
122
+ readonly wallClockMs: number;
123
+ readonly origin?: string;
124
+ }
125
+
126
+ interface Runner {
127
+ /** The host call this runner yielded to wait for, if any. */
128
+ pending: Promise<unknown> | null;
129
+ /** The request this callback answers, passed along with its host calls. */
130
+ origin?: string;
131
+ /** The budget ran out at least once, even if the plugin caught E_TIMEOUT. */
132
+ overran: boolean;
133
+ }
134
+
135
+ type Settled =
136
+ | { status: "fulfilled"; value: unknown }
137
+ | { status: "rejected"; value: string }
138
+ | { status: "late"; value: undefined };
139
+
140
+ /** Wait for `promise`, but no later than `deadline` (a performance.now() time). */
141
+ async function settleBefore(promise: Promise<unknown>, deadline: number): Promise<Settled> {
142
+ let timer: NodeJS.Timeout | undefined;
143
+ const late = new Promise<Settled>((resolve) => {
144
+ timer = setTimeout(
145
+ () => resolve({ status: "late", value: undefined }),
146
+ Math.max(0, deadline - performance.now()),
147
+ );
148
+ });
149
+ try {
150
+ return await Promise.race([
151
+ promise.then(
152
+ (value): Settled => ({ status: "fulfilled", value }),
153
+ (error: unknown): Settled => ({
154
+ status: "rejected",
155
+ value: error instanceof Error ? error.message : String(error),
156
+ }),
157
+ ),
158
+ late,
159
+ ]);
160
+ } finally {
161
+ clearTimeout(timer);
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Lua only ever receives plain JSON data from the host: a copy made through
167
+ * JSON, after checking there is nothing a copy would silently drop or call
168
+ * (functions, class instances, Maps, getters, cycles, non-finite numbers).
169
+ */
170
+ export function toPlainJson(
171
+ value: unknown,
172
+ ): { ok: true; value: unknown } | { ok: false; error: string } {
173
+ const refuse = (why: string) => ({
174
+ ok: false as const,
175
+ error: `E_INVALID: a host function returned ${why}, not plain JSON data`,
176
+ });
177
+ const seen = new Set<object>();
178
+ const check = (v: unknown, depth: number): string | null => {
179
+ if (v === null || typeof v === "string" || typeof v === "boolean") return null;
180
+ if (typeof v === "number") return Number.isFinite(v) ? null : "a non-finite number";
181
+ if (v === undefined) return depth === 0 ? null : "undefined inside a value";
182
+ if (typeof v !== "object") return `a ${typeof v}`;
183
+ if (depth > 64) return "a value nested deeper than 64 levels";
184
+ if (seen.has(v)) return "a value that contains itself";
185
+ seen.add(v);
186
+ const proto = Object.getPrototypeOf(v) as unknown;
187
+ if (Array.isArray(v)) {
188
+ if (proto !== Array.prototype) return "an array subclass";
189
+ } else if (proto !== Object.prototype && proto !== null) {
190
+ return "a class instance";
191
+ }
192
+ for (const key of Reflect.ownKeys(v)) {
193
+ if (typeof key === "symbol") return "an object with symbol keys";
194
+ const descriptor = Object.getOwnPropertyDescriptor(v, key)!;
195
+ if (!("value" in descriptor)) return "an object with accessors";
196
+ const why = check(descriptor.value, depth + 1);
197
+ if (why) return why;
198
+ }
199
+ seen.delete(v);
200
+ return null;
201
+ };
202
+ const why = check(value, 0);
203
+ if (why) return refuse(why);
204
+ if (value === undefined || value === null) return { ok: true, value: undefined };
205
+ // Lua has no null: JSON nulls become nil (absent keys). wasmoon cannot push
206
+ // a JS null nested inside a table, so they are dropped in the copy.
207
+ return {
208
+ ok: true,
209
+ value: JSON.parse(JSON.stringify(value), (_key, item: unknown) =>
210
+ item === null ? undefined : item,
211
+ ),
212
+ };
213
+ }
214
+
215
+ function plainOrThrow(value: unknown): unknown {
216
+ const plain = toPlainJson(value);
217
+ if (!plain.ok) throw new PluginRunError(plain.error, null);
218
+ return plain.value;
219
+ }
220
+
221
+ function classify(message: string): PluginTripKind | null {
222
+ if (message.includes(TIMEOUT_MESSAGE) || message.includes(WALL_CLOCK_MESSAGE)) return "timeout";
223
+ if (/not enough memory/u.test(message)) return "memory";
224
+ if (/Aborted\(|RuntimeError/u.test(message)) return "abort";
225
+ return null;
226
+ }
227
+
228
+ export class PluginLuaState {
229
+ readonly name: string;
230
+ readonly #engine: LuaEngine;
231
+ readonly #hooks: PluginStateHooks;
232
+ #deadline = Number.POSITIVE_INFINITY;
233
+ #actionsChanged = false;
234
+ readonly #timers = new Map<number, NodeJS.Timeout>();
235
+ /** No timer of this plugin fires before this time (performance.now()). */
236
+ #timerReadyAt = 0;
237
+ #callbackLimits: { budgetMs: number; wallClockMs: number } = {
238
+ budgetMs: 250,
239
+ wallClockMs: 30_000,
240
+ };
241
+ /** The runner whose slice is executing right now, if any. */
242
+ #active: Runner | null = null;
243
+ #broken: string | null = null;
244
+
245
+ private constructor(name: string, engine: LuaEngine, hooks: PluginStateHooks) {
246
+ this.name = name;
247
+ this.#engine = engine;
248
+ this.#hooks = hooks;
249
+ }
250
+
251
+ static async create(options: {
252
+ spec: Pick<PluginSpec, "name" | "includeRoots" | "moduleRoots" | "settings">;
253
+ apiVersion: string;
254
+ productVersion: string;
255
+ limits: PluginLimits;
256
+ hooks: PluginStateHooks;
257
+ /** Async host functions exposed as `ide.<name>`. Slice A ships none. */
258
+ hostFunctions?: HostFunctions;
259
+ }): Promise<PluginLuaState> {
260
+ const engine = await new LuaFactory().createEngine({
261
+ openStandardLibs: true,
262
+ injectObjects: false,
263
+ enableProxy: false,
264
+ traceAllocations: true,
265
+ });
266
+ const state = new PluginLuaState(options.spec.name, engine, options.hooks);
267
+ state.#callbackLimits = {
268
+ budgetMs: options.limits.callbackBudgetMs,
269
+ wallClockMs: options.limits.wallClockMs,
270
+ };
271
+ const global = engine.global;
272
+ global.set("__ide_over", () => {
273
+ if (performance.now() <= state.#deadline) return false;
274
+ if (state.#active) state.#active.overran = true;
275
+ return true;
276
+ });
277
+ const hostFunctions = options.hostFunctions ?? {};
278
+ // Starts a host call for the runner whose slice is running; the prelude
279
+ // then yields, and runThread waits for exactly this promise.
280
+ global.set("__ide_begin", (name: unknown, args: unknown) => {
281
+ const runner = state.#active;
282
+ if (!runner) throw new Error("E_INVALID: host calls are only possible inside a callback");
283
+ if (runner.pending) throw new Error("E_INVALID: a host call is already in progress");
284
+ const fn = typeof name === "string" ? hostFunctions[name] : undefined;
285
+ if (!fn) throw new Error(`E_INVALID: no host function '${String(name)}'`);
286
+ let parsed: unknown;
287
+ try {
288
+ parsed = typeof args === "string" ? JSON.parse(args) : [];
289
+ } catch {
290
+ parsed = [];
291
+ }
292
+ const list = Array.isArray(parsed) ? parsed : [];
293
+ const origin = runner.origin;
294
+ runner.pending = Promise.resolve().then(() => fn(list, origin));
295
+ });
296
+ global.set("__ide_log", (level: unknown, message: unknown, fieldsJson: unknown) => {
297
+ const lvl: PluginLogLevel =
298
+ level === "debug" || level === "warn" || level === "error" ? level : "info";
299
+ let fields: Record<string, unknown> | undefined;
300
+ if (typeof fieldsJson === "string") {
301
+ try {
302
+ const parsed: unknown = JSON.parse(fieldsJson);
303
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
304
+ fields = parsed as Record<string, unknown>;
305
+ } catch {
306
+ fields = undefined;
307
+ }
308
+ }
309
+ options.hooks.log(lvl, String(message), fields);
310
+ });
311
+ global.set("__ide_resolve", (kind: unknown, name: unknown) => {
312
+ if ((kind !== "file" && kind !== "module") || typeof name !== "string")
313
+ return LuaMultiReturn.of(undefined, "E_INVALID: bad include request");
314
+ const roots = kind === "file" ? options.spec.includeRoots : options.spec.moduleRoots;
315
+ const resolved = resolveSource(kind, name, roots);
316
+ return resolved.ok
317
+ ? LuaMultiReturn.of(resolved.source, resolved.display)
318
+ : LuaMultiReturn.of(undefined, resolved.error);
319
+ });
320
+ global.set("__ide_info", {
321
+ api: options.apiVersion,
322
+ version: options.productVersion,
323
+ plugin: options.spec.name,
324
+ settings: options.spec.settings,
325
+ host_functions: Object.keys(hostFunctions),
326
+ });
327
+ global.set("__ide_actions_changed", () => {
328
+ state.#actionsChanged = true;
329
+ });
330
+ engine.doStringSync(SANDBOX_PRELUDE);
331
+ engine.doStringSync(ACTIONS_PRELUDE);
332
+ global.set("__ide_timer_start", (id: unknown, ms: unknown, repeating: unknown) =>
333
+ state.#startTimer(Number(id), Number(ms), repeating === true),
334
+ );
335
+ global.set("__ide_timer_cancel", (id: unknown) => state.#cancelTimer(Number(id)));
336
+ global.set("__ide_json_decode", (text: unknown) => {
337
+ let parsed: unknown;
338
+ try {
339
+ parsed = JSON.parse(String(text));
340
+ } catch (error) {
341
+ throw new Error(`E_INVALID: ide.json.decode: ${(error as Error).message}`, {
342
+ cause: error,
343
+ });
344
+ }
345
+ const plain = toPlainJson(parsed);
346
+ if (!plain.ok) throw new Error(plain.error);
347
+ return plain.value;
348
+ });
349
+ engine.doStringSync(HOST_API_PRELUDE);
350
+ // Cap memory only after the prelude, so the cap measures plugin use.
351
+ global.setMemoryMax(global.getMemoryUsed() + options.limits.memoryBytes);
352
+ return state;
353
+ }
354
+
355
+ /** True once a fatal abort left this state unusable. */
356
+ get broken(): string | null {
357
+ return this.#broken;
358
+ }
359
+
360
+ memoryUsed(): number {
361
+ return this.#engine.global.getMemoryUsed();
362
+ }
363
+
364
+ /**
365
+ * Run `internalFunction` from `__ide_internal` on a fresh runner thread with
366
+ * `args`, giving Lua at most `budgetMs` of run time across all its slices.
367
+ */
368
+ async runThread(
369
+ internalFunction: string,
370
+ args: unknown[],
371
+ limits: CallbackLimits,
372
+ ): Promise<unknown[]> {
373
+ if (this.#broken) throw new PluginRunError(`E_UNAVAILABLE: ${this.#broken}`, null);
374
+ const global = this.#engine.global;
375
+ const lua = global.lua;
376
+ const thread = global.newThread();
377
+ // Anchor the thread in the registry instead of by stack index, so runner
378
+ // threads that finish out of order cannot remove each other.
379
+ const ref = lua.luaL_ref(global.address, LUA_REGISTRYINDEX);
380
+ const runner: Runner = {
381
+ pending: null,
382
+ overran: false,
383
+ ...(limits.origin ? { origin: limits.origin } : {}),
384
+ };
385
+ const wallDeadline = performance.now() + limits.wallClockMs;
386
+ let remaining = limits.budgetMs;
387
+ try {
388
+ thread.loadString(`return __ide_internal.${internalFunction}(...)`, `=${internalFunction}`);
389
+ for (const arg of args) thread.pushValue(arg);
390
+ let argCount = args.length;
391
+ for (;;) {
392
+ this.#hooks.busy();
393
+ const started = performance.now();
394
+ this.#deadline = started + Math.max(0, remaining);
395
+ this.#active = runner;
396
+ let result;
397
+ try {
398
+ result = thread.resume(argCount);
399
+ } finally {
400
+ this.#active = null;
401
+ remaining -= performance.now() - started;
402
+ this.#deadline = Number.POSITIVE_INFINITY;
403
+ this.#hooks.idle();
404
+ }
405
+ argCount = 0;
406
+ if (result.result === LuaReturn.Yield) {
407
+ // Never inspect or convert what Lua yielded: a table can pose as a
408
+ // promise and its `then` would run as JS outside every limit. The
409
+ // only yield the host waits on is one it started itself.
410
+ if (result.resultCount > 0) thread.pop(result.resultCount);
411
+ const pending = runner.pending;
412
+ runner.pending = null;
413
+ if (pending) {
414
+ const outcome = await settleBefore(pending, wallDeadline);
415
+ if (outcome.status === "late") throw new Error(WALL_CLOCK_MESSAGE);
416
+ const plain =
417
+ outcome.status === "fulfilled"
418
+ ? toPlainJson(outcome.value)
419
+ : { ok: false as const, error: outcome.value };
420
+ thread.pushValue(plain.ok);
421
+ thread.pushValue(plain.ok ? plain.value : plain.error);
422
+ argCount = 2;
423
+ } else if (result.resultCount > 0) {
424
+ throw new Error(FOREIGN_YIELD_MESSAGE);
425
+ } else {
426
+ // A bare coroutine.yield(): let the event loop breathe, then go on,
427
+ // unless the wall clock ran out meanwhile. (A host call's wait has
428
+ // its own deadline above; each guard covers exactly one path.)
429
+ await new Promise((resolve) => setImmediate(resolve));
430
+ if (performance.now() > wallDeadline) throw new Error(WALL_CLOCK_MESSAGE);
431
+ }
432
+ continue;
433
+ }
434
+ thread.assertOk(result.result);
435
+ // The plugin caught E_TIMEOUT and still returned: count the overrun.
436
+ if (runner.overran) this.#hooks.trip("timeout");
437
+ return [...thread.getStackValues()];
438
+ }
439
+ } catch (error) {
440
+ const message = error instanceof Error ? error.message : String(error);
441
+ const trip = classify(message);
442
+ if (trip) this.#hooks.trip(trip);
443
+ if (trip === "abort") this.#broken = "the Lua runtime aborted; reload the plugin";
444
+ throw new PluginRunError(message, trip);
445
+ } finally {
446
+ lua.luaL_unref(global.address, LUA_REGISTRYINDEX, ref);
447
+ this.#publishActions();
448
+ }
449
+ }
450
+
451
+ /** Hand the host the plugin's action list if a callback changed it. */
452
+ #publishActions(): void {
453
+ if (!this.#actionsChanged || this.#broken) return;
454
+ this.#actionsChanged = false;
455
+ try {
456
+ const json: unknown = this.#engine.doStringSync("return __ide_internal.actions_json()");
457
+ if (typeof json === "string") this.#hooks.actions?.(json);
458
+ } catch (error) {
459
+ this.#hooks.log("error", `could not publish actions: ${(error as Error).message}`);
460
+ }
461
+ }
462
+
463
+ /** Run plugin source text. Resolves to the JSON text of its return values. */
464
+ async runSource(
465
+ source: string,
466
+ chunkName: string,
467
+ limits: { budgetMs: number; wallClockMs: number },
468
+ ): Promise<string> {
469
+ const [json] = await this.runThread("run_source", [source, chunkName], limits);
470
+ return typeof json === "string" ? json : "[]";
471
+ }
472
+
473
+ /**
474
+ * Invoke one of the plugin's actions. `args` and `context` must already be
475
+ * plain JSON data. Resolves to the JSON text of the action's first result.
476
+ */
477
+ async invokeAction(
478
+ action: string,
479
+ args: Record<string, unknown>,
480
+ context: Record<string, unknown>,
481
+ limits: CallbackLimits,
482
+ ): Promise<string> {
483
+ const [json] = await this.runThread(
484
+ "invoke_action",
485
+ [action, plainOrThrow(args), plainOrThrow(context)],
486
+ limits,
487
+ );
488
+ return typeof json === "string" ? json : "[]";
489
+ }
490
+
491
+ /** Choices and default for one parameter, as JSON text `{ choices?, default? }`. */
492
+ async paramOptions(
493
+ action: string,
494
+ param: string,
495
+ context: Record<string, unknown>,
496
+ limits: CallbackLimits,
497
+ ): Promise<string> {
498
+ const [json] = await this.runThread(
499
+ "param_options",
500
+ [action, param, plainOrThrow(context)],
501
+ limits,
502
+ );
503
+ return typeof json === "string" ? json : "{}";
504
+ }
505
+
506
+ #startTimer(id: number, ms: number, repeating: boolean): void {
507
+ // Timers get at most half the host: after a timer callback that took t ms
508
+ // of wall time (Lua and the host calls it waited for), no timer of this
509
+ // plugin fires for another max(t, TIMER_GAP_MS). A chain of
510
+ // ide.timer.after(0) callbacks, busy or empty, cannot keep the host busy.
511
+ const fire = () => {
512
+ const wait = this.#timerReadyAt - performance.now();
513
+ if (wait > 0) {
514
+ // An interval just skips this tick; a one-shot timer fires later.
515
+ if (!repeating) schedule(setTimeout(fire, Math.ceil(wait)));
516
+ return;
517
+ }
518
+ if (!repeating) this.#timers.delete(id);
519
+ const started = performance.now();
520
+ void this.runThread("run_timer", [id], this.#callbackLimits)
521
+ .catch((error: unknown) => {
522
+ this.#hooks.log("error", `timer failed: ${(error as Error).message}`);
523
+ })
524
+ .finally(() => {
525
+ const now = performance.now();
526
+ this.#timerReadyAt = now + Math.max(now - started, TIMER_GAP_MS);
527
+ });
528
+ };
529
+ const schedule = (handle: NodeJS.Timeout) => {
530
+ handle.unref?.();
531
+ this.#timers.set(id, handle);
532
+ };
533
+ schedule(repeating ? setInterval(fire, ms) : setTimeout(fire, ms));
534
+ }
535
+
536
+ #cancelTimer(id: number): void {
537
+ const handle = this.#timers.get(id);
538
+ if (!handle) return;
539
+ clearTimeout(handle);
540
+ clearInterval(handle);
541
+ this.#timers.delete(id);
542
+ }
543
+
544
+ /** Timers currently scheduled; for tests and status. */
545
+ activeTimers(): number {
546
+ return this.#timers.size;
547
+ }
548
+
549
+ close(): void {
550
+ for (const id of [...this.#timers.keys()]) this.#cancelTimer(id);
551
+ try {
552
+ this.#engine.global.close();
553
+ } catch {
554
+ // A state that aborted may not close cleanly; its memory goes with the module.
555
+ }
556
+ }
557
+ }