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