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,326 @@
1
+ /**
2
+ * `ide.exec`: a plugin runs a program, on the daemon's side of the wire.
3
+ *
4
+ * - Only programs the plugin's manifest lists under `capabilities.exec`, and
5
+ * that the owner consented to. A bare program name, looked up on the
6
+ * daemon's own PATH (absolute entries only), never on one the plugin sets.
7
+ * - No shell unless the plugin asks for `shell = true`, which needs the
8
+ * manifest's `capabilities.shell` (shown at consent as "any command").
9
+ * - A minimal environment, never the daemon's; a plugin may add only
10
+ * locale, terminal and colour variables and its own `PLUGIN_*` ones, so it
11
+ * cannot change PATH or inject a library (DYLD_*, LD_*) or interpreter
12
+ * option (NODE_OPTIONS, PYTHONPATH, GIT_*, …).
13
+ * - With `context = "%N"` the program runs as if typed in that tmux pane
14
+ * (its cwd, TMUX and TMUX_PANE); that needs the `panes.send` capability.
15
+ * - Inside the OS sandbox (exec-sandbox.ts), with a timeout that kills the
16
+ * whole process group, capped at the callback's wall clock, and a cap on
17
+ * captured output. The daemon also kills a plugin's programs when the
18
+ * plugin fails, unloads, is disabled or loses consent.
19
+ * - Output is redacted before it goes back to Lua.
20
+ */
21
+ import { spawn as nodeSpawn, type ChildProcess } from "node:child_process";
22
+ import { existsSync, statSync } from "node:fs";
23
+ import { isAbsolute } from "node:path";
24
+ import { z } from "zod";
25
+ import { redactText } from "../lib/log-sanitize.ts";
26
+ import { findOnPath, sandboxedArgv, type SandboxPlan, type SandboxPaths } from "./exec-sandbox.ts";
27
+ import { ensureRealDirectory } from "./safe-files.ts";
28
+
29
+ export const EXEC_DEFAULT_TIMEOUT_MS = 30_000;
30
+ export const EXEC_MAX_TIMEOUT_MS = 600_000;
31
+ export const EXEC_OUTPUT_CAP_BYTES = 1024 * 1024;
32
+
33
+ const PROGRAM_NAME = /^[\w.+-]{1,64}$/u;
34
+ const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/u;
35
+
36
+ /**
37
+ * The variables a plugin may set for a program it runs. Everything else
38
+ * could change what runs (PATH, DYLD_INSERT_LIBRARIES, LD_PRELOAD,
39
+ * NODE_OPTIONS, PYTHONPATH, GIT_SSH_COMMAND, BASH_ENV, …) and is refused.
40
+ */
41
+ const ALLOWED_ENV =
42
+ /^(?:LANG|LANGUAGE|LC_[A-Z]+|TZ|TERM|COLORTERM|NO_COLOR|FORCE_COLOR|CLICOLOR|CLICOLOR_FORCE|COLUMNS|LINES|PLUGIN_[A-Z0-9_]+)$/u;
43
+
44
+ export const ExecRequestSchemaZ = z
45
+ .object({
46
+ cmd: z
47
+ .string()
48
+ .min(1)
49
+ .max(64 * 1024),
50
+ args: z
51
+ .array(z.string().max(64 * 1024))
52
+ .max(256)
53
+ .default([]),
54
+ cwd: z.string().min(1).max(4096).optional(),
55
+ env: z.record(z.string().regex(ENV_NAME), z.string().max(64 * 1024)).optional(),
56
+ stdin: z
57
+ .string()
58
+ .max(1024 * 1024)
59
+ .optional(),
60
+ timeout_ms: z.number().int().min(1).max(EXEC_MAX_TIMEOUT_MS).optional(),
61
+ /** A tmux pane id like `%12`: run as if typed there. */
62
+ context: z
63
+ .string()
64
+ .regex(
65
+ /^%\d{1,9}$/u,
66
+ "must be a tmux pane id like %3; ctx.pane is set only when the caller knows one",
67
+ )
68
+ .optional(),
69
+ shell: z.boolean().optional(),
70
+ })
71
+ .strict();
72
+ export type ExecRequest = z.infer<typeof ExecRequestSchemaZ>;
73
+
74
+ export interface ExecResult {
75
+ readonly code: number | null;
76
+ readonly signal: string | null;
77
+ readonly stdout: string;
78
+ readonly stderr: string;
79
+ readonly timed_out: boolean;
80
+ readonly truncated: boolean;
81
+ }
82
+
83
+ export interface ExecPolicy {
84
+ /** Program names the plugin may run, or "any" (init.lua and `lua run`). */
85
+ readonly programs: readonly string[] | "any";
86
+ readonly shell: boolean;
87
+ /** May run a program as if typed in a pane (`context`): `panes.send`. */
88
+ readonly panes: boolean;
89
+ }
90
+
91
+ export interface PaneContext {
92
+ /** Value for $TMUX: `<socket>,<server pid>,<session index>`. */
93
+ readonly tmux: string;
94
+ readonly pane: string;
95
+ readonly cwd: string;
96
+ }
97
+
98
+ export interface ExecDependencies {
99
+ readonly policy: ExecPolicy;
100
+ readonly sandbox: SandboxPaths;
101
+ /** The environment programs start from (already minimal). */
102
+ readonly baseEnv: NodeJS.ProcessEnv;
103
+ readonly resolvePane: (pane: string) => Promise<PaneContext | null>;
104
+ readonly secrets: () => ReadonlySet<string>;
105
+ readonly plan?: (command: readonly string[], paths: SandboxPaths) => SandboxPlan;
106
+ readonly spawn?: typeof nodeSpawn;
107
+ /** The longest a program may run: the callback's wall clock. */
108
+ readonly maxTimeoutMs?: number;
109
+ /**
110
+ * Asked right before the program starts, after every await: false when
111
+ * the plugin was disabled, unloaded or revoked meanwhile.
112
+ */
113
+ readonly stillAllowed?: () => boolean;
114
+ /** Told about each started program; returns the call that forgets it. */
115
+ readonly track?: (child: ChildProcess) => () => void;
116
+ }
117
+
118
+ export class ExecError extends Error {}
119
+
120
+ function fail(message: string): never {
121
+ throw new ExecError(message);
122
+ }
123
+
124
+ /** Validate the request and work out the argv, cwd and environment. */
125
+ export async function prepareExec(raw: unknown, deps: ExecDependencies) {
126
+ const parsed = ExecRequestSchemaZ.safeParse(raw);
127
+ if (!parsed.success) {
128
+ const issue = parsed.error.issues[0];
129
+ fail(
130
+ `E_INVALID: ide.exec ${issue?.path.join(".") || "request"}: ${issue?.message ?? "invalid"}`,
131
+ );
132
+ }
133
+ const request = parsed.data;
134
+ const env: NodeJS.ProcessEnv = { ...deps.baseEnv };
135
+ for (const [key, value] of Object.entries(request.env ?? {})) {
136
+ if (!ALLOWED_ENV.test(key))
137
+ fail(
138
+ `E_DENIED: ide.exec may not set ${key}; plugins may set LANG, LC_*, TZ, TERM, colour variables, COLUMNS, LINES and PLUGIN_*`,
139
+ );
140
+ env[key] = value;
141
+ }
142
+
143
+ let command: string[];
144
+ if (request.shell) {
145
+ if (!deps.policy.shell)
146
+ fail("E_DENIED: this plugin may not run shell commands (manifest capability 'shell')");
147
+ command = ["/bin/sh", "-c", request.cmd, "sh", ...request.args];
148
+ } else {
149
+ if (!PROGRAM_NAME.test(request.cmd))
150
+ fail("E_INVALID: ide.exec cmd must be a program name like 'git', not a path or command line");
151
+ if (deps.policy.programs !== "any" && !deps.policy.programs.includes(request.cmd))
152
+ fail(`E_DENIED: this plugin may not run '${request.cmd}' (manifest capability 'exec')`);
153
+ // The daemon's PATH, never one from the request.
154
+ const resolved = findOnPath(request.cmd, deps.baseEnv.PATH ?? "");
155
+ if (!resolved) fail(`E_NOT_FOUND: '${request.cmd}' is not on PATH`);
156
+ command = [resolved, ...request.args];
157
+ }
158
+
159
+ // Without panes.send a program gets no hint where the tmux server is (and
160
+ // the sandbox keeps it from the socket directories anyway).
161
+ if (!deps.policy.panes) delete env.TMUX_TMPDIR;
162
+
163
+ let cwd = env.HOME ?? "/";
164
+ if (request.context) {
165
+ if (!deps.policy.panes)
166
+ fail(
167
+ "E_DENIED: running a program in a pane (context) needs the manifest capability 'panes.send'",
168
+ );
169
+ const pane = await deps.resolvePane(request.context);
170
+ if (!pane) fail(`E_NOT_FOUND: no tmux pane ${request.context}`);
171
+ env.TMUX = pane.tmux;
172
+ env.TMUX_PANE = pane.pane;
173
+ cwd = pane.cwd;
174
+ }
175
+ if (request.cwd !== undefined) {
176
+ if (!isAbsolute(request.cwd)) fail("E_INVALID: ide.exec cwd must be an absolute path");
177
+ cwd = request.cwd;
178
+ }
179
+ if (!existsSync(cwd) || !statSync(cwd).isDirectory())
180
+ fail(`E_NOT_FOUND: ide.exec cwd ${cwd} is not a directory`);
181
+
182
+ try {
183
+ ensureRealDirectory(deps.sandbox.writable);
184
+ } catch (error) {
185
+ fail(`E_UNAVAILABLE: the plugin's data directory is unusable: ${(error as Error).message}`);
186
+ }
187
+ const plan = (deps.plan ?? sandboxedArgv)(command, deps.sandbox);
188
+ if (!plan.ok) fail(`E_UNAVAILABLE: ${plan.reason}`);
189
+ return {
190
+ argv: plan.argv,
191
+ cwd,
192
+ env,
193
+ stdin: request.stdin,
194
+ timeoutMs: Math.min(
195
+ request.timeout_ms ?? EXEC_DEFAULT_TIMEOUT_MS,
196
+ deps.maxTimeoutMs ?? EXEC_MAX_TIMEOUT_MS,
197
+ ),
198
+ };
199
+ }
200
+
201
+ class Capture {
202
+ readonly #chunks: Buffer[] = [];
203
+ #bytes = 0;
204
+ truncated = false;
205
+ add(chunk: Buffer): void {
206
+ const room = EXEC_OUTPUT_CAP_BYTES - this.#bytes;
207
+ if (room <= 0) {
208
+ this.truncated = true;
209
+ return;
210
+ }
211
+ const kept = chunk.length > room ? chunk.subarray(0, room) : chunk;
212
+ if (kept.length < chunk.length) this.truncated = true;
213
+ this.#chunks.push(kept);
214
+ this.#bytes += kept.length;
215
+ }
216
+ text(): string {
217
+ return Buffer.concat(this.#chunks).toString("utf8");
218
+ }
219
+ }
220
+
221
+ /** Kill `child` and everything it started (it leads its own process group). */
222
+ export function killGroup(child: ChildProcess): void {
223
+ if (child.pid === undefined) return;
224
+ try {
225
+ process.kill(-child.pid, "SIGKILL");
226
+ } catch {
227
+ child.kill("SIGKILL");
228
+ }
229
+ }
230
+
231
+ export async function runPluginExec(raw: unknown, deps: ExecDependencies): Promise<ExecResult> {
232
+ const prepared = await prepareExec(raw, deps);
233
+ if (deps.stillAllowed && !deps.stillAllowed())
234
+ throw new ExecError("E_UNAVAILABLE: the plugin was stopped before its program started");
235
+ const spawn = deps.spawn ?? nodeSpawn;
236
+ const [file, ...args] = prepared.argv;
237
+ return new Promise<ExecResult>((resolve, reject) => {
238
+ let child: ChildProcess;
239
+ try {
240
+ child = spawn(file!, args, {
241
+ cwd: prepared.cwd,
242
+ env: prepared.env,
243
+ stdio: ["pipe", "pipe", "pipe"],
244
+ // Its own process group, so a timeout kills everything it started.
245
+ detached: true,
246
+ });
247
+ } catch (error) {
248
+ reject(
249
+ new ExecError(`E_UNAVAILABLE: could not start the program: ${(error as Error).message}`),
250
+ );
251
+ return;
252
+ }
253
+ const forget = deps.track?.(child) ?? (() => {});
254
+ const stdout = new Capture();
255
+ const stderr = new Capture();
256
+ let timedOut = false;
257
+ const timer = setTimeout(() => {
258
+ timedOut = true;
259
+ killGroup(child);
260
+ }, prepared.timeoutMs);
261
+ child.stdout?.on("data", (chunk: Buffer) => stdout.add(chunk));
262
+ child.stderr?.on("data", (chunk: Buffer) => stderr.add(chunk));
263
+ child.stdin?.on("error", () => {});
264
+ child.on("error", (error) => {
265
+ clearTimeout(timer);
266
+ forget();
267
+ reject(new ExecError(`E_UNAVAILABLE: could not start the program: ${error.message}`));
268
+ });
269
+ child.on("close", (code, signal) => {
270
+ clearTimeout(timer);
271
+ forget();
272
+ const secrets = deps.secrets();
273
+ resolve({
274
+ code,
275
+ signal,
276
+ stdout: redactText(stdout.text(), secrets),
277
+ stderr: redactText(stderr.text(), secrets),
278
+ timed_out: timedOut,
279
+ truncated: stdout.truncated || stderr.truncated,
280
+ });
281
+ });
282
+ child.stdin?.end(prepared.stdin ?? "");
283
+ });
284
+ }
285
+
286
+ /** Programs plugins started and that still run, by plugin. */
287
+ export class PluginPrograms {
288
+ readonly #byPlugin = new Map<string, Map<ChildProcess, string | undefined>>();
289
+
290
+ /**
291
+ * Remember `child` as `plugin`'s, started for request `origin` (or by a
292
+ * timer or load when there is none); returns the call that forgets it.
293
+ */
294
+ track(plugin: string, child: ChildProcess, origin?: string): () => void {
295
+ let running = this.#byPlugin.get(plugin);
296
+ if (!running) this.#byPlugin.set(plugin, (running = new Map()));
297
+ running.set(child, origin);
298
+ return () => {
299
+ running.delete(child);
300
+ if (running.size === 0 && this.#byPlugin.get(plugin) === running)
301
+ this.#byPlugin.delete(plugin);
302
+ };
303
+ }
304
+
305
+ /**
306
+ * Kill `plugin`'s programs, or every plugin's; with `origin`, only the ones
307
+ * started for that request. Returns how many.
308
+ */
309
+ kill(plugin?: string, origin?: string): number {
310
+ const groups =
311
+ plugin === undefined ? [...this.#byPlugin.values()] : [this.#byPlugin.get(plugin)];
312
+ let killed = 0;
313
+ for (const running of groups) {
314
+ for (const [child, started] of running ?? []) {
315
+ if (origin !== undefined && started !== origin) continue;
316
+ killGroup(child);
317
+ killed += 1;
318
+ }
319
+ }
320
+ return killed;
321
+ }
322
+
323
+ running(plugin: string): number {
324
+ return this.#byPlugin.get(plugin)?.size ?? 0;
325
+ }
326
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * `<state home>/logs/plugins.log`: one JSON line per plugin log entry, with
3
+ * the same one-generation rotation as the fleet events log.
4
+ */
5
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, statSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
7
+ import type { PluginLogLevel } from "./protocol.ts";
8
+
9
+ export const PLUGIN_LOG_MAX_BYTES = 1024 * 1024;
10
+
11
+ export interface PluginLogEntry {
12
+ readonly ts: string;
13
+ readonly plugin: string;
14
+ readonly level: PluginLogLevel;
15
+ readonly message: string;
16
+ readonly fields?: Record<string, unknown>;
17
+ }
18
+
19
+ export function pluginLogPath(stateHome: string): string {
20
+ return join(stateHome, "logs", "plugins.log");
21
+ }
22
+
23
+ export function appendPluginLog(path: string, entry: PluginLogEntry): void {
24
+ try {
25
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
26
+ if (existsSync(path) && statSync(path).size > PLUGIN_LOG_MAX_BYTES) {
27
+ renameSync(path, `${path}.1`);
28
+ }
29
+ appendFileSync(path, `${JSON.stringify(entry)}\n`, { mode: 0o600 });
30
+ } catch {
31
+ // A lost log line is never fatal to the daemon.
32
+ }
33
+ }
34
+
35
+ /** The last `limit` entries, oldest first, optionally for one plugin. */
36
+ export function readPluginLog(path: string, options: { limit?: number; plugin?: string } = {}) {
37
+ const limit = options.limit ?? 200;
38
+ const out: PluginLogEntry[] = [];
39
+ for (const file of [`${path}.1`, path]) {
40
+ let text: string;
41
+ try {
42
+ text = readFileSync(file, "utf8");
43
+ } catch {
44
+ continue;
45
+ }
46
+ for (const line of text.split("\n")) {
47
+ if (!line) continue;
48
+ try {
49
+ const entry = JSON.parse(line) as PluginLogEntry;
50
+ if (!options.plugin || entry.plugin === options.plugin) out.push(entry);
51
+ } catch {
52
+ // Skip a torn line.
53
+ }
54
+ }
55
+ }
56
+ return out.slice(-limit);
57
+ }
58
+
59
+ export function formatPluginLogEntry(entry: PluginLogEntry): string {
60
+ const time = /T(\d{2}:\d{2}:\d{2})/u.exec(entry.ts)?.[1] ?? entry.ts;
61
+ const fields = entry.fields ? ` ${JSON.stringify(entry.fields)}` : "";
62
+ return `${time} ${entry.plugin} ${entry.level.padEnd(5)} ${entry.message}${fields}`;
63
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * `ide.store`: a small JSON key/value store per plugin, kept in
3
+ * `<state>/plugin-store/<plugin>.json`. That is outside the plugin's data
4
+ * directory on purpose: programs a plugin runs can write there, and the
5
+ * daemon must never read or write through anything they planted.
6
+ *
7
+ * Reads refuse symlinks, non-regular files and files over the cap; writes
8
+ * go to a fresh randomly named file and are renamed into place.
9
+ */
10
+ import { join } from "node:path";
11
+ import { toPlainJson } from "./host/lua-state.ts";
12
+ import { readRegularFile, UnsafeFileError, writeFileAtomic } from "./safe-files.ts";
13
+
14
+ export const STORE_MAX_BYTES = 1024 * 1024;
15
+ export const STORE_MAX_KEYS = 1000;
16
+
17
+ export class PluginStoreError extends Error {}
18
+
19
+ /** Where `plugin`'s store lives. */
20
+ export function pluginStorePath(stateHome: string, plugin: string): string {
21
+ return join(stateHome, "plugin-store", `${plugin}.json`);
22
+ }
23
+
24
+ export class PluginStore {
25
+ readonly #path: string;
26
+
27
+ constructor(path: string) {
28
+ this.#path = path;
29
+ }
30
+
31
+ #read(): Record<string, unknown> {
32
+ let text: string | null;
33
+ try {
34
+ text = readRegularFile(this.#path, STORE_MAX_BYTES);
35
+ } catch (error) {
36
+ if (error instanceof UnsafeFileError)
37
+ throw new PluginStoreError(`E_FAILED: the store file is unusable (${error.message})`);
38
+ throw error;
39
+ }
40
+ if (text === null) return {};
41
+ try {
42
+ const parsed: unknown = JSON.parse(text);
43
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed)
44
+ ? (parsed as Record<string, unknown>)
45
+ : {};
46
+ } catch {
47
+ return {};
48
+ }
49
+ }
50
+
51
+ get(key: string): unknown {
52
+ const data = this.#read();
53
+ return Object.hasOwn(data, key) ? data[key] : null;
54
+ }
55
+
56
+ keys(): string[] {
57
+ return Object.keys(this.#read()).sort();
58
+ }
59
+
60
+ /** Set `key`; `null` or `undefined` deletes it. */
61
+ set(key: string, value: unknown): void {
62
+ const data = this.#read();
63
+ if (value === null || value === undefined) {
64
+ delete data[key];
65
+ } else {
66
+ const plain = toPlainJson(value);
67
+ if (!plain.ok)
68
+ throw new PluginStoreError(
69
+ plain.error.replace("a host function returned", "the store got"),
70
+ );
71
+ data[key] = plain.value;
72
+ if (Object.keys(data).length > STORE_MAX_KEYS)
73
+ throw new PluginStoreError(`E_LIMIT: the store holds at most ${STORE_MAX_KEYS} keys`);
74
+ }
75
+ const text = JSON.stringify(data);
76
+ if (Buffer.byteLength(text, "utf8") > STORE_MAX_BYTES)
77
+ throw new PluginStoreError("E_LIMIT: the store may hold at most 1 MiB");
78
+ writeFileAtomic(this.#path, text);
79
+ }
80
+ }