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,790 @@
1
+ /**
2
+ * The daemon side of plugins: starts the plugin host process, keeps it alive,
3
+ * and decides when a plugin is switched off.
4
+ *
5
+ * Three guards, from gentle to hard:
6
+ * 1. The host's own per-callback budget and memory cap, which raise Lua
7
+ * errors. Each one is reported here as a trip; `tripLimit` trips within
8
+ * `tripWindowMs` disable the plugin.
9
+ * 2. The heartbeat watchdog. The host sends a heartbeat every second from its
10
+ * event loop. A Lua slice that never returns (for example one that keeps
11
+ * catching E_TIMEOUT) stops the heartbeats; after `heartbeatTimeoutMs`
12
+ * this kills the host with SIGKILL and disables the plugin that the
13
+ * host's last "busy" marker named.
14
+ * 3. Restarts with exponential backoff when the host exits on its own.
15
+ */
16
+ import { spawn } from "node:child_process";
17
+ import { randomUUID } from "node:crypto";
18
+ import { createInterface } from "node:readline";
19
+ import { CommandChoiceSchemaZ, terminalSafe, terminalSafeDeep, } from "@tmux-ide/contracts";
20
+ import { z } from "zod";
21
+ import { isSecretKey, redactLogValue, redactText } from "../lib/log-sanitize.js";
22
+ import { PluginActionCatalog, parsePluginCommandId } from "./action-catalog.js";
23
+ import { ownerCapabilities } from "./host-calls.js";
24
+ import { discoverPlugins } from "./discovery.js";
25
+ import { appendPluginLog, pluginLogPath } from "./plugin-log.js";
26
+ import { DEFAULT_PLUGIN_LIMITS, RUN_STATE_NAME, HostEventSchemaZ, MAX_PROTOCOL_LINE_BYTES, PLUGIN_HOST_PROTOCOL_VERSION, } from "./protocol.js";
27
+ /**
28
+ * The only variables the plugin host inherits. The daemon's own environment
29
+ * (owner tokens, TMUX_IDE_* settings, anything the user exported) stays out.
30
+ */
31
+ export const HOST_ENV_ALLOWLIST = Object.freeze([
32
+ "PATH",
33
+ "HOME",
34
+ "TMUX_IDE_HOME",
35
+ "USER",
36
+ "LOGNAME",
37
+ "SHELL",
38
+ "LANG",
39
+ "LC_ALL",
40
+ "LC_CTYPE",
41
+ "LC_MESSAGES",
42
+ "TMPDIR",
43
+ // Where tmux keeps its default socket: programs such as tmux-ide reach the
44
+ // same tmux server as the daemon.
45
+ "TMUX_TMPDIR",
46
+ "TZ",
47
+ // Windows needs these to start Node at all.
48
+ "SystemRoot",
49
+ "TEMP",
50
+ "TMP",
51
+ ]);
52
+ export function minimalHostEnv(env = process.env) {
53
+ const out = {};
54
+ for (const key of HOST_ENV_ALLOWLIST) {
55
+ const value = env[key];
56
+ if (value !== undefined)
57
+ out[key] = value;
58
+ }
59
+ return out;
60
+ }
61
+ /** Values of credential-named variables in `env`, to redact wherever they appear. */
62
+ export function secretEnvValues(env = process.env) {
63
+ return Object.entries(env)
64
+ .filter(([key, value]) => isSecretKey(key) && typeof value === "string" && value.length >= 8)
65
+ .map(([, value]) => value);
66
+ }
67
+ const ParamOptionsReplySchemaZ = z
68
+ .object({
69
+ choices: z.array(CommandChoiceSchemaZ).max(500).optional(),
70
+ default: z.union([z.string().max(10_000), z.number(), z.boolean()]).optional(),
71
+ })
72
+ .strip();
73
+ function safeJson(text) {
74
+ try {
75
+ return JSON.parse(text);
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
81
+ const defaultRestartDelay = (attempt) => Math.min(1000 * 2 ** attempt, 60_000);
82
+ export class PluginSupervisor {
83
+ #options;
84
+ #entries = new Map();
85
+ #loadWaiters = new Map();
86
+ #runs = new Map();
87
+ #requests = new Map();
88
+ #actions;
89
+ #problems = [];
90
+ #awaitingConsent = [];
91
+ #host = null;
92
+ #restarts = 0;
93
+ #backoffAttempt = 0;
94
+ #restartTimer = null;
95
+ #watchdog = null;
96
+ #stopped = false;
97
+ constructor(options) {
98
+ const logPath = pluginLogPath(options.stateHome);
99
+ this.#options = {
100
+ stateHome: options.stateHome,
101
+ productVersion: options.productVersion,
102
+ hostCommand: options.hostCommand,
103
+ hostEnv: options.hostEnv ?? minimalHostEnv(),
104
+ secrets: options.secrets ?? (() => secretEnvValues()),
105
+ limits: options.limits ?? DEFAULT_PLUGIN_LIMITS,
106
+ heartbeatTimeoutMs: options.heartbeatTimeoutMs ?? 5000,
107
+ watchdogIntervalMs: options.watchdogIntervalMs ?? 500,
108
+ helloTimeoutMs: options.helloTimeoutMs ?? 15_000,
109
+ tripLimit: options.tripLimit ?? 3,
110
+ tripWindowMs: options.tripWindowMs ?? 60_000,
111
+ restartDelayMs: options.restartDelayMs ?? defaultRestartDelay,
112
+ healthyAfterMs: options.healthyAfterMs ?? 60_000,
113
+ onLog: options.onLog ?? ((entry) => appendPluginLog(logPath, entry)),
114
+ now: options.now ?? Date.now,
115
+ calls: options.calls,
116
+ };
117
+ this.#actions = new PluginActionCatalog(() => {
118
+ // A listener that throws must not break whatever changed the catalog
119
+ // (a host event, an exit, a stop).
120
+ try {
121
+ options.onCatalogChange?.();
122
+ }
123
+ catch (error) {
124
+ this.#log("host", "error", `a catalog listener failed: ${error.message}`);
125
+ }
126
+ });
127
+ }
128
+ // ------------------------------------------------------------------ public
129
+ /** Discover plugins and load them. Starts the host only if there is something to load. */
130
+ async start() {
131
+ return this.reload();
132
+ }
133
+ /**
134
+ * Discover again and (re)load every plugin, or only `name`. Reloading
135
+ * clears a plugin's disabled state and trip count.
136
+ */
137
+ async reload(name) {
138
+ if (this.#stopped)
139
+ return this.status();
140
+ const discovery = discoverPlugins(this.#options.stateHome);
141
+ this.#problems = discovery.problems;
142
+ this.#awaitingConsent = discovery.awaitingConsent;
143
+ const found = new Set(discovery.specs.map((spec) => spec.name));
144
+ // Plugins that vanished from disk, became invalid, or changed since
145
+ // consent are unloaded and forgotten.
146
+ for (const [entryName, entry] of [...this.#entries]) {
147
+ // Whatever was asked to reload: a loaded plugin whose files changed,
148
+ // lost consent or broke goes now, not at its own next reload.
149
+ if (entry.spec && !found.has(entryName)) {
150
+ this.#send({ type: "unload", name: entryName });
151
+ this.#entries.delete(entryName);
152
+ this.#actions.drop(entryName);
153
+ this.#stopPrograms(entryName);
154
+ }
155
+ }
156
+ for (const problem of discovery.problems) {
157
+ // A loaded plugin that became a problem was unloaded above, actions
158
+ // and programs included (it is no longer among the specs).
159
+ this.#entries.delete(problem.name);
160
+ }
161
+ const toLoad = discovery.specs.filter((spec) => !name || spec.name === name);
162
+ if (toLoad.length === 0)
163
+ return this.status();
164
+ if (!this.#host)
165
+ this.#spawn();
166
+ const waits = [];
167
+ for (const spec of toLoad) {
168
+ // Loading again replaces the plugin's code: what the old code started goes.
169
+ if (this.#entries.has(spec.name))
170
+ this.#stopPrograms(spec.name);
171
+ this.#entries.set(spec.name, {
172
+ spec,
173
+ name: spec.name,
174
+ kind: spec.kind,
175
+ state: "loading",
176
+ trips: [],
177
+ });
178
+ waits.push(this.#waitLoaded(spec.name));
179
+ this.#send({ type: "load", plugin: spec });
180
+ }
181
+ const budget = this.#options.limits.callbackBudgetMs + this.#options.helloTimeoutMs;
182
+ await Promise.race([
183
+ Promise.all(waits),
184
+ new Promise((resolve) => setTimeout(resolve, budget).unref()),
185
+ ]);
186
+ return this.status();
187
+ }
188
+ status() {
189
+ const secrets = this.#secretSet();
190
+ const plugins = [...this.#entries.values()].map((entry) => ({
191
+ name: entry.name,
192
+ kind: entry.kind,
193
+ state: entry.state,
194
+ ...(entry.error ? { error: entry.error } : {}),
195
+ ...(entry.memoryBytes !== undefined ? { memoryBytes: entry.memoryBytes } : {}),
196
+ trips: entry.trips.length,
197
+ }));
198
+ for (const problem of this.#problems) {
199
+ plugins.push({
200
+ name: problem.name,
201
+ kind: "plugin",
202
+ state: "invalid",
203
+ error: problem.error,
204
+ trips: 0,
205
+ });
206
+ }
207
+ for (const pending of this.#awaitingConsent) {
208
+ plugins.push({
209
+ name: pending.name,
210
+ kind: "plugin",
211
+ state: "needs-consent",
212
+ error: pending.reason === "new"
213
+ ? `not consented to yet; run \`tmux-ide plugin consent ${pending.name}\``
214
+ : `changed since it was consented to; run \`tmux-ide plugin consent ${pending.name}\` again`,
215
+ trips: 0,
216
+ });
217
+ }
218
+ plugins.sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "init" ? 1 : -1);
219
+ return {
220
+ host: {
221
+ running: this.#host !== null,
222
+ pid: this.#host?.child.pid ?? null,
223
+ restarts: this.#restarts,
224
+ },
225
+ // Every error here can quote plugin output (a load error, a manifest
226
+ // parse error): redact all of them on the way out.
227
+ plugins: plugins.map((plugin) => plugin.error ? { ...plugin, error: redactText(plugin.error, secrets) } : plugin),
228
+ };
229
+ }
230
+ /** Run Lua source once in a fresh, temporary state. */
231
+ async run(code, options = {}) {
232
+ if (this.#stopped)
233
+ return { ok: false, error: "E_UNAVAILABLE: plugins are stopped", logs: [] };
234
+ if (!this.#host)
235
+ this.#spawn();
236
+ const id = randomUUID();
237
+ const budgetMs = options.budgetMs ?? 5000;
238
+ return new Promise((resolve) => {
239
+ const timer = setTimeout(() => {
240
+ this.#runs.delete(id);
241
+ resolve({ ok: false, error: "E_TIMEOUT: the host did not answer", logs: [] });
242
+ }, Math.max(this.#options.limits.wallClockMs, budgetMs * 2) +
243
+ this.#options.heartbeatTimeoutMs +
244
+ this.#options.helloTimeoutMs);
245
+ timer.unref();
246
+ this.#runs.set(id, (result) => {
247
+ clearTimeout(timer);
248
+ this.#runs.delete(id);
249
+ resolve(result);
250
+ });
251
+ this.#send({
252
+ type: "run",
253
+ id,
254
+ code,
255
+ chunkName: options.chunkName ?? "=run",
256
+ budgetMs,
257
+ });
258
+ });
259
+ }
260
+ /** Every action plugins registered, as command catalog entries. */
261
+ actionCatalog() {
262
+ return { revision: this.#actions.revision, entries: this.#actions.entries() };
263
+ }
264
+ /**
265
+ * Invoke a plugin action by catalog id. A dangerous action runs only with
266
+ * `confirmed`, which the caller sets after the person confirmed it.
267
+ */
268
+ async invokeAction(id, args, context, options = {}) {
269
+ const entry = this.#actions.find(id);
270
+ const parsed = parsePluginCommandId(id);
271
+ if (!entry || !parsed)
272
+ return { ok: false, error: `E_NOT_FOUND: no command '${terminalSafe(id, 200)}'` };
273
+ if (entry.descriptor.dangerous && options.confirmed !== true)
274
+ return { ok: false, error: `E_CONFIRM: '${entry.descriptor.label}' must be confirmed first` };
275
+ let origin = "";
276
+ const reply = await this.#request((requestId) => ({
277
+ type: "invoke",
278
+ id: (origin = requestId),
279
+ plugin: parsed.plugin,
280
+ action: parsed.action,
281
+ args,
282
+ context,
283
+ }));
284
+ const secrets = this.#secretSet();
285
+ if (!reply.ok) {
286
+ // A failed callback leaves nothing running behind it; programs other
287
+ // callbacks (timers, other requests) started keep running.
288
+ this.#stopPrograms(parsed.plugin, origin);
289
+ // Results and errors are plugin text on their way to terminals: plain
290
+ // text only, whatever the plugin returned.
291
+ return { ok: false, error: terminalSafe(redactText(reply.error, secrets)) };
292
+ }
293
+ let value;
294
+ try {
295
+ const list = JSON.parse(reply.text);
296
+ value = Array.isArray(list) ? list[0] : undefined;
297
+ }
298
+ catch {
299
+ value = undefined;
300
+ }
301
+ return value === undefined
302
+ ? { ok: true }
303
+ : { ok: true, value: terminalSafeDeep(redactLogValue(value, secrets)) };
304
+ }
305
+ /** Choices and default for one parameter of a plugin action. */
306
+ async actionParamOptions(id, param, context) {
307
+ const entry = this.#actions.find(id);
308
+ const parsed = parsePluginCommandId(id);
309
+ if (!entry || !parsed)
310
+ return { ok: false, error: `E_NOT_FOUND: no command '${terminalSafe(id, 200)}'` };
311
+ if (!entry.params.some((candidate) => candidate.name === param))
312
+ return {
313
+ ok: false,
314
+ error: `E_NOT_FOUND: '${id}' has no parameter '${terminalSafe(param, 200)}'`,
315
+ };
316
+ let origin = "";
317
+ const reply = await this.#request((requestId) => ({
318
+ type: "param-options",
319
+ id: (origin = requestId),
320
+ plugin: parsed.plugin,
321
+ action: parsed.action,
322
+ param,
323
+ context,
324
+ }));
325
+ const secrets = this.#secretSet();
326
+ if (!reply.ok) {
327
+ this.#stopPrograms(parsed.plugin, origin);
328
+ return { ok: false, error: terminalSafe(redactText(reply.error, secrets)) };
329
+ }
330
+ const result = ParamOptionsReplySchemaZ.safeParse(terminalSafeDeep(redactLogValue(safeJson(reply.text), secrets)));
331
+ if (!result.success)
332
+ return { ok: false, error: "E_INVALID: the plugin returned malformed choices" };
333
+ return {
334
+ ok: true,
335
+ ...(result.data.choices ? { choices: result.data.choices } : {}),
336
+ ...(result.data.default !== undefined ? { default: result.data.default } : {}),
337
+ };
338
+ }
339
+ #request(build) {
340
+ if (this.#stopped)
341
+ return Promise.resolve({ ok: false, error: "E_UNAVAILABLE: plugins are stopped" });
342
+ if (!this.#host)
343
+ return Promise.resolve({ ok: false, error: "E_UNAVAILABLE: the plugin host is not running" });
344
+ const requestId = randomUUID();
345
+ return new Promise((resolve) => {
346
+ const timer = setTimeout(() => {
347
+ this.#requests.delete(requestId);
348
+ resolve({ ok: false, error: "E_TIMEOUT: the plugin did not answer" });
349
+ }, this.#options.limits.wallClockMs + this.#options.heartbeatTimeoutMs + 1000);
350
+ timer.unref();
351
+ this.#requests.set(requestId, (reply) => {
352
+ clearTimeout(timer);
353
+ this.#requests.delete(requestId);
354
+ resolve(reply);
355
+ });
356
+ this.#send(build(requestId));
357
+ });
358
+ }
359
+ async stop() {
360
+ this.#stopped = true;
361
+ if (this.#restartTimer)
362
+ clearTimeout(this.#restartTimer);
363
+ this.#restartTimer = null;
364
+ this.#stopWatchdog();
365
+ const host = this.#host;
366
+ this.#host = null;
367
+ this.#failRuns("E_UNAVAILABLE: plugins stopped");
368
+ if (!host)
369
+ return;
370
+ await new Promise((resolve) => {
371
+ const timer = setTimeout(() => {
372
+ host.child.kill("SIGKILL");
373
+ resolve();
374
+ }, 2000);
375
+ timer.unref();
376
+ host.child.once("exit", () => {
377
+ clearTimeout(timer);
378
+ resolve();
379
+ });
380
+ try {
381
+ host.child.stdin.end(`${JSON.stringify({ type: "shutdown" })}\n`);
382
+ }
383
+ catch {
384
+ host.child.kill("SIGKILL");
385
+ }
386
+ });
387
+ }
388
+ // ---------------------------------------------------------------- internals
389
+ #log(plugin, level, message, fields) {
390
+ const secrets = this.#secretSet();
391
+ this.#options.onLog({
392
+ ts: new Date(this.#options.now()).toISOString(),
393
+ plugin,
394
+ level,
395
+ message: redactText(message, secrets),
396
+ ...(fields ? { fields: redactLogValue(fields, secrets) } : {}),
397
+ });
398
+ }
399
+ #secretSet() {
400
+ return new Set([...this.#options.secrets()].filter((secret) => secret.length >= 8));
401
+ }
402
+ #waitLoaded(name) {
403
+ return new Promise((resolve) => {
404
+ const list = this.#loadWaiters.get(name) ?? [];
405
+ list.push(resolve);
406
+ this.#loadWaiters.set(name, list);
407
+ });
408
+ }
409
+ #settleLoad(name) {
410
+ const list = this.#loadWaiters.get(name);
411
+ this.#loadWaiters.delete(name);
412
+ for (const resolve of list ?? [])
413
+ resolve();
414
+ }
415
+ #send(command) {
416
+ const host = this.#host;
417
+ if (!host)
418
+ return;
419
+ if (!host.ready && command.type !== "configure") {
420
+ host.outbox.push(command);
421
+ return;
422
+ }
423
+ try {
424
+ host.child.stdin.write(`${JSON.stringify(command)}\n`);
425
+ }
426
+ catch {
427
+ // The exit handler restarts the host and resends loads.
428
+ }
429
+ }
430
+ #spawn() {
431
+ const [command, ...args] = this.#options.hostCommand;
432
+ if (!command)
433
+ throw new Error("plugin host command is empty");
434
+ const child = spawn(command, args, {
435
+ stdio: ["pipe", "pipe", "pipe", "pipe"],
436
+ env: this.#options.hostEnv,
437
+ });
438
+ const host = {
439
+ child,
440
+ ready: false,
441
+ lastHeartbeat: this.#options.now(),
442
+ busy: null,
443
+ outbox: [],
444
+ killedBy: null,
445
+ healthyTimer: null,
446
+ };
447
+ this.#host = host;
448
+ const events = child.stdio[3];
449
+ const lines = createInterface({ input: events, crlfDelay: Infinity });
450
+ lines.on("line", (line) => this.#onEventLine(host, line));
451
+ for (const stream of [child.stdout, child.stderr]) {
452
+ if (!stream)
453
+ continue;
454
+ const out = createInterface({ input: stream, crlfDelay: Infinity });
455
+ out.on("line", (line) => {
456
+ if (line.trim())
457
+ this.#log("host", "warn", line.slice(0, 2000));
458
+ });
459
+ }
460
+ child.on("error", (error) => this.#log("host", "error", `plugin host failed: ${error.message}`));
461
+ child.on("exit", (code, signal) => this.#onExit(host, code, signal));
462
+ const helloTimer = setTimeout(() => {
463
+ if (this.#host === host && !host.ready) {
464
+ host.killedBy = "the plugin host did not start in time";
465
+ child.kill("SIGKILL");
466
+ }
467
+ }, this.#options.helloTimeoutMs);
468
+ helloTimer.unref();
469
+ child.once("exit", () => clearTimeout(helloTimer));
470
+ this.#startWatchdog();
471
+ }
472
+ #onEventLine(host, line) {
473
+ if (this.#host !== host || line.length > MAX_PROTOCOL_LINE_BYTES)
474
+ return;
475
+ let raw;
476
+ try {
477
+ raw = JSON.parse(line);
478
+ }
479
+ catch {
480
+ return;
481
+ }
482
+ const parsed = HostEventSchemaZ.safeParse(raw);
483
+ if (!parsed.success)
484
+ return;
485
+ // Host lines carry plugin output: nothing in handling one may throw out
486
+ // of the stream handler and take the daemon down.
487
+ try {
488
+ this.#onEvent(host, parsed.data);
489
+ }
490
+ catch (error) {
491
+ this.#log("host", "error", `ignored a host event that failed: ${error.message}`);
492
+ }
493
+ }
494
+ #onEvent(host, event) {
495
+ switch (event.type) {
496
+ case "hello": {
497
+ if (event.protocolVersion !== PLUGIN_HOST_PROTOCOL_VERSION)
498
+ return;
499
+ host.ready = true;
500
+ // A host that stays up for a while has recovered: the next crash
501
+ // starts the backoff from the beginning again.
502
+ host.healthyTimer = setTimeout(() => {
503
+ if (this.#host === host)
504
+ this.#backoffAttempt = 0;
505
+ }, this.#options.healthyAfterMs);
506
+ host.healthyTimer.unref();
507
+ host.lastHeartbeat = this.#options.now();
508
+ this.#send({
509
+ type: "configure",
510
+ protocolVersion: PLUGIN_HOST_PROTOCOL_VERSION,
511
+ productVersion: this.#options.productVersion,
512
+ limits: this.#options.limits,
513
+ });
514
+ const queued = host.outbox.splice(0);
515
+ for (const command of queued)
516
+ this.#send(command);
517
+ return;
518
+ }
519
+ case "heartbeat":
520
+ host.lastHeartbeat = this.#options.now();
521
+ return;
522
+ case "busy":
523
+ host.busy = event.plugin;
524
+ return;
525
+ case "idle":
526
+ if (host.busy === event.plugin)
527
+ host.busy = null;
528
+ host.lastHeartbeat = this.#options.now();
529
+ return;
530
+ case "log":
531
+ this.#log(event.plugin, event.level, event.message, event.fields);
532
+ return;
533
+ case "loaded": {
534
+ const entry = this.#entries.get(event.plugin);
535
+ if (entry && entry.state !== "disabled") {
536
+ entry.state = event.ok ? "loaded" : "failed";
537
+ // Raw here; status() is the one place entries leave the
538
+ // supervisor, and it redacts every error on the way out.
539
+ entry.error = event.ok ? undefined : event.error;
540
+ entry.memoryBytes = event.memoryBytes;
541
+ }
542
+ // A plugin that failed to load keeps nothing running either: not the
543
+ // programs its top-level code or its timers started.
544
+ if (!event.ok)
545
+ this.#stopPrograms(event.plugin);
546
+ this.#settleLoad(event.plugin);
547
+ return;
548
+ }
549
+ case "trip":
550
+ this.#onTrip(event.plugin, event.kind);
551
+ return;
552
+ case "actions": {
553
+ const entry = this.#entries.get(event.plugin);
554
+ if (!entry?.spec || entry.state === "disabled")
555
+ return;
556
+ const problem = this.#actions.publish(event.plugin, event.actions);
557
+ if (problem)
558
+ this.#log(event.plugin, "warn", `ignored its action list: ${problem}`);
559
+ return;
560
+ }
561
+ case "call":
562
+ void this.#onCall(event);
563
+ return;
564
+ case "invoke-result":
565
+ this.#requests.get(event.id)?.(event.ok
566
+ ? { ok: true, text: event.value ?? "[]" }
567
+ : { ok: false, error: event.error ?? "failed" });
568
+ return;
569
+ case "param-options-result":
570
+ this.#requests.get(event.id)?.(event.ok
571
+ ? { ok: true, text: event.options ?? "{}" }
572
+ : { ok: false, error: event.error ?? "failed" });
573
+ return;
574
+ case "run-result": {
575
+ const resolve = this.#runs.get(event.id);
576
+ if (!resolve)
577
+ return;
578
+ let values;
579
+ if (event.values !== undefined) {
580
+ try {
581
+ const parsed = JSON.parse(event.values);
582
+ values = Array.isArray(parsed) ? parsed : [parsed];
583
+ }
584
+ catch {
585
+ values = [];
586
+ }
587
+ }
588
+ if (!event.ok)
589
+ this.#stopPrograms(RUN_STATE_NAME);
590
+ const secrets = this.#secretSet();
591
+ resolve({
592
+ ok: event.ok,
593
+ ...(values ? { values: values.map((value) => redactLogValue(value, secrets)) } : {}),
594
+ ...(event.error ? { error: redactText(event.error, secrets) } : {}),
595
+ logs: event.logs.map((log) => ({ ...log, message: redactText(log.message, secrets) })),
596
+ });
597
+ return;
598
+ }
599
+ }
600
+ }
601
+ async #onCall(event) {
602
+ const reply = (result) => {
603
+ const secrets = this.#secretSet();
604
+ this.#send(result.ok
605
+ ? {
606
+ type: "call-result",
607
+ id: event.id,
608
+ ok: true,
609
+ ...(result.value === undefined
610
+ ? {}
611
+ : { value: JSON.stringify(redactLogValue(result.value, secrets)) }),
612
+ }
613
+ : {
614
+ type: "call-result",
615
+ id: event.id,
616
+ ok: false,
617
+ error: redactText(result.error, secrets),
618
+ });
619
+ };
620
+ const entry = this.#entries.get(event.plugin);
621
+ const capabilities = ownerCapabilities(event.plugin) ??
622
+ (entry?.spec && entry.state !== "disabled" ? entry.spec.capabilities : null);
623
+ if (!capabilities || !this.#options.calls) {
624
+ reply({ ok: false, error: `E_UNAVAILABLE: ${event.method.slice(1)} is not available` });
625
+ return;
626
+ }
627
+ let args;
628
+ try {
629
+ args = JSON.parse(event.args);
630
+ }
631
+ catch {
632
+ args = null;
633
+ }
634
+ if (!Array.isArray(args)) {
635
+ reply({ ok: false, error: "E_INVALID: malformed host call" });
636
+ return;
637
+ }
638
+ // Whether the plugin that made this call may still act: a disable,
639
+ // unload, reload or revoke that lands while the call awaits (say, a tmux
640
+ // lookup before a program starts) stops it from starting anything.
641
+ const host = this.#host;
642
+ const active = () => !this.#stopped &&
643
+ this.#host === host &&
644
+ (event.plugin === RUN_STATE_NAME ||
645
+ (this.#entries.get(event.plugin) === entry &&
646
+ entry !== undefined &&
647
+ entry.state !== "disabled" &&
648
+ entry.state !== "failed"));
649
+ try {
650
+ const value = await this.#options.calls.handle({
651
+ plugin: event.plugin,
652
+ capabilities,
653
+ active,
654
+ ...(event.origin ? { origin: event.origin } : {}),
655
+ }, event.method, args);
656
+ reply({ ok: true, value });
657
+ }
658
+ catch (error) {
659
+ reply({ ok: false, error: error.message });
660
+ }
661
+ }
662
+ #onTrip(plugin, kind) {
663
+ // The callback that tripped failed; its programs go with it.
664
+ this.#stopPrograms(plugin);
665
+ const entry = this.#entries.get(plugin);
666
+ if (!entry)
667
+ return;
668
+ const now = this.#options.now();
669
+ entry.trips = entry.trips.filter((at) => now - at < this.#options.tripWindowMs);
670
+ entry.trips.push(now);
671
+ const label = kind === "timeout"
672
+ ? "ran past its time budget"
673
+ : kind === "memory"
674
+ ? "ran out of memory"
675
+ : "crashed the Lua runtime";
676
+ this.#log(plugin, "warn", `${label} (${entry.trips.length}/${this.#options.tripLimit})`);
677
+ if (kind === "abort" || entry.trips.length >= this.#options.tripLimit) {
678
+ this.#disable(entry, kind === "abort"
679
+ ? "the Lua runtime crashed"
680
+ : `${label} ${entry.trips.length} times within ${Math.round(this.#options.tripWindowMs / 1000)} s`);
681
+ }
682
+ }
683
+ #disable(entry, reason) {
684
+ entry.state = "disabled";
685
+ entry.error = `disabled: ${reason}; run \`tmux-ide plugin reload ${entry.name}\` to try again`;
686
+ this.#log(entry.name, "error", entry.error);
687
+ this.#send({ type: "unload", name: entry.name });
688
+ this.#actions.drop(entry.name);
689
+ // Its programs are already gone: a disable follows a trip (which stops
690
+ // them) or a watchdog kill of the host (which stops every program).
691
+ this.#settleLoad(entry.name);
692
+ }
693
+ /**
694
+ * Kill the programs `plugin` (or, with no name, every plugin) still runs;
695
+ * with `origin`, only those started for that request.
696
+ */
697
+ #stopPrograms(plugin, origin) {
698
+ const killed = this.#options.calls?.stopPrograms(plugin, origin) ?? 0;
699
+ if (killed > 0)
700
+ this.#log(plugin ?? "host", "info", `stopped ${killed} program${killed === 1 ? "" : "s"} it started`);
701
+ }
702
+ #startWatchdog() {
703
+ if (this.#watchdog)
704
+ return;
705
+ this.#watchdog = setInterval(() => {
706
+ const host = this.#host;
707
+ if (!host || !host.ready || host.killedBy)
708
+ return;
709
+ const silentFor = this.#options.now() - host.lastHeartbeat;
710
+ if (silentFor <= this.#options.heartbeatTimeoutMs)
711
+ return;
712
+ const culprit = host.busy;
713
+ host.killedBy = culprit
714
+ ? `${culprit} kept the plugin host busy for more than ${Math.round(this.#options.heartbeatTimeoutMs / 1000)} s`
715
+ : "the plugin host stopped responding";
716
+ this.#log("host", "error", `watchdog: ${host.killedBy}; restarting the host`);
717
+ const entry = culprit ? this.#entries.get(culprit) : undefined;
718
+ if (culprit === RUN_STATE_NAME) {
719
+ // A one-off `lua run` was busy: its own result already fails; no
720
+ // plugin is to blame, so none is charged.
721
+ }
722
+ else if (entry) {
723
+ this.#disable(entry, "the watchdog stopped it: it did not return control for more than 5 s");
724
+ }
725
+ else {
726
+ // No Lua slice was running, so no busy marker names a culprit. Charge
727
+ // what the host was doing for us: the plugin it was loading (loads run
728
+ // one at a time, in send order). Repeated kills then end in a disable
729
+ // instead of a restart loop.
730
+ const loading = [...this.#entries.values()].find((candidate) => candidate.state === "loading");
731
+ if (loading)
732
+ this.#onTrip(loading.name, "timeout");
733
+ }
734
+ host.child.kill("SIGKILL");
735
+ }, this.#options.watchdogIntervalMs);
736
+ this.#watchdog.unref();
737
+ }
738
+ #stopWatchdog() {
739
+ if (this.#watchdog)
740
+ clearInterval(this.#watchdog);
741
+ this.#watchdog = null;
742
+ }
743
+ #failRuns(error) {
744
+ for (const resolve of [...this.#runs.values()])
745
+ resolve({ ok: false, error, logs: [] });
746
+ this.#runs.clear();
747
+ for (const resolve of [...this.#requests.values()])
748
+ resolve({ ok: false, error });
749
+ this.#requests.clear();
750
+ // Plugins publish their actions again when the host loads them.
751
+ this.#actions.clear();
752
+ // No callback survives the host, so neither do the programs they started.
753
+ this.#stopPrograms();
754
+ }
755
+ #onExit(host, code, signal) {
756
+ if (host.healthyTimer)
757
+ clearTimeout(host.healthyTimer);
758
+ if (this.#host !== host)
759
+ return;
760
+ this.#host = null;
761
+ this.#stopWatchdog();
762
+ this.#failRuns(`E_UNAVAILABLE: the plugin host exited (${host.killedBy ?? signal ?? `code ${code}`})`);
763
+ for (const name of [...this.#loadWaiters.keys()])
764
+ this.#settleLoad(name);
765
+ if (this.#stopped)
766
+ return;
767
+ const pending = [...this.#entries.values()].filter((entry) => entry.spec && entry.state !== "disabled");
768
+ if (pending.length === 0)
769
+ return;
770
+ if (!host.killedBy)
771
+ this.#log("host", "error", `plugin host exited (${signal ?? `code ${code}`}); restarting`);
772
+ for (const entry of pending)
773
+ entry.state = "loading";
774
+ const delay = this.#options.restartDelayMs(this.#backoffAttempt);
775
+ this.#backoffAttempt += 1;
776
+ this.#restarts += 1;
777
+ this.#restartTimer = setTimeout(() => {
778
+ this.#restartTimer = null;
779
+ if (this.#stopped || this.#host)
780
+ return;
781
+ const again = [...this.#entries.values()].filter((entry) => entry.spec && entry.state === "loading");
782
+ if (again.length === 0)
783
+ return;
784
+ this.#spawn();
785
+ for (const entry of again)
786
+ this.#send({ type: "load", plugin: entry.spec });
787
+ }, delay);
788
+ this.#restartTimer.unref();
789
+ }
790
+ }