@misakacloud/openchamber-mux 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,1252 @@
1
+ // ../mux-core/src/backend.ts
2
+ import { spawn } from "node:child_process";
3
+ function createCommandRunner() {
4
+ return (executable, args, { cwd, env, signal, timeoutMs } = {}) => new Promise((resolve, reject) => {
5
+ const child = spawn(executable, args, {
6
+ cwd,
7
+ env,
8
+ signal,
9
+ timeout: timeoutMs,
10
+ killSignal: "SIGKILL",
11
+ stdio: ["ignore", "pipe", "pipe"],
12
+ windowsHide: true
13
+ });
14
+ let stdout = "";
15
+ let stderr = "";
16
+ child.stdout.setEncoding("utf8").on("data", (chunk) => {
17
+ stdout += chunk;
18
+ });
19
+ child.stderr.setEncoding("utf8").on("data", (chunk) => {
20
+ stderr += chunk;
21
+ });
22
+ let error;
23
+ child.once("error", (cause) => {
24
+ error = cause;
25
+ });
26
+ child.once("close", (exitCode, exitSignal) => {
27
+ if (error)
28
+ reject(error);
29
+ else
30
+ resolve({ exitCode, stdout, stderr, signal: exitSignal ?? undefined });
31
+ });
32
+ });
33
+ }
34
+ async function detectMuxBackend({
35
+ runner = createCommandRunner(),
36
+ platform = process.platform,
37
+ preferred,
38
+ socketName
39
+ } = {}) {
40
+ const fallback = platform === "win32" ? ["psmux", "tmux"] : ["tmux", "psmux"];
41
+ const kinds = preferred ? [preferred, ...fallback.filter((kind) => kind !== preferred)] : fallback;
42
+ for (const kind of kinds) {
43
+ try {
44
+ if ((await runner(kind, ["-V"], { timeoutMs: 2000 })).exitCode === 0) {
45
+ return { kind, executable: kind, platform, socketName };
46
+ }
47
+ } catch (error) {
48
+ const code = error.code;
49
+ if (code !== "ENOENT" && code !== "EACCES")
50
+ throw error;
51
+ }
52
+ }
53
+ return null;
54
+ }
55
+ function quotePosixShell(value) {
56
+ return `'${value.replaceAll("'", "'\\''")}'`;
57
+ }
58
+ function muxCommandArgs(backend, args) {
59
+ return backend.socketName ? ["-L", backend.socketName, ...args] : [...args];
60
+ }
61
+ function useCmd(backend) {
62
+ return (backend.platform ?? process.platform) === "win32" || backend.kind === "psmux";
63
+ }
64
+ function supportsPosixMuxFeatures(backend) {
65
+ return !useCmd(backend);
66
+ }
67
+ function quoteCmdArg(value) {
68
+ if (/["%\r\n\0]/.test(value))
69
+ throw new Error("Unsupported character in cmd.exe argument");
70
+ return `"${value.replace(/\\+$/, "$&$&")}"`;
71
+ }
72
+ function wrapShellCommand(backend, command, channel, exitFilePrefix) {
73
+ const direct = command.endsWith(";") ? `${command}${useCmd(backend) ? " " : `
74
+ `}` : command;
75
+ const executable = backend.executable ?? backend.kind;
76
+ if (exitFilePrefix && supportsPosixMuxFeatures(backend)) {
77
+ const signal = channel ? `${[executable, ...muxCommandArgs(backend, ["wait-for", "-S", channel])].map(quotePosixShell).join(" ")} 2>/dev/null; ` : "";
78
+ return [
79
+ "sh",
80
+ "-lc",
81
+ `trap ':' INT; sh -lc ${quotePosixShell(command)}; __rc=$?; ` + `__oc_exit=${quotePosixShell(exitFilePrefix)}$$.txt; ` + 'if __oc_tmp=$(mktemp "${__oc_exit}.XXXXXX"); then ' + `if ! { printf '%s\\n' "$__rc" > "$__oc_tmp" && mv -f "$__oc_tmp" "$__oc_exit"; }; then rm -f "$__oc_tmp"; fi; fi; ` + signal + 'if [ -n "$SHELL" ] && [ -x "$SHELL" ]; then exec "$SHELL" -i; ' + "elif [ -x /bin/bash ]; then exec /bin/bash -i; else exec /bin/sh -i; fi"
82
+ ];
83
+ }
84
+ if (!channel)
85
+ return useCmd(backend) ? ["cmd.exe", "/d", "/c", direct] : ["sh", "-lc", direct];
86
+ const args = muxCommandArgs(backend, ["wait-for", "-S", channel]);
87
+ if (useCmd(backend)) {
88
+ if (/["%!^\r\n]/.test(command) || [executable, ...args].some((arg) => /["%!\r\n\0]/.test(arg))) {
89
+ return ["cmd.exe", "/d", "/c", direct];
90
+ }
91
+ const signal = [executable, ...args].map(quoteCmdArg).join(" ");
92
+ return [
93
+ "cmd.exe",
94
+ "/d",
95
+ "/v:on",
96
+ "/c",
97
+ `cmd.exe /d /v:off /s /c "${command}" & set "__oc_rc=!errorlevel!" & ${signal} & exit /b !__oc_rc!`
98
+ ];
99
+ }
100
+ const signal = [executable, ...args].map(quotePosixShell).join(" ");
101
+ return ["sh", "-lc", `sh -lc ${quotePosixShell(command)}; __rc=$?; ${signal}; exit "$__rc"`];
102
+ }
103
+ function buildAttachCommand(backend, sessionName) {
104
+ const executable = backend.executable ?? backend.kind;
105
+ const args = muxCommandArgs(backend, ["attach-session", "-t", `=${sessionName}`]);
106
+ if (useCmd(backend)) {
107
+ return `cmd.exe /d /v:off /s /c "${[executable, ...args].map(quoteCmdArg).join(" ")}"`;
108
+ }
109
+ return [executable, ...args].map(quotePosixShell).join(" ");
110
+ }
111
+ function stripAnsi(text) {
112
+ return text.replace(/(?:\x1b\]|\x9d)[^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)/g, "").replace(/(?:\x1b[P^_X]|[\x90\x98\x9e\x9f])[^\x1b\x9c]*(?:\x1b\\|\x9c)/g, "").replace(/(?:\x1b\[|\x9b)[0-?]*[ -/]*[@-~]|\x1b[ -/]*[@-_]/g, "");
113
+ }
114
+ // ../mux-core/src/tmux.ts
115
+ import { mkdtemp, rm, writeFile } from "node:fs/promises";
116
+ import { tmpdir } from "node:os";
117
+ import { join } from "node:path";
118
+ var OPTIONS = {
119
+ managed: "@opencode_mux_managed",
120
+ id: "@opencode_mux_id",
121
+ role: "@opencode_mux_role",
122
+ name: "@opencode_mux_name",
123
+ session: "@opencode_mux_session",
124
+ dir: "@opencode_mux_dir",
125
+ cmd: "@opencode_mux_cmd"
126
+ };
127
+ var cleanupHookName = "pane-died[100]";
128
+ var cleanupHook = 'if-shell -F "#{pane_dead}" "kill-pane"';
129
+ var byobuTable = "mux-byobu";
130
+ var themeHook = "after-new-window[mux-theme]";
131
+ var mouseKey = /^(?:[CMS]-)*(?:Mouse|Wheel|DoubleClick|TripleClick)\S*$/;
132
+ var keyBinding = /^(bind-key\s+(?:-r\s+)?-T\s+)(\S+)(\s+(\S+)\s+\S.*)$/;
133
+ function mouseBindings(stdout, table) {
134
+ return stdout.split(/\r?\n/).flatMap((line) => {
135
+ const match = keyBinding.exec(line);
136
+ return match && match[2] === table && mouseKey.test(match[4]) ? [`${match[1]}${byobuTable}${match[3]}`] : [];
137
+ });
138
+ }
139
+ var fallbackMouseBindings = [
140
+ ["MouseDown1Status", "switch-client -t ="],
141
+ ["WheelUpStatus", "previous-window"],
142
+ ["WheelDownStatus", "next-window"],
143
+ ["MouseDown1Pane", "select-pane -t = ; send-keys -M"],
144
+ ["WheelUpPane", 'if-shell -F "#{||:#{alternate_on},#{pane_in_mode},#{mouse_any_flag}}" { send-keys -M } { copy-mode -e }'],
145
+ ["WheelDownPane", 'if-shell -F "#{||:#{pane_in_mode},#{mouse_any_flag}}" "send-keys -M"'],
146
+ ["MouseDrag1Pane", 'if-shell -F "#{||:#{pane_in_mode},#{mouse_any_flag}}" { send-keys -M } { copy-mode -M }'],
147
+ ["MouseDrag1Border", "resize-pane -M"]
148
+ ];
149
+ function sessionThemeOptions(ascii) {
150
+ return [
151
+ ["status", "on"],
152
+ ["status-position", "bottom"],
153
+ ["status-interval", "1"],
154
+ ["status-justify", "left"],
155
+ ["status-style", "bg=#333333,fg=#eeeeee"],
156
+ ["status-left-style", "default"],
157
+ ["status-left-length", "16"],
158
+ ["status-left", ascii ? "#[bg=#5faf5f,fg=#1c1c1c,bold] mux #[default] " : "#[bg=#5faf5f,fg=#1c1c1c,bold] mux #[bg=#333333,fg=#5faf5f,nobold]#[default] "],
159
+ ["status-right-style", "default"],
160
+ ["status-right-length", "96"],
161
+ ["status-right", ascii ? "#S + %Y-%m-%d + %H:%M:%S" : "#[bg=#333333,fg=#4e4e4e]#[bg=#4e4e4e,fg=#eeeeee] #S #[bg=#4e4e4e,fg=#1c1c1c]#[bg=#1c1c1c,fg=#b8b8b8] %Y-%m-%d #[fg=#eeeeee,bold]%H:%M:%S #[default]"],
162
+ ["mouse", "on"],
163
+ ["renumber-windows", "on"],
164
+ ["visual-activity", "off"],
165
+ ["message-style", "bg=#75507b,fg=#eeeeee,bold"],
166
+ ["message-command-style", "bg=#333333,fg=#87d75f,bold"]
167
+ ];
168
+ }
169
+ function windowThemeOptions(ascii) {
170
+ const compact = " #I:#W#{?window_flags,#{window_flags},} ";
171
+ return [
172
+ ["window-status-style", "bg=#333333,fg=#b8b8b8"],
173
+ ["window-status-current-style", "bg=#eeeeee,fg=#1c1c1c,bold"],
174
+ ["window-status-activity-style", "bg=#333333,fg=#87d75f,bold"],
175
+ ["window-status-bell-style", "bg=#dd4814,fg=#eeeeee,bold"],
176
+ ["window-status-separator", " "],
177
+ ["window-status-format", ascii ? compact : " #I #W#{?window_flags,#{window_flags},} "],
178
+ ["window-status-current-format", ascii ? compact : "#[bg=#eeeeee,fg=#333333,nobold]#[fg=#1c1c1c,bold] #I #W#{?window_flags,#{window_flags},} #[bg=#333333,fg=#eeeeee,nobold]"],
179
+ ["pane-border-style", "fg=#4e4e4e"],
180
+ ["pane-active-border-style", "fg=#5faf5f"],
181
+ ["mode-style", "bg=#75507b,fg=#eeeeee"],
182
+ ["monitor-activity", "on"]
183
+ ];
184
+ }
185
+ var commandList = (commands) => commands.flatMap((command, index) => index ? [";", ...command] : command);
186
+ var separator = "\x1F";
187
+ var paneFormat = [
188
+ "session_name",
189
+ "window_index",
190
+ "window_name",
191
+ "pane_id",
192
+ "pane_pid",
193
+ "pane_current_path",
194
+ "pane_current_command",
195
+ "pane_dead",
196
+ "pane_dead_status",
197
+ "pane_dead_signal",
198
+ ...Object.values(OPTIONS),
199
+ "pane_title"
200
+ ].map((field) => `#{${field}}`).join(separator);
201
+ function numberField(value) {
202
+ return /^-?\d+$/.test(value) ? Number(value) : undefined;
203
+ }
204
+ var encodedPrefix = "opencode-b64:";
205
+ function encodeField(value) {
206
+ return /[\r\n\x1f]|;$/.test(value) || value.startsWith(encodedPrefix) ? encodedPrefix + Buffer.from(value).toString("base64") : value;
207
+ }
208
+ function decodeField(value) {
209
+ return value.startsWith(encodedPrefix) ? Buffer.from(value.slice(encodedPrefix.length), "base64").toString() : value || undefined;
210
+ }
211
+ function parsePanes(stdout) {
212
+ return stdout.split(/\r?\n/).flatMap((line) => {
213
+ const fields = line.split(separator);
214
+ if (fields.length < 18 || !/^%\d+$/.test(fields[3]))
215
+ return [];
216
+ const [
217
+ sessionName,
218
+ index,
219
+ windowName,
220
+ paneId,
221
+ pid,
222
+ paneCurrentPath,
223
+ paneCurrentCommand,
224
+ dead,
225
+ status,
226
+ signal,
227
+ managed,
228
+ taskId,
229
+ role,
230
+ name,
231
+ sessionId,
232
+ cwd,
233
+ command,
234
+ ...title
235
+ ] = fields;
236
+ const signum = numberField(signal);
237
+ return [{
238
+ sessionName,
239
+ windowIndex: Number(index),
240
+ windowName,
241
+ paneId,
242
+ panePid: numberField(pid),
243
+ paneCurrentPath,
244
+ paneCurrentCommand,
245
+ paneDead: dead === "1",
246
+ exitCode: dead === "1" ? numberField(status) ?? (signum ? 128 + signum : undefined) : undefined,
247
+ paneTitle: title.join(separator),
248
+ managed: managed === "1",
249
+ taskId: decodeField(taskId),
250
+ role: role === "build" || role === "service" ? role : undefined,
251
+ taskName: decodeField(name),
252
+ sessionId: decodeField(sessionId),
253
+ cwd: decodeField(cwd),
254
+ command: decodeField(command)
255
+ }];
256
+ });
257
+ }
258
+ function noServer(result) {
259
+ return result.exitCode === 1 && /no server running|no sessions|error connecting to .+ \(No such file or directory\)/i.test(result.stderr);
260
+ }
261
+
262
+ class MuxCommandError extends Error {
263
+ subcommand;
264
+ result;
265
+ constructor(subcommand, result) {
266
+ super(`${subcommand} failed (${result.exitCode ?? result.signal ?? "no exit code"}): ${result.stderr.trim()}`);
267
+ this.subcommand = subcommand;
268
+ this.result = result;
269
+ this.name = "MuxCommandError";
270
+ }
271
+ }
272
+ function createMuxClient(backend, runner, options = {}) {
273
+ const run = (args, options) => runner(backend.executable ?? backend.kind, muxCommandArgs(backend, args), options);
274
+ const checked = async (args, options) => {
275
+ const result = await run(args, options);
276
+ if (result.exitCode !== 0)
277
+ throw new MuxCommandError(args[0], result);
278
+ return result;
279
+ };
280
+ async function listPanes() {
281
+ const result = await run(["list-panes", "-a", "-F", paneFormat]);
282
+ if (noServer(result))
283
+ return [];
284
+ if (result.exitCode !== 0)
285
+ throw new MuxCommandError("list-panes", result);
286
+ return parsePanes(result.stdout);
287
+ }
288
+ async function setMetadata(paneId, task) {
289
+ const entries = [
290
+ [OPTIONS.id, task.id],
291
+ [OPTIONS.role, task.role],
292
+ [OPTIONS.name, task.name],
293
+ [OPTIONS.session, task.sessionId ?? ""],
294
+ [OPTIONS.dir, task.cwd],
295
+ [OPTIONS.cmd, task.command],
296
+ [OPTIONS.managed, "1"]
297
+ ];
298
+ const commands = entries.map(([key, value]) => ["set-option", "-p", "-t", paneId, key, encodeField(value)]);
299
+ if (backend.kind === "psmux") {
300
+ for (const command of commands)
301
+ await checked(command);
302
+ } else {
303
+ await checked(commands.flatMap((command, index) => index ? [";", ...command] : command));
304
+ }
305
+ }
306
+ async function respawnPane(paneId, { cwd, command, channel, metadata }, taskId = metadata?.id) {
307
+ const exitFilePrefix = taskId && await options.prepareExitFile?.(paneId, taskId);
308
+ if (supportsPosixMuxFeatures(backend)) {
309
+ if (exitFilePrefix)
310
+ await checked(["set-hook", "-p", "-t", paneId, cleanupHookName, cleanupHook]);
311
+ else if (metadata)
312
+ await checked(["set-hook", "-p", "-u", "-t", paneId, cleanupHookName]);
313
+ }
314
+ await checked(["respawn-pane", "-k", "-t", paneId, "-c", cwd, ...wrapShellCommand(backend, command, channel, exitFilePrefix)]);
315
+ if (metadata)
316
+ await setMetadata(paneId, metadata);
317
+ }
318
+ async function transplantMouseBindings() {
319
+ const existing = await run(["list-keys", "-T", byobuTable]);
320
+ if (existing.exitCode === 0 && mouseBindings(existing.stdout, byobuTable).length)
321
+ return;
322
+ const root = await run(["list-keys", "-T", "root"]);
323
+ const bindings = root.exitCode === 0 ? mouseBindings(root.stdout, "root") : [];
324
+ if (bindings.length) {
325
+ const dir = await mkdtemp(join(tmpdir(), "opencode-mux-keys-"));
326
+ try {
327
+ const path = join(dir, "mouse.conf");
328
+ await writeFile(path, `${bindings.join(`
329
+ `)}
330
+ `, { mode: 384 });
331
+ if ((await run(["source-file", path])).exitCode === 0)
332
+ return;
333
+ } finally {
334
+ await rm(dir, { recursive: true, force: true });
335
+ }
336
+ }
337
+ await checked(commandList(fallbackMouseBindings.map(([key, command]) => ["bind-key", "-T", byobuTable, key, command])));
338
+ }
339
+ async function enableByobuKeys(session) {
340
+ const bindings = [
341
+ ["F2", "new-window", "-c", "#{pane_current_path}"],
342
+ ["F3", "previous-window"],
343
+ ["F4", "next-window"],
344
+ ["F6", "detach-client"],
345
+ ["F7", "copy-mode"],
346
+ ["F8", "command-prompt", "-I", "#W", "-p", "rename-window ", 'rename-window "%%"'],
347
+ ["M-Left", "previous-window"],
348
+ ["M-Right", "next-window"]
349
+ ];
350
+ await transplantMouseBindings();
351
+ await checked(commandList([
352
+ ...bindings.map((binding) => ["bind-key", "-T", byobuTable, ...binding]),
353
+ ["set-option", "-t", session, "key-table", byobuTable]
354
+ ]));
355
+ }
356
+ async function applySessionTheme(sessionName, paneId, variant) {
357
+ if (variant === "off")
358
+ return;
359
+ const ascii = variant === "ascii" || !supportsPosixMuxFeatures(backend);
360
+ const windowOptions = windowThemeOptions(ascii);
361
+ const hook = windowOptions.map(([key, value]) => `set-option -w ${key} ${JSON.stringify(value)}`).join("; ");
362
+ const commands = [
363
+ ...sessionThemeOptions(ascii).map(([key, value]) => ["set-option", "-t", sessionName, key, value]),
364
+ ["set-hook", "-t", sessionName, themeHook, hook],
365
+ ...windowOptions.map(([key, value]) => ["set-option", "-w", "-t", paneId, key, value])
366
+ ];
367
+ if (backend.kind === "psmux") {
368
+ for (const command of commands) {
369
+ const result = await run(command);
370
+ if (result.exitCode !== 0 && !/unknown|unsupported|not (?:yet )?(?:supported|implemented)|invalid (?:option|style|hook|index|value)/i.test(result.stderr)) {
371
+ throw new MuxCommandError(command[0], result);
372
+ }
373
+ }
374
+ } else {
375
+ await checked(commandList(commands));
376
+ }
377
+ }
378
+ async function killPane(paneId) {
379
+ const result = await run(["kill-pane", "-t", paneId]);
380
+ if (result.exitCode !== 0 && !noServer(result) && !/can't find pane|no such pane|pane not found/i.test(result.stderr)) {
381
+ throw new MuxCommandError("kill-pane", result);
382
+ }
383
+ }
384
+ async function killSession(sessionName) {
385
+ const result = await run(["kill-session", "-t", `=${sessionName}`]);
386
+ if (result.exitCode !== 0 && !noServer(result) && !/can't find session|no such session|session not found/i.test(result.stderr)) {
387
+ throw new MuxCommandError("kill-session", result);
388
+ }
389
+ }
390
+ async function createManagedPane(task) {
391
+ const placeholder = wrapShellCommand(backend, backend.kind === "psmux" || (backend.platform ?? process.platform) === "win32" ? "ping -t 127.0.0.1 >nul" : "exec sleep 86400");
392
+ const common = ["-c", task.cwd, "-P", "-F", "#{pane_id}", ...placeholder];
393
+ const first = await run(["new-session", "-d", "-s", task.muxSession, ...common]);
394
+ let result = first;
395
+ if (first.exitCode !== 0) {
396
+ if (!/duplicate session|session already exists/i.test(first.stderr))
397
+ throw new MuxCommandError("new-session", first);
398
+ result = await checked(["new-window", "-d", "-t", `${task.muxSession}:`, ...common]);
399
+ }
400
+ const paneId = result.stdout.trim();
401
+ if (!/^%\d+$/.test(paneId))
402
+ throw new Error(`Invalid pane id from mux: ${paneId}`);
403
+ try {
404
+ const remain = ["set-option", "-p", "-t", paneId, "remain-on-exit", "on"];
405
+ if (backend.kind === "tmux") {
406
+ remain.push(";", "set-option", "-p", "-t", paneId, "remain-on-exit-format", "");
407
+ }
408
+ await checked(remain);
409
+ await setMetadata(paneId, task);
410
+ await applySessionTheme(task.muxSession, paneId, options.statusTheme ?? "powerline");
411
+ if (options.byobuKeys && supportsPosixMuxFeatures(backend))
412
+ await enableByobuKeys(task.muxSession);
413
+ await respawnPane(paneId, task, task.id);
414
+ } catch (error) {
415
+ await killPane(paneId).catch(() => {});
416
+ throw error;
417
+ }
418
+ return paneId;
419
+ }
420
+ async function sendInterrupt(paneId) {
421
+ await checked(["send-keys", "-t", paneId, "C-c"]);
422
+ }
423
+ async function sendKeys(paneId, text, enter = false) {
424
+ if (text)
425
+ await checked(["send-keys", "-t", paneId, "-l", "--", text.endsWith(";") ? text.slice(0, -1) + "\\;" : text]);
426
+ if (enter)
427
+ await checked(["send-keys", "-t", paneId, "Enter"]);
428
+ }
429
+ async function capturePane(paneId, lines) {
430
+ if (lines !== undefined && (!Number.isSafeInteger(lines) || lines < 0)) {
431
+ throw new RangeError("lines must be a non-negative integer");
432
+ }
433
+ if (lines === 0)
434
+ return "";
435
+ const args = ["capture-pane", "-p", "-t", paneId];
436
+ if (lines !== undefined)
437
+ args.push("-S", `-${lines}`);
438
+ const result = await checked(args);
439
+ const output = stripAnsi(result.stdout).replaceAll(`\r
440
+ `, `
441
+ `).replace(/(?:\n[ \t]*)+$/, "");
442
+ return lines === undefined ? output : output.split(`
443
+ `).slice(-lines).join(`
444
+ `);
445
+ }
446
+ async function waitForChannel(channel, { timeoutMs, signal } = {}) {
447
+ if (signal?.aborted || timeoutMs !== undefined && timeoutMs <= 0)
448
+ return false;
449
+ const controller = new AbortController;
450
+ const abort = () => controller.abort();
451
+ signal?.addEventListener("abort", abort, { once: true });
452
+ const timer = timeoutMs === undefined ? undefined : setTimeout(abort, timeoutMs);
453
+ try {
454
+ return (await run(["wait-for", channel], { signal: controller.signal, timeoutMs })).exitCode === 0;
455
+ } catch (error) {
456
+ if (controller.signal.aborted)
457
+ return false;
458
+ throw error;
459
+ } finally {
460
+ signal?.removeEventListener("abort", abort);
461
+ clearTimeout(timer);
462
+ }
463
+ }
464
+ return { listPanes, createManagedPane, respawnPane, sendInterrupt, sendKeys, capturePane, killPane, killSession, waitForChannel };
465
+ }
466
+ // ../mux-core/src/state.ts
467
+ import { randomUUID } from "node:crypto";
468
+ import { mkdir, readdir, readFile, rename, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
469
+ import { homedir } from "node:os";
470
+ import { basename, join as join2, resolve } from "node:path";
471
+ function resolveMuxStateDir(env = process.env, home = homedir()) {
472
+ return env.OPENCODE_MUX_STATE_DIR || (env.XDG_STATE_HOME ? join2(env.XDG_STATE_HOME, "opencode-mux") : join2(home, ".local", "state", "opencode-mux"));
473
+ }
474
+ function isMissing(error) {
475
+ return error.code === "ENOENT";
476
+ }
477
+ function isSafeTaskId(id) {
478
+ return /^[a-zA-Z0-9_-]{1,128}$/.test(id) && !/^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i.test(id);
479
+ }
480
+ function checkTask(value, id) {
481
+ if (!value || typeof value !== "object")
482
+ return false;
483
+ const task = value;
484
+ return task.id === id && (task.role === "build" || task.role === "service") && (task.muxKind === "tmux" || task.muxKind === "psmux") && ["running", "succeeded", "failed", "stopped", "gone"].includes(task.status ?? "") && typeof task.name === "string" && typeof task.cwd === "string" && typeof task.command === "string" && typeof task.muxSession === "string" && /^%\d+$/.test(task.paneId ?? "") && Number.isSafeInteger(task.restartCount) && typeof task.createdAt === "string" && typeof task.updatedAt === "string";
485
+ }
486
+ function createMuxState(stateDir = resolveMuxStateDir()) {
487
+ const dir = join2(stateDir, "tasks");
488
+ const exitDir = resolve(stateDir, "exit");
489
+ const pathFor = (id) => {
490
+ if (!isSafeTaskId(id))
491
+ throw new Error(`Invalid mux task id: ${id}`);
492
+ return join2(dir, `${id}.json`);
493
+ };
494
+ function exitFilePrefix(paneId, id) {
495
+ if (!/^%\d+$/.test(paneId))
496
+ throw new Error(`Invalid mux pane id: ${paneId}`);
497
+ if (!isSafeTaskId(id))
498
+ throw new Error(`Invalid mux task id: ${id}`);
499
+ return join2(exitDir, `p${paneId.slice(1)}_${id}_`);
500
+ }
501
+ async function prepareExitFile(paneId, id) {
502
+ const prefix = exitFilePrefix(paneId, id);
503
+ await mkdir(exitDir, { recursive: true, mode: 448 });
504
+ return prefix;
505
+ }
506
+ async function findExitFiles(paneId, id) {
507
+ const prefix = basename(exitFilePrefix(paneId, id));
508
+ try {
509
+ return (await readdir(exitDir)).filter((name) => name.startsWith(prefix) && /^\d+\.txt$/.test(name.slice(prefix.length))).map((name) => join2(exitDir, name));
510
+ } catch (error) {
511
+ if (isMissing(error))
512
+ return [];
513
+ throw error;
514
+ }
515
+ }
516
+ async function readExitCode({ paneId, id, panePid }) {
517
+ const files = panePid === undefined ? await findExitFiles(paneId, id) : [`${exitFilePrefix(paneId, id)}${panePid}.txt`];
518
+ if (files.length !== 1)
519
+ return;
520
+ try {
521
+ const content = await readFile(files[0], "utf8");
522
+ const code = Number(content);
523
+ return /^\d+\n$/.test(content) && Number.isSafeInteger(code) ? code : undefined;
524
+ } catch (error) {
525
+ if (isMissing(error))
526
+ return;
527
+ throw error;
528
+ }
529
+ }
530
+ async function deleteExitFile({ paneId, id, panePid }) {
531
+ const files = panePid === undefined ? await findExitFiles(paneId, id) : [`${exitFilePrefix(paneId, id)}${panePid}.txt`];
532
+ await Promise.all(files.map((file) => rm2(file, { force: true })));
533
+ }
534
+ async function readTask(id) {
535
+ try {
536
+ const value = JSON.parse(await readFile(pathFor(id), "utf8"));
537
+ return checkTask(value, id) ? value : undefined;
538
+ } catch (error) {
539
+ if (isMissing(error) || error instanceof SyntaxError)
540
+ return;
541
+ throw error;
542
+ }
543
+ }
544
+ async function writeTask(task) {
545
+ const dest = pathFor(task.id);
546
+ const temp = join2(dir, `.${randomUUID()}.tmp`);
547
+ await mkdir(dir, { recursive: true, mode: 448 });
548
+ try {
549
+ await writeFile2(temp, `${JSON.stringify(task, null, 2)}
550
+ `, { flag: "wx", mode: 384 });
551
+ await rename(temp, dest);
552
+ } finally {
553
+ await rm2(temp, { force: true });
554
+ }
555
+ }
556
+ async function deleteTask(id) {
557
+ await rm2(pathFor(id), { force: true });
558
+ }
559
+ async function listTasks() {
560
+ try {
561
+ const entries = await readdir(dir, { withFileTypes: true });
562
+ const ids = entries.filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name.slice(0, -5)).filter(isSafeTaskId).sort();
563
+ return (await Promise.all(ids.map(readTask))).filter((task) => task !== undefined);
564
+ } catch (error) {
565
+ if (isMissing(error))
566
+ return [];
567
+ throw error;
568
+ }
569
+ }
570
+ return { stateDir, readTask, writeTask, deleteTask, listTasks, prepareExitFile, readExitCode, deleteExitFile };
571
+ }
572
+ // ../mux-core/src/manager.ts
573
+ import { createHash, randomUUID as randomUUID2 } from "node:crypto";
574
+ import { basename as basename2, resolve as resolve2 } from "node:path";
575
+ var now = () => new Date().toISOString();
576
+ function projectMuxSession(cwd) {
577
+ const directory = resolve2(cwd);
578
+ const slug = basename2(directory).toLowerCase().replace(/[^a-z0-9]+/g, "-").slice(0, 40).replace(/^-+|-+$/g, "") || "project";
579
+ const hash = createHash("sha256").update(directory).digest("hex").slice(0, 8);
580
+ return `oc-${slug}-${hash}`;
581
+ }
582
+ function duration(value, name, min = 0) {
583
+ if (!Number.isSafeInteger(value) || value < min || value > 2147483647) {
584
+ throw new RangeError(`${name} must be an integer from ${min} to 2147483647`);
585
+ }
586
+ return value;
587
+ }
588
+ function validateCommand(command) {
589
+ if (!command.trim() || command.includes("\x00"))
590
+ throw new Error("A non-empty mux command is required");
591
+ }
592
+ function statusFromPane(pane, exitCode, stopRequested = false) {
593
+ if (exitCode !== undefined)
594
+ return exitCode === 0 ? "succeeded" : exitCode >= 128 ? "stopped" : "failed";
595
+ if (!pane.paneDead)
596
+ return "running";
597
+ if (stopRequested && (pane.exitCode === undefined || [0, 130, 143].includes(pane.exitCode)))
598
+ return "stopped";
599
+ return pane.exitCode === 0 ? "succeeded" : "failed";
600
+ }
601
+ function matches(task, filter) {
602
+ return (filter.cwd === undefined || task.cwd === resolve2(filter.cwd)) && (filter.role === undefined || task.role === filter.role) && (filter.name === undefined || task.name === filter.name) && (filter.status === undefined || task.status === filter.status) && (filter.sessionId === undefined || task.sessionId === filter.sessionId);
603
+ }
604
+ var delay = (ms) => new Promise((done) => {
605
+ setTimeout(done, ms);
606
+ });
607
+ function createMuxManager(options = {}) {
608
+ const runner = options.runner ?? createCommandRunner();
609
+ const state = createMuxState(options.stateDir);
610
+ const polling = duration(options.pollIntervalMs ?? 100, "pollIntervalMs", 1);
611
+ let backendPromise;
612
+ function getBackend() {
613
+ if (options.backend)
614
+ return Promise.resolve({
615
+ ...options.backend,
616
+ platform: options.platform ?? options.backend.platform,
617
+ socketName: options.socketName ?? options.backend.socketName
618
+ });
619
+ return backendPromise ??= detectMuxBackend({ ...options, runner }).then((backend) => {
620
+ if (!backend)
621
+ throw new Error("No tmux or psmux executable found");
622
+ return backend;
623
+ }).catch((error) => {
624
+ backendPromise = undefined;
625
+ throw error;
626
+ });
627
+ }
628
+ const client = async () => {
629
+ const backend = await getBackend();
630
+ return createMuxClient(backend, runner, {
631
+ byobuKeys: options.byobuKeys ?? true,
632
+ statusTheme: options.statusTheme,
633
+ prepareExitFile: options.keepShellOnExit !== false && supportsPosixMuxFeatures(backend) ? state.prepareExitFile : undefined
634
+ });
635
+ };
636
+ function readExitCode(backend, pane, id, panePid = pane.panePid) {
637
+ return supportsPosixMuxFeatures(backend) ? state.readExitCode({ paneId: pane.paneId, id, panePid }) : undefined;
638
+ }
639
+ function paneResult(pane, exitCode, stopRequested) {
640
+ return {
641
+ status: statusFromPane(pane, exitCode, stopRequested),
642
+ exitCode: exitCode ?? pane.exitCode,
643
+ shell: !pane.paneDead && exitCode !== undefined ? true : undefined
644
+ };
645
+ }
646
+ let queue = Promise.resolve();
647
+ function serial(work) {
648
+ const result = queue.then(work);
649
+ queue = result.catch(() => {});
650
+ return result;
651
+ }
652
+ async function reconcile() {
653
+ const backend = await getBackend();
654
+ const [stored, panes] = await Promise.all([state.listTasks(), (await client()).listPanes()]);
655
+ const byId = new Map(stored.map((task) => [task.id, task]));
656
+ const liveById = new Map;
657
+ for (const pane of panes) {
658
+ if (!pane.managed || !pane.taskId || !isSafeTaskId(pane.taskId) || !pane.role)
659
+ continue;
660
+ const current = liveById.get(pane.taskId) ?? [];
661
+ if (!current.some(({ paneId }) => paneId === pane.paneId))
662
+ current.push(pane);
663
+ liveById.set(pane.taskId, current);
664
+ }
665
+ const tasks = [];
666
+ for (const storedTask of stored) {
667
+ if (storedTask.muxKind !== backend.kind || storedTask.socketName !== backend.socketName)
668
+ continue;
669
+ const candidates = liveById.get(storedTask.id) ?? [];
670
+ const pane = candidates.find(({ paneId }) => paneId === storedTask.paneId) ?? (candidates.length === 1 ? candidates[0] : undefined);
671
+ const panePid = pane?.panePid ?? (pane?.paneDead && pane.paneId === storedTask.paneId ? storedTask.panePid : undefined);
672
+ const exitCode = pane && await readExitCode(backend, pane, storedTask.id, panePid);
673
+ const restarted = !!pane && (pane.paneId !== storedTask.paneId || pane.panePid !== undefined && storedTask.panePid !== undefined && pane.panePid !== storedTask.panePid || !pane.paneDead && exitCode === undefined && storedTask.status !== "running");
674
+ if (restarted && (pane.paneId !== storedTask.paneId || storedTask.panePid !== undefined && panePid !== storedTask.panePid)) {
675
+ await state.deleteExitFile(storedTask);
676
+ }
677
+ const stopRequested = restarted ? undefined : storedTask.stopRequested;
678
+ const task = pane ? {
679
+ ...storedTask,
680
+ muxSession: pane.sessionName,
681
+ paneId: pane.paneId,
682
+ panePid,
683
+ ...paneResult(pane, exitCode, stopRequested),
684
+ stopRequested,
685
+ forceStopped: undefined,
686
+ restartCount: storedTask.restartCount + Number(restarted)
687
+ } : {
688
+ ...storedTask,
689
+ status: storedTask.forceStopped ? "stopped" : "gone",
690
+ shell: undefined
691
+ };
692
+ if (JSON.stringify(task) !== JSON.stringify(storedTask)) {
693
+ task.updatedAt = now();
694
+ await state.writeTask(task);
695
+ }
696
+ tasks.push(task);
697
+ }
698
+ for (const [id, candidates] of liveById) {
699
+ if (byId.has(id) || candidates.length !== 1)
700
+ continue;
701
+ const pane = candidates[0];
702
+ const timestamp = now();
703
+ const task = {
704
+ id,
705
+ role: pane.role,
706
+ name: pane.taskName ?? pane.windowName,
707
+ cwd: pane.cwd ?? pane.paneCurrentPath,
708
+ command: pane.command ?? pane.paneCurrentCommand,
709
+ sessionId: pane.sessionId,
710
+ muxKind: backend.kind,
711
+ muxSession: pane.sessionName,
712
+ socketName: backend.socketName,
713
+ paneId: pane.paneId,
714
+ panePid: pane.panePid,
715
+ ...paneResult(pane, await readExitCode(backend, pane, id)),
716
+ restartCount: 0,
717
+ createdAt: timestamp,
718
+ updatedAt: timestamp
719
+ };
720
+ await state.writeTask(task);
721
+ tasks.push(task);
722
+ }
723
+ return tasks;
724
+ }
725
+ async function find(id) {
726
+ return (await reconcile()).find((task) => task.id === id);
727
+ }
728
+ async function findNamed(role, { name, cwd }) {
729
+ return (await reconcile()).filter((t) => t.role === role && t.name === name && t.cwd === cwd).sort((a, b) => Number(a.status === "gone") - Number(b.status === "gone") || b.updatedAt.localeCompare(a.updatedAt))[0];
730
+ }
731
+ async function start(role, identity, command, existing, channel) {
732
+ validateCommand(command);
733
+ if (!identity.name.trim() || identity.name.includes("\x00"))
734
+ throw new Error("A non-empty mux task name is required");
735
+ const backend = await getBackend();
736
+ const mux = await client();
737
+ const meta = {
738
+ ...identity,
739
+ id: existing?.id ?? randomUUID2(),
740
+ role,
741
+ command,
742
+ muxSession: existing?.muxSession ?? projectMuxSession(identity.cwd),
743
+ sessionId: identity.sessionId ?? existing?.sessionId,
744
+ channel
745
+ };
746
+ const paneAvailable = existing && existing.status !== "gone" && (await mux.listPanes()).some((pane) => pane.paneId === existing.paneId && pane.managed && pane.taskId === existing.id);
747
+ if (existing)
748
+ await state.deleteExitFile(existing);
749
+ let paneId;
750
+ if (paneAvailable) {
751
+ paneId = existing.paneId;
752
+ await mux.respawnPane(paneId, { ...meta, metadata: meta });
753
+ if (existing.panePid !== undefined)
754
+ await state.deleteExitFile(existing);
755
+ } else {
756
+ paneId = await mux.createManagedPane(meta);
757
+ }
758
+ const pane = (await mux.listPanes()).find((p) => p.paneId === paneId && p.taskId === meta.id);
759
+ const timestamp = now();
760
+ const task = {
761
+ id: meta.id,
762
+ role,
763
+ name: meta.name,
764
+ cwd: meta.cwd,
765
+ command,
766
+ sessionId: meta.sessionId,
767
+ source: identity.source ?? existing?.source,
768
+ muxKind: backend.kind,
769
+ socketName: backend.socketName,
770
+ muxSession: pane?.sessionName ?? meta.muxSession,
771
+ paneId,
772
+ panePid: pane?.panePid,
773
+ ...pane ? paneResult(pane, await readExitCode(backend, pane, meta.id)) : { status: "gone" },
774
+ restartCount: existing ? existing.restartCount + 1 : 0,
775
+ createdAt: existing?.createdAt ?? timestamp,
776
+ updatedAt: timestamp
777
+ };
778
+ await state.writeTask(task);
779
+ return task;
780
+ }
781
+ async function runBuild(options) {
782
+ const { wait = true, tailLines = 80 } = options;
783
+ const timeout = duration(options.timeoutMs ?? 120000, "timeoutMs");
784
+ duration(tailLines, "tailLines");
785
+ const identity = { ...options, cwd: resolve2(options.cwd) };
786
+ const channel = wait ? `oc-build-${randomUUID2()}` : undefined;
787
+ const initial = await serial(async () => start("build", identity, options.command, await findNamed("build", identity), channel));
788
+ if (!wait)
789
+ return { ok: initial.status !== "gone", task: initial, tail: "", timedOut: false };
790
+ const mux = await client();
791
+ const controller = new AbortController;
792
+ const deadline = Date.now() + timeout;
793
+ let wake;
794
+ let notifiedAt;
795
+ mux.waitForChannel(channel, { timeoutMs: timeout, signal: controller.signal }).then((signaled) => {
796
+ if (signaled) {
797
+ notifiedAt = Date.now();
798
+ wake?.();
799
+ }
800
+ }, () => {});
801
+ let task = initial;
802
+ try {
803
+ while (task.status === "running" && task.restartCount === initial.restartCount) {
804
+ const remaining = deadline - Date.now();
805
+ if (remaining <= 0)
806
+ break;
807
+ const interval = Math.min(remaining, polling);
808
+ if (notifiedAt !== undefined) {
809
+ await delay(Date.now() - notifiedAt < 250 ? Math.min(interval, 20) : interval);
810
+ } else {
811
+ await new Promise((done) => {
812
+ const timer = setTimeout(done, interval);
813
+ wake = () => {
814
+ clearTimeout(timer);
815
+ done();
816
+ };
817
+ });
818
+ wake = undefined;
819
+ }
820
+ task = await serial(() => find(initial.id)) ?? { ...task, status: "gone" };
821
+ }
822
+ } finally {
823
+ controller.abort();
824
+ }
825
+ const sameRun = task.restartCount === initial.restartCount;
826
+ let tail = "";
827
+ if (sameRun && task.status !== "gone") {
828
+ try {
829
+ tail = await mux.capturePane(task.paneId, tailLines);
830
+ } catch (error) {
831
+ const current = await serial(() => find(task.id));
832
+ if (current && current.status !== "gone" && current.restartCount === task.restartCount)
833
+ throw error;
834
+ task = current ?? { ...task, status: "gone" };
835
+ }
836
+ }
837
+ return {
838
+ ok: task.restartCount === initial.restartCount && task.status === "succeeded",
839
+ task,
840
+ tail,
841
+ timedOut: sameRun && task.status === "running"
842
+ };
843
+ }
844
+ async function stop(task, options) {
845
+ if (task.status !== "running")
846
+ return { ok: task.status !== "gone", task };
847
+ const timeout = duration(options.timeoutMs ?? 2000, "timeoutMs");
848
+ const mux = await client();
849
+ const requested = { ...task, stopRequested: true, updatedAt: now() };
850
+ await state.writeTask(requested);
851
+ try {
852
+ await mux.sendInterrupt(task.paneId);
853
+ } catch (error) {
854
+ const current = await find(task.id);
855
+ if (current?.status !== "running")
856
+ return { ok: current?.status === "stopped", task: current };
857
+ await state.writeTask({ ...current, stopRequested: task.stopRequested });
858
+ throw error;
859
+ }
860
+ const deadline = Date.now() + timeout;
861
+ let current = await find(task.id) ?? requested;
862
+ while (current.status === "running" && current.restartCount === task.restartCount && Date.now() < deadline) {
863
+ await delay(Math.min(polling, Math.max(0, deadline - Date.now())));
864
+ current = await find(task.id) ?? requested;
865
+ }
866
+ if (current.restartCount !== task.restartCount)
867
+ return { ok: false, task: current };
868
+ if (current.status !== "running")
869
+ return { ok: current.status === "stopped", task: current };
870
+ if (!options.force)
871
+ return { ok: false, task: current, timedOut: true };
872
+ await mux.killPane(task.paneId);
873
+ await state.deleteExitFile(task);
874
+ const stopped = { ...current, status: "stopped", forceStopped: true, panePid: undefined, updatedAt: now() };
875
+ await state.writeTask(stopped);
876
+ return { ok: true, task: stopped };
877
+ }
878
+ async function deleteTaskState(task) {
879
+ await state.deleteExitFile(task);
880
+ await state.deleteTask(task.id);
881
+ }
882
+ async function remove(task) {
883
+ const mux = await client();
884
+ if ((await mux.listPanes()).some((pane) => pane.paneId === task.paneId && pane.managed && pane.taskId === task.id)) {
885
+ await mux.killPane(task.paneId);
886
+ }
887
+ await deleteTaskState(task);
888
+ return { ok: true, task };
889
+ }
890
+ async function serviceAction(options) {
891
+ const identity = { ...options, cwd: resolve2(options.cwd) };
892
+ return serial(async () => {
893
+ const task = await findNamed("service", identity);
894
+ switch (options.action) {
895
+ case "status":
896
+ return { ok: !!task, task };
897
+ case "stop":
898
+ return task ? stop(task, options) : { ok: false };
899
+ case "remove":
900
+ return task ? remove(task) : { ok: false };
901
+ case "start":
902
+ if (task?.status === "running" && !options.restartIfRunning)
903
+ return { ok: true, task };
904
+ case "restart": {
905
+ const command = options.command ?? task?.command;
906
+ if (command === undefined)
907
+ throw new Error("A command is required for a new service");
908
+ const started = await start("service", identity, command, task);
909
+ return { ok: started.status !== "gone", task: started };
910
+ }
911
+ }
912
+ });
913
+ }
914
+ function restartTask(id, options = {}) {
915
+ return serial(async () => {
916
+ const task = await find(id);
917
+ if (!task)
918
+ return { ok: false };
919
+ const started = await start(task.role, { ...task, ...options }, options.command ?? task.command, task);
920
+ return { ok: started.status !== "gone", task: started };
921
+ });
922
+ }
923
+ function stopTask(id, options = {}) {
924
+ return serial(async () => {
925
+ const task = await find(id);
926
+ return task ? stop(task, options) : { ok: false };
927
+ });
928
+ }
929
+ function removeTask(id) {
930
+ return serial(async () => {
931
+ const task = await find(id);
932
+ return task ? remove(task) : { ok: false };
933
+ });
934
+ }
935
+ function closeSession({ cwd = process.cwd() } = {}) {
936
+ return serial(async () => {
937
+ const sessionName = projectMuxSession(cwd);
938
+ const tasks = (await reconcile()).filter((task) => task.muxSession === sessionName);
939
+ await (await client()).killSession(sessionName);
940
+ await Promise.all(tasks.map(deleteTaskState));
941
+ return { ok: true, removed: tasks.length, sessionName };
942
+ });
943
+ }
944
+ async function liveTask(id) {
945
+ const task = await find(id);
946
+ if (!task || task.status === "gone" || task.forceStopped) {
947
+ throw new Error(`Mux task ${id} has no live pane`);
948
+ }
949
+ return task;
950
+ }
951
+ return {
952
+ getBackend,
953
+ runBuild,
954
+ serviceAction,
955
+ restartTask,
956
+ stopTask,
957
+ removeTask,
958
+ closeSession,
959
+ captureLogs: (id, lines) => serial(async () => (await client()).capturePane((await liveTask(id)).paneId, lines)),
960
+ sendInput: (id, input, { enter } = {}) => serial(async () => {
961
+ const task = await liveTask(id);
962
+ const mux = await client();
963
+ if (!(await mux.listPanes()).some((pane) => pane.paneId === task.paneId && pane.taskId === id && pane.managed && !pane.paneDead)) {
964
+ throw new Error(`Mux task ${id} has no live pane`);
965
+ }
966
+ await mux.sendKeys(task.paneId, input, enter);
967
+ }),
968
+ listTasks: (filter = {}) => serial(async () => (await reconcile()).filter((task) => matches(task, filter))),
969
+ pruneGone: (filter = {}) => serial(async () => {
970
+ const gone = (await reconcile()).filter((task) => task.status === "gone" && matches(task, filter));
971
+ await Promise.all(gone.map(deleteTaskState));
972
+ return gone;
973
+ }),
974
+ attachCommand: async (task) => buildAttachCommand(await getBackend(), task.muxSession)
975
+ };
976
+ }
977
+ // service/app.ts
978
+ import { createServer } from "node:http";
979
+ var MAX_BODY_BYTES = 64 * 1024;
980
+ var MAX_INTEGER = 2147483647;
981
+ var MAX_BUILD_WAIT_MS = 15000;
982
+ var MISSING_BACKEND = "No tmux or psmux executable found";
983
+ var ROLES = ["build", "service"];
984
+ var STATUSES = ["running", "succeeded", "failed", "stopped", "gone"];
985
+ var ACTIONS = ["start", "restart", "stop", "status", "remove"];
986
+
987
+ class HttpError extends Error {
988
+ status;
989
+ constructor(status, message) {
990
+ super(message);
991
+ this.status = status;
992
+ }
993
+ }
994
+ function respond(response, status, body) {
995
+ response.writeHead(status, {
996
+ "Content-Type": "application/json; charset=utf-8",
997
+ "Cache-Control": "no-store"
998
+ }).end(JSON.stringify(body));
999
+ }
1000
+ async function readBody(request) {
1001
+ const tooLarge = () => new HttpError(400, "JSON body exceeds 64 KiB");
1002
+ if (Number(request.headers["content-length"]) > MAX_BODY_BYTES)
1003
+ throw tooLarge();
1004
+ const chunks = [];
1005
+ let size = 0;
1006
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
1007
+ size += chunk.length;
1008
+ if (size > MAX_BODY_BYTES)
1009
+ throw tooLarge();
1010
+ chunks.push(chunk);
1011
+ }
1012
+ if (size === 0)
1013
+ return {};
1014
+ let data;
1015
+ try {
1016
+ data = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks, size)));
1017
+ } catch {
1018
+ throw new HttpError(400, "Invalid JSON");
1019
+ }
1020
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
1021
+ throw new HttpError(400, "Expected a JSON object");
1022
+ }
1023
+ return data;
1024
+ }
1025
+ function text(value, field, allowEmpty = false) {
1026
+ if (typeof value !== "string" || !allowEmpty && !value.trim() || value.includes("\x00")) {
1027
+ throw new HttpError(400, `Invalid ${field}`);
1028
+ }
1029
+ return value;
1030
+ }
1031
+ function optionalText(value, field) {
1032
+ return value === undefined ? undefined : text(value, field);
1033
+ }
1034
+ function optionalBoolean(value, field) {
1035
+ if (value === undefined || typeof value === "boolean")
1036
+ return value;
1037
+ throw new HttpError(400, `Invalid ${field}`);
1038
+ }
1039
+ function optionalInteger(value, field) {
1040
+ if (value === undefined)
1041
+ return;
1042
+ if (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= MAX_INTEGER)
1043
+ return value;
1044
+ throw new HttpError(400, `Invalid ${field}`);
1045
+ }
1046
+ function oneOf(value, field, values, optional = false) {
1047
+ if (value === undefined && optional)
1048
+ return;
1049
+ const match = values.find((item) => item === value);
1050
+ if (match === undefined)
1051
+ throw new HttpError(400, `Invalid ${field}`);
1052
+ return match;
1053
+ }
1054
+ function taskNotFound() {
1055
+ return new HttpError(404, "Task not found");
1056
+ }
1057
+ function missingPane(error, id) {
1058
+ return error instanceof Error && (error.message === `Mux task ${id} has no live pane` || error instanceof MuxCommandError && ["capture-pane", "send-keys"].includes(error.subcommand) && /can't find pane|no such pane|pane not found|no server running|no sessions|no such file or directory/i.test(error.result.stderr));
1059
+ }
1060
+ function createServiceHandler({ manager, token }) {
1061
+ const authorization = token ? `Bearer ${token}` : undefined;
1062
+ const backendOrNull = async () => {
1063
+ try {
1064
+ return await manager.getBackend();
1065
+ } catch (error) {
1066
+ if (error instanceof Error && error.message === MISSING_BACKEND)
1067
+ return null;
1068
+ throw error;
1069
+ }
1070
+ };
1071
+ const view = async (task) => ({ ...task, attachCommand: await manager.attachCommand(task) });
1072
+ const actionResponse = async (result) => result.task ? { ...result, task: await view(result.task) } : { ok: result.ok, timedOut: result.timedOut };
1073
+ async function route(request) {
1074
+ if (authorization === undefined || request.headers.authorization !== authorization) {
1075
+ throw new HttpError(401, "Unauthorized");
1076
+ }
1077
+ const target = request.url;
1078
+ if (!target?.startsWith("/") || target.startsWith("//"))
1079
+ throw new HttpError(400, "Invalid request target");
1080
+ const { pathname, searchParams } = new URL(target, "http://127.0.0.1");
1081
+ const method = request.method;
1082
+ if (method === "GET" && pathname === "/health") {
1083
+ return { ok: true, backend: await backendOrNull() };
1084
+ }
1085
+ if (method === "GET" && pathname === "/tasks") {
1086
+ const filter = {
1087
+ cwd: optionalText(searchParams.get("cwd") ?? undefined, "cwd"),
1088
+ role: oneOf(searchParams.get("role") ?? undefined, "role", ROLES, true),
1089
+ status: oneOf(searchParams.get("status") ?? undefined, "status", STATUSES, true)
1090
+ };
1091
+ const backend = await backendOrNull();
1092
+ const tasks = backend ? await Promise.all((await manager.listTasks(filter)).map(view)) : [];
1093
+ return { tasks, backend };
1094
+ }
1095
+ if (method === "POST" && pathname === "/builds") {
1096
+ const body = await readBody(request);
1097
+ const input = {
1098
+ name: text(body.name, "name"),
1099
+ command: text(body.command, "command"),
1100
+ cwd: text(body.cwd, "cwd"),
1101
+ wait: optionalBoolean(body.wait, "wait") ?? false,
1102
+ timeoutMs: optionalInteger(body.timeoutMs, "timeoutMs"),
1103
+ tailLines: optionalInteger(body.tailLines, "tailLines")
1104
+ };
1105
+ if (input.wait)
1106
+ input.timeoutMs = Math.min(input.timeoutMs ?? MAX_BUILD_WAIT_MS, MAX_BUILD_WAIT_MS);
1107
+ const result = await manager.runBuild({ ...input, source: "openchamber" });
1108
+ return { ...result, task: await view(result.task) };
1109
+ }
1110
+ if (method === "POST" && pathname === "/services") {
1111
+ const body = await readBody(request);
1112
+ const input = {
1113
+ action: oneOf(body.action, "action", ACTIONS),
1114
+ name: text(body.name, "name"),
1115
+ cwd: text(body.cwd, "cwd"),
1116
+ command: optionalText(body.command, "command"),
1117
+ restartIfRunning: optionalBoolean(body.restartIfRunning, "restartIfRunning"),
1118
+ force: optionalBoolean(body.force, "force"),
1119
+ timeoutMs: optionalInteger(body.timeoutMs, "timeoutMs")
1120
+ };
1121
+ return actionResponse(await manager.serviceAction({ ...input, source: "openchamber" }));
1122
+ }
1123
+ if (method === "POST" && pathname === "/prune") {
1124
+ const body = await readBody(request);
1125
+ const filter = {
1126
+ cwd: optionalText(body.cwd, "cwd"),
1127
+ role: oneOf(body.role, "role", ROLES, true)
1128
+ };
1129
+ return { pruned: await manager.pruneGone(filter) };
1130
+ }
1131
+ if (method === "POST" && pathname === "/session/close") {
1132
+ const body = await readBody(request);
1133
+ const input = { cwd: text(body.cwd, "cwd") };
1134
+ return await manager.closeSession(input);
1135
+ }
1136
+ const taskRoute = /^\/tasks\/([^/]+)(?:\/(restart|stop|logs|input))?$/.exec(pathname);
1137
+ if (taskRoute) {
1138
+ let id;
1139
+ try {
1140
+ id = decodeURIComponent(taskRoute[1]);
1141
+ } catch {
1142
+ throw new HttpError(400, "Invalid task ID");
1143
+ }
1144
+ if (!isSafeTaskId(id))
1145
+ throw taskNotFound();
1146
+ const operation = taskRoute[2];
1147
+ if (method === "POST" && operation === "restart") {
1148
+ const body = await readBody(request);
1149
+ const input = { command: optionalText(body.command, "command") };
1150
+ const result = await manager.restartTask(id, { ...input, source: "openchamber" });
1151
+ if (!result.task)
1152
+ throw taskNotFound();
1153
+ return actionResponse(result);
1154
+ }
1155
+ if (method === "POST" && operation === "stop") {
1156
+ const body = await readBody(request);
1157
+ const input = {
1158
+ force: optionalBoolean(body.force, "force"),
1159
+ timeoutMs: optionalInteger(body.timeoutMs, "timeoutMs")
1160
+ };
1161
+ const result = await manager.stopTask(id, input);
1162
+ if (!result.task)
1163
+ throw taskNotFound();
1164
+ return actionResponse(result);
1165
+ }
1166
+ if (method === "DELETE" && operation === undefined) {
1167
+ const result = await manager.removeTask(id);
1168
+ if (!result.task)
1169
+ throw taskNotFound();
1170
+ return actionResponse(result);
1171
+ }
1172
+ if (method === "GET" && operation === "logs") {
1173
+ const value = searchParams.get("lines") ?? "120";
1174
+ if (!/^\d+$/.test(value))
1175
+ throw new HttpError(400, "Invalid lines");
1176
+ const lines = optionalInteger(Number(value), "lines");
1177
+ let tail;
1178
+ try {
1179
+ tail = await manager.captureLogs(id, lines);
1180
+ } catch (error) {
1181
+ if (missingPane(error, id))
1182
+ throw taskNotFound();
1183
+ throw error;
1184
+ }
1185
+ const task = (await manager.listTasks()).find((item) => item.id === id);
1186
+ if (!task || task.status === "gone" || task.forceStopped)
1187
+ throw taskNotFound();
1188
+ const { status, exitCode, attachCommand } = await view(task);
1189
+ return { id, status, exitCode, tail, attachCommand };
1190
+ }
1191
+ if (method === "POST" && operation === "input") {
1192
+ const body = await readBody(request);
1193
+ const input = { input: text(body.input, "input", true), enter: optionalBoolean(body.enter, "enter") };
1194
+ try {
1195
+ await manager.sendInput(id, input.input, { enter: input.enter });
1196
+ } catch (error) {
1197
+ if (error instanceof Error && error.message === `Mux task ${id} is not running`) {
1198
+ throw new HttpError(409, "Task is not running");
1199
+ }
1200
+ if (missingPane(error, id))
1201
+ throw taskNotFound();
1202
+ throw error;
1203
+ }
1204
+ return { ok: true };
1205
+ }
1206
+ }
1207
+ throw new HttpError(404, "Not found");
1208
+ }
1209
+ return (request, response) => {
1210
+ route(request).then((body) => respond(response, 200, body)).catch((error) => {
1211
+ request.resume();
1212
+ if (response.destroyed || response.headersSent)
1213
+ return;
1214
+ if (error instanceof HttpError) {
1215
+ respond(response, error.status, { error: error.message });
1216
+ } else if (error instanceof Error && error.message === MISSING_BACKEND) {
1217
+ respond(response, 503, { error: MISSING_BACKEND });
1218
+ } else if (error instanceof Error && error.message === "A command is required for a new service") {
1219
+ respond(response, 400, { error: error.message });
1220
+ } else {
1221
+ console.error("Mux service request failed", error);
1222
+ respond(response, 500, { error: "Internal server error" });
1223
+ }
1224
+ });
1225
+ };
1226
+ }
1227
+ function createServiceServer(options) {
1228
+ return createServer(createServiceHandler(options));
1229
+ }
1230
+
1231
+ // service/main.ts
1232
+ var portValue = process.env.OPENCHAMBER_SERVICE_PORT ?? "";
1233
+ var port = Number(portValue);
1234
+ var token = process.env.OPENCHAMBER_SERVICE_TOKEN;
1235
+ if (!/^\d+$/.test(portValue) || !Number.isInteger(port) || port < 1 || port > 65535) {
1236
+ throw new Error("OPENCHAMBER_SERVICE_PORT must be an integer from 1 to 65535");
1237
+ }
1238
+ if (!token?.trim())
1239
+ throw new Error("OPENCHAMBER_SERVICE_TOKEN is required");
1240
+ var server = createServiceServer({ manager: createMuxManager(), token });
1241
+ server.listen(port, "127.0.0.1");
1242
+ var closing = false;
1243
+ function shutdown() {
1244
+ if (closing)
1245
+ return;
1246
+ closing = true;
1247
+ setTimeout(() => process.exit(0), 5000).unref();
1248
+ server.close();
1249
+ server.closeIdleConnections();
1250
+ }
1251
+ process.on("SIGTERM", shutdown);
1252
+ process.on("SIGINT", shutdown);