reevesagents 1.2.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.
- package/CHANGELOG.md +104 -0
- package/LICENSE +166 -0
- package/README.md +288 -0
- package/dist/chunk-3IXII4H5.js +129 -0
- package/dist/chunk-4Q3JF22J.js +51 -0
- package/dist/chunk-D24DQQ6V.js +36 -0
- package/dist/chunk-DHAW6OY3.js +40 -0
- package/dist/chunk-G6FN75ZW.js +2393 -0
- package/dist/chunk-JY4ZTTRK.js +172 -0
- package/dist/chunk-LUW6GCPO.js +108 -0
- package/dist/chunk-MVMGFG4W.js +1462 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +355 -0
- package/dist/extras-25AF6TAR.js +12 -0
- package/dist/index.d.ts +236 -0
- package/dist/index.js +89 -0
- package/dist/open-browser-DRSIJQ37.js +26 -0
- package/dist/router-WCFLHJV7.js +5700 -0
- package/dist/server-Z2YTGWSX.js +883 -0
- package/dist/tui-launch-7RGFE5KY.js +10 -0
- package/dist/web/addon-fit.js +2 -0
- package/dist/web/app.css +1742 -0
- package/dist/web/app.js +1435 -0
- package/dist/web/brand-duck.json +1 -0
- package/dist/web/index.html +178 -0
- package/dist/web/xterm.css +285 -0
- package/dist/web/xterm.js +2 -0
- package/package.json +86 -0
|
@@ -0,0 +1,883 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
localeCatalog
|
|
4
|
+
} from "./chunk-G6FN75ZW.js";
|
|
5
|
+
import {
|
|
6
|
+
modelValuesForProvider
|
|
7
|
+
} from "./chunk-LUW6GCPO.js";
|
|
8
|
+
import {
|
|
9
|
+
LANGUAGE_OPTIONS,
|
|
10
|
+
PROVIDERS,
|
|
11
|
+
archiveAndRemoveRun,
|
|
12
|
+
autoCleanupRuns,
|
|
13
|
+
computeRunStatus,
|
|
14
|
+
deleteAgent,
|
|
15
|
+
deleteRunHistory,
|
|
16
|
+
detectAvailable,
|
|
17
|
+
findAgent,
|
|
18
|
+
findAgentAny,
|
|
19
|
+
isLanguageCode,
|
|
20
|
+
killAgent,
|
|
21
|
+
listAgents,
|
|
22
|
+
listAgentsAny,
|
|
23
|
+
listRunHistory,
|
|
24
|
+
listRuns,
|
|
25
|
+
listRunsAny,
|
|
26
|
+
loadConfig,
|
|
27
|
+
normalizeProvider,
|
|
28
|
+
providerColor,
|
|
29
|
+
providerDisplayName,
|
|
30
|
+
readRun,
|
|
31
|
+
readRunAny,
|
|
32
|
+
runHasLiveTmuxTarget,
|
|
33
|
+
saveConfig,
|
|
34
|
+
spawnWorker,
|
|
35
|
+
startRun,
|
|
36
|
+
stopRun
|
|
37
|
+
} from "./chunk-MVMGFG4W.js";
|
|
38
|
+
|
|
39
|
+
// src/web/server.ts
|
|
40
|
+
import { createServer } from "http";
|
|
41
|
+
import { readFileSync } from "fs";
|
|
42
|
+
import { join, dirname } from "path";
|
|
43
|
+
import { fileURLToPath } from "url";
|
|
44
|
+
|
|
45
|
+
// src/web/guards.ts
|
|
46
|
+
import { URL } from "url";
|
|
47
|
+
var LOOPBACK_HOSTS = /* @__PURE__ */ new Set(["127.0.0.1", "localhost", "::1"]);
|
|
48
|
+
function stripBrackets(host) {
|
|
49
|
+
return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
|
|
50
|
+
}
|
|
51
|
+
function hostOnly(value) {
|
|
52
|
+
if (value.startsWith("[")) {
|
|
53
|
+
const end = value.indexOf("]");
|
|
54
|
+
return end >= 0 ? value.slice(0, end + 1) : value;
|
|
55
|
+
}
|
|
56
|
+
const colon = value.lastIndexOf(":");
|
|
57
|
+
return colon >= 0 ? value.slice(0, colon) : value;
|
|
58
|
+
}
|
|
59
|
+
function isAllowedHostHeader(hostHeader) {
|
|
60
|
+
if (!hostHeader) return false;
|
|
61
|
+
const host = stripBrackets(hostOnly(hostHeader.trim())).toLowerCase();
|
|
62
|
+
return LOOPBACK_HOSTS.has(host);
|
|
63
|
+
}
|
|
64
|
+
function isStateChangingMethod(method) {
|
|
65
|
+
const verb = (method ?? "").toUpperCase();
|
|
66
|
+
return verb !== "" && verb !== "GET" && verb !== "HEAD" && verb !== "OPTIONS";
|
|
67
|
+
}
|
|
68
|
+
function isAllowedOrigin(originHeader, port) {
|
|
69
|
+
if (!originHeader) return false;
|
|
70
|
+
let url;
|
|
71
|
+
try {
|
|
72
|
+
url = new URL(originHeader);
|
|
73
|
+
} catch {
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
const host = stripBrackets(url.hostname).toLowerCase();
|
|
77
|
+
if (!LOOPBACK_HOSTS.has(host)) return false;
|
|
78
|
+
return url.port === String(port);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/web/prebeta-orchestrator.ts
|
|
82
|
+
var ORCHESTRATOR_WEB_PROVIDERS = ["cc", "codex", "opencode", "hermes"];
|
|
83
|
+
function isOrchestratorWebProvider(provider) {
|
|
84
|
+
return ORCHESTRATOR_WEB_PROVIDERS.includes(provider);
|
|
85
|
+
}
|
|
86
|
+
function isRuntime(value) {
|
|
87
|
+
if (!value || typeof value !== "object") return false;
|
|
88
|
+
const maybe = value;
|
|
89
|
+
return typeof maybe.startRun === "function" && typeof maybe.spawnWorker === "function" && typeof maybe.killAgent === "function" && typeof maybe.stopRun === "function";
|
|
90
|
+
}
|
|
91
|
+
async function loadWebOrchestratorRuntime(injected) {
|
|
92
|
+
if (injected) return injected;
|
|
93
|
+
try {
|
|
94
|
+
const specifier = "reevesagents-orchestrator";
|
|
95
|
+
const mod = await import(specifier);
|
|
96
|
+
if (isRuntime(mod)) return mod;
|
|
97
|
+
} catch {
|
|
98
|
+
}
|
|
99
|
+
throw new Error([
|
|
100
|
+
"PRE-BETA orchestrator web mode requires the separate orchestrator package.",
|
|
101
|
+
"Install the all-in pre-beta option, then rerun:",
|
|
102
|
+
" npm install -g reevesagents reevesagents-orchestrator",
|
|
103
|
+
" reevesagents web --prebeta-orchestrator"
|
|
104
|
+
].join("\n"));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// src/web/state.ts
|
|
108
|
+
function monogram(nickname, provider) {
|
|
109
|
+
const base = (nickname || provider).trim();
|
|
110
|
+
const alnum = base.replace(/[^A-Za-z0-9]/g, "");
|
|
111
|
+
return (alnum.slice(0, 2) || provider.slice(0, 2)).toUpperCase();
|
|
112
|
+
}
|
|
113
|
+
function buildWebState(options = {}) {
|
|
114
|
+
const runsSource = options.prebetaOrchestrator ? listRunsAny() : listRuns();
|
|
115
|
+
const listForRun = options.prebetaOrchestrator ? listAgentsAny : listAgents;
|
|
116
|
+
const runs = runsSource.map((run) => {
|
|
117
|
+
const mode = run.mode === "spawner" ? "spawner" : "orchestrator";
|
|
118
|
+
const live = options.liveTmuxTarget ? options.liveTmuxTarget(run) : runHasLiveTmuxTarget(run);
|
|
119
|
+
const runStatus = computeRunStatus(run, live);
|
|
120
|
+
const terminals = listForRun(run.id).map((agent) => {
|
|
121
|
+
const status = agent.ended_at ? "ended" : agent.task_status;
|
|
122
|
+
const hasWindow = !agent.headless && !!agent.tmux_window_id;
|
|
123
|
+
const canAttach = live && hasWindow && status !== "ended";
|
|
124
|
+
const canKill = live && status !== "ended" && hasWindow && (mode === "spawner" || agent.role !== "root");
|
|
125
|
+
const canDelete = status === "ended";
|
|
126
|
+
return {
|
|
127
|
+
id: agent.id,
|
|
128
|
+
nickname: agent.nickname,
|
|
129
|
+
provider: agent.provider,
|
|
130
|
+
provider_label: providerDisplayName(agent.provider),
|
|
131
|
+
model: agent.model,
|
|
132
|
+
role: agent.role,
|
|
133
|
+
status,
|
|
134
|
+
headless: !!agent.headless,
|
|
135
|
+
hasWindow,
|
|
136
|
+
canAttach,
|
|
137
|
+
canKill,
|
|
138
|
+
canDelete,
|
|
139
|
+
disabledReason: canAttach ? null : status === "ended" ? "agent has ended" : !live ? "run tmux session is unavailable" : "agent has no tmux window",
|
|
140
|
+
monogram: monogram(agent.nickname, agent.provider),
|
|
141
|
+
color: providerColor(agent.provider)
|
|
142
|
+
};
|
|
143
|
+
});
|
|
144
|
+
return {
|
|
145
|
+
id: run.id,
|
|
146
|
+
mode,
|
|
147
|
+
name: run.name,
|
|
148
|
+
status: runStatus,
|
|
149
|
+
working_dir: run.working_dir,
|
|
150
|
+
canStop: run.status === "running" && !run.ended_at,
|
|
151
|
+
canDelete: run.status === "ended" || run.ended_at !== null,
|
|
152
|
+
terminals
|
|
153
|
+
};
|
|
154
|
+
});
|
|
155
|
+
const history = listRunHistory({ includeAllModes: options.prebetaOrchestrator === true }).map((record) => ({
|
|
156
|
+
id: record.id,
|
|
157
|
+
name: record.name,
|
|
158
|
+
mode: record.mode,
|
|
159
|
+
status: record.status,
|
|
160
|
+
working_dir: record.working_dir,
|
|
161
|
+
started_at: record.started_at,
|
|
162
|
+
ended_at: record.ended_at,
|
|
163
|
+
archived_at: record.archived_at,
|
|
164
|
+
agent_count: record.agent_count,
|
|
165
|
+
root_provider: record.root_provider,
|
|
166
|
+
root_provider_label: record.root_provider ? providerDisplayName(record.root_provider) : null
|
|
167
|
+
}));
|
|
168
|
+
return { runs, history };
|
|
169
|
+
}
|
|
170
|
+
function listWebProviders() {
|
|
171
|
+
const available = detectAvailable();
|
|
172
|
+
return PROVIDERS.map((id) => ({
|
|
173
|
+
id,
|
|
174
|
+
name: providerDisplayName(id),
|
|
175
|
+
available: available[id],
|
|
176
|
+
orchestrator: isOrchestratorWebProvider(id),
|
|
177
|
+
color: providerColor(id),
|
|
178
|
+
models: [...modelValuesForProvider(id)]
|
|
179
|
+
}));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// src/web/client-shell.ts
|
|
183
|
+
var PALETTE = {
|
|
184
|
+
bg: "#15191f",
|
|
185
|
+
panel: "#1b2129",
|
|
186
|
+
border: "#3a4b5f",
|
|
187
|
+
text: "#ece7dc",
|
|
188
|
+
dim: "#b8b0a3",
|
|
189
|
+
muted: "#817b70",
|
|
190
|
+
accent: "#7eb8f5",
|
|
191
|
+
ok: "#83a36f",
|
|
192
|
+
warn: "#d7a84f",
|
|
193
|
+
error: "#d56a60"
|
|
194
|
+
};
|
|
195
|
+
function placeholderPage() {
|
|
196
|
+
return `<!doctype html>
|
|
197
|
+
<html lang="en">
|
|
198
|
+
<head>
|
|
199
|
+
<meta charset="utf-8" />
|
|
200
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
201
|
+
<title>ReevesAgents Web</title>
|
|
202
|
+
<style>
|
|
203
|
+
:root { color-scheme: dark; }
|
|
204
|
+
* { box-sizing: border-box; }
|
|
205
|
+
body {
|
|
206
|
+
margin: 0; font: 14px/1.5 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
|
|
207
|
+
background: ${PALETTE.bg}; color: ${PALETTE.text};
|
|
208
|
+
}
|
|
209
|
+
header {
|
|
210
|
+
padding: 16px 20px; border-bottom: 1px solid ${PALETTE.border};
|
|
211
|
+
display: flex; align-items: baseline; gap: 12px;
|
|
212
|
+
}
|
|
213
|
+
header h1 { margin: 0; font-size: 16px; letter-spacing: 0.04em; }
|
|
214
|
+
header .tag { color: ${PALETTE.muted}; font-size: 12px; }
|
|
215
|
+
main { padding: 20px; max-width: 760px; }
|
|
216
|
+
.run { margin-bottom: 24px; }
|
|
217
|
+
.run-name { color: ${PALETTE.accent}; font-size: 13px; margin-bottom: 8px; }
|
|
218
|
+
.run-meta { color: ${PALETTE.muted}; font-size: 12px; margin-left: 8px; }
|
|
219
|
+
.card {
|
|
220
|
+
display: flex; align-items: center; gap: 12px;
|
|
221
|
+
padding: 10px 12px; margin-bottom: 6px;
|
|
222
|
+
background: ${PALETTE.panel}; border: 1px solid ${PALETTE.border}; border-radius: 6px;
|
|
223
|
+
}
|
|
224
|
+
.mono {
|
|
225
|
+
width: 30px; height: 30px; flex: none; border-radius: 6px;
|
|
226
|
+
display: grid; place-items: center; font-weight: 600; font-size: 12px;
|
|
227
|
+
color: #15191f;
|
|
228
|
+
}
|
|
229
|
+
.card .name { font-size: 13px; }
|
|
230
|
+
.card .sub { color: ${PALETTE.dim}; font-size: 12px; }
|
|
231
|
+
.status { margin-left: auto; font-size: 12px; }
|
|
232
|
+
.s-running, .s-working, .s-done { color: ${PALETTE.ok}; }
|
|
233
|
+
.s-stale, .s-queued, .s-blocked { color: ${PALETTE.warn}; }
|
|
234
|
+
.s-ended, .s-failed { color: ${PALETTE.error}; }
|
|
235
|
+
.empty { color: ${PALETTE.muted}; }
|
|
236
|
+
</style>
|
|
237
|
+
</head>
|
|
238
|
+
<body>
|
|
239
|
+
<header>
|
|
240
|
+
<h1>ReevesAgents</h1>
|
|
241
|
+
<span class="tag">web ui (beta) \xB7 loopback only</span>
|
|
242
|
+
</header>
|
|
243
|
+
<main id="app"><p class="empty">Loading agents...</p></main>
|
|
244
|
+
<script>
|
|
245
|
+
function esc(s) { return String(s).replace(/[&<>"]/g, c => ({'&':'&','<':'<','>':'>','"':'"'}[c])); }
|
|
246
|
+
function statusClass(s) { return 's-' + String(s).replace(/[^a-z]/gi, ''); }
|
|
247
|
+
async function load() {
|
|
248
|
+
const app = document.getElementById('app');
|
|
249
|
+
try {
|
|
250
|
+
const res = await fetch('/api/state', { headers: { accept: 'application/json' } });
|
|
251
|
+
const state = await res.json();
|
|
252
|
+
if (!state.runs || state.runs.length === 0) {
|
|
253
|
+
app.innerHTML = '<p class="empty">No runs yet. Start a run from the TUI or CLI.</p>';
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
app.innerHTML = state.runs.map(run => {
|
|
257
|
+
const cards = run.terminals.map(t =>
|
|
258
|
+
'<div class="card">'
|
|
259
|
+
+ '<div class="mono" style="background:' + esc(t.color) + '">' + esc(t.monogram) + '</div>'
|
|
260
|
+
+ '<div><div class="name">' + esc(t.nickname) + '</div>'
|
|
261
|
+
+ '<div class="sub">' + esc(t.provider_label || t.provider) + (t.model ? ' \xB7 ' + esc(t.model) : '') + '</div></div>'
|
|
262
|
+
+ '<div class="status ' + statusClass(t.status) + '">' + esc(t.status) + '</div>'
|
|
263
|
+
+ '</div>'
|
|
264
|
+
).join('');
|
|
265
|
+
return '<section class="run"><div class="run-name">' + esc(run.name)
|
|
266
|
+
+ '<span class="run-meta">' + esc(run.status) + ' \xB7 ' + esc(run.working_dir) + '</span></div>'
|
|
267
|
+
+ (cards || '<p class="empty">no agents</p>') + '</section>';
|
|
268
|
+
}).join('');
|
|
269
|
+
} catch (err) {
|
|
270
|
+
app.innerHTML = '<p class="empty">Failed to load state: ' + esc(err && err.message || err) + '</p>';
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
load();
|
|
274
|
+
setInterval(load, 4000);
|
|
275
|
+
</script>
|
|
276
|
+
</body>
|
|
277
|
+
</html>`;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// src/web/bridge.ts
|
|
281
|
+
import { execFileSync, spawnSync } from "child_process";
|
|
282
|
+
import { randomBytes } from "crypto";
|
|
283
|
+
import { URL as URL2 } from "url";
|
|
284
|
+
import { WebSocketServer } from "ws";
|
|
285
|
+
import pty from "@lydell/node-pty";
|
|
286
|
+
function resolveTerminalTarget(id, options = {}) {
|
|
287
|
+
if (!id) throw new Error("missing agent id");
|
|
288
|
+
const agent = options.prebetaOrchestrator ? findAgentAny(id) : findAgent(id);
|
|
289
|
+
if (options.prebetaOrchestrator) readRunAny(agent.run_id);
|
|
290
|
+
else readRun(agent.run_id);
|
|
291
|
+
if (agent.ended_at) throw new Error("agent has ended");
|
|
292
|
+
if (agent.headless || !agent.tmux_window_id) throw new Error("agent has no tmux window");
|
|
293
|
+
return { session: agent.tmux_session, windowId: agent.tmux_window_id, nickname: agent.nickname };
|
|
294
|
+
}
|
|
295
|
+
function parseClientFrame(raw) {
|
|
296
|
+
let text;
|
|
297
|
+
if (typeof raw === "string") text = raw;
|
|
298
|
+
else if (Buffer.isBuffer(raw)) text = raw.toString("utf8");
|
|
299
|
+
else if (Array.isArray(raw)) text = Buffer.concat(raw).toString("utf8");
|
|
300
|
+
else if (raw instanceof ArrayBuffer) text = Buffer.from(raw).toString("utf8");
|
|
301
|
+
else return null;
|
|
302
|
+
let parsed;
|
|
303
|
+
try {
|
|
304
|
+
parsed = JSON.parse(text);
|
|
305
|
+
} catch {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
if (!parsed || typeof parsed !== "object") return null;
|
|
309
|
+
const frame = parsed;
|
|
310
|
+
if (frame.t === "i" && typeof frame.d === "string") return { t: "i", d: frame.d };
|
|
311
|
+
if (frame.t === "r" && typeof frame.c === "number" && typeof frame.r === "number") {
|
|
312
|
+
return { t: "r", c: frame.c, r: frame.r };
|
|
313
|
+
}
|
|
314
|
+
return null;
|
|
315
|
+
}
|
|
316
|
+
function tmuxAvailable() {
|
|
317
|
+
try {
|
|
318
|
+
return spawnSync("tmux", ["-V"], { stdio: "ignore" }).status === 0;
|
|
319
|
+
} catch {
|
|
320
|
+
return false;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
function send(ws, frame) {
|
|
324
|
+
if (ws.readyState === ws.OPEN) ws.send(JSON.stringify(frame));
|
|
325
|
+
}
|
|
326
|
+
function disposeBridge(bridge) {
|
|
327
|
+
try {
|
|
328
|
+
bridge.term.kill();
|
|
329
|
+
} catch {
|
|
330
|
+
}
|
|
331
|
+
try {
|
|
332
|
+
execFileSync("tmux", ["kill-session", "-t", bridge.viewer], { stdio: "ignore" });
|
|
333
|
+
} catch {
|
|
334
|
+
}
|
|
335
|
+
try {
|
|
336
|
+
if (bridge.ws.readyState === bridge.ws.OPEN) bridge.ws.close();
|
|
337
|
+
} catch {
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
function openBridge(ws, id, bridges, options) {
|
|
341
|
+
let target;
|
|
342
|
+
try {
|
|
343
|
+
target = resolveTerminalTarget(id, options);
|
|
344
|
+
} catch (err) {
|
|
345
|
+
send(ws, { t: "e", m: err instanceof Error ? err.message : "agent not found" });
|
|
346
|
+
ws.close();
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
if (!tmuxAvailable()) {
|
|
350
|
+
send(ws, { t: "e", m: "tmux is not available on this host" });
|
|
351
|
+
ws.close();
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
const viewer = `reevesweb_${randomBytes(4).toString("hex")}`;
|
|
355
|
+
try {
|
|
356
|
+
execFileSync("tmux", ["new-session", "-d", "-s", viewer, "-t", target.session], { stdio: "ignore" });
|
|
357
|
+
execFileSync("tmux", ["select-window", "-t", `${viewer}:${target.windowId}`], { stdio: "ignore" });
|
|
358
|
+
} catch {
|
|
359
|
+
try {
|
|
360
|
+
execFileSync("tmux", ["kill-session", "-t", viewer], { stdio: "ignore" });
|
|
361
|
+
} catch {
|
|
362
|
+
}
|
|
363
|
+
send(ws, { t: "e", m: "could not open a tmux view for this agent" });
|
|
364
|
+
ws.close();
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
const term = pty.spawn("tmux", ["attach-session", "-t", viewer], {
|
|
368
|
+
name: "xterm-256color",
|
|
369
|
+
cols: 80,
|
|
370
|
+
rows: 24,
|
|
371
|
+
env: process.env
|
|
372
|
+
});
|
|
373
|
+
const bridge = { ws, term, viewer };
|
|
374
|
+
bridges.add(bridge);
|
|
375
|
+
let cleaned = false;
|
|
376
|
+
const cleanup = () => {
|
|
377
|
+
if (cleaned) return;
|
|
378
|
+
cleaned = true;
|
|
379
|
+
bridges.delete(bridge);
|
|
380
|
+
disposeBridge(bridge);
|
|
381
|
+
};
|
|
382
|
+
term.onData((data) => send(ws, { t: "o", d: data }));
|
|
383
|
+
term.onExit(({ exitCode }) => {
|
|
384
|
+
send(ws, { t: "x", code: exitCode });
|
|
385
|
+
cleanup();
|
|
386
|
+
});
|
|
387
|
+
ws.on("message", (raw) => {
|
|
388
|
+
const frame = parseClientFrame(raw);
|
|
389
|
+
if (!frame) return;
|
|
390
|
+
if (frame.t === "i") {
|
|
391
|
+
term.write(frame.d);
|
|
392
|
+
} else {
|
|
393
|
+
try {
|
|
394
|
+
term.resize(Math.max(1, Math.floor(frame.c)), Math.max(1, Math.floor(frame.r)));
|
|
395
|
+
} catch {
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
});
|
|
399
|
+
ws.on("close", cleanup);
|
|
400
|
+
ws.on("error", cleanup);
|
|
401
|
+
}
|
|
402
|
+
function attachTerminalBridge(server, getPort, options = {}) {
|
|
403
|
+
const wss = new WebSocketServer({ noServer: true });
|
|
404
|
+
const bridges = /* @__PURE__ */ new Set();
|
|
405
|
+
server.on("upgrade", (req, socket, head) => {
|
|
406
|
+
const port = getPort();
|
|
407
|
+
if (!isAllowedHostHeader(req.headers.host) || !isAllowedOrigin(req.headers.origin, port)) {
|
|
408
|
+
socket.destroy();
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
let pathname;
|
|
412
|
+
let id;
|
|
413
|
+
try {
|
|
414
|
+
const url = new URL2(req.url ?? "/", `http://127.0.0.1:${port}`);
|
|
415
|
+
pathname = url.pathname;
|
|
416
|
+
id = url.searchParams.get("id") ?? "";
|
|
417
|
+
} catch {
|
|
418
|
+
socket.destroy();
|
|
419
|
+
return;
|
|
420
|
+
}
|
|
421
|
+
if (pathname !== "/term") {
|
|
422
|
+
socket.destroy();
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
wss.handleUpgrade(req, socket, head, (ws) => openBridge(ws, id, bridges, options));
|
|
426
|
+
});
|
|
427
|
+
return {
|
|
428
|
+
close: () => new Promise((resolve) => {
|
|
429
|
+
for (const bridge of bridges) disposeBridge(bridge);
|
|
430
|
+
bridges.clear();
|
|
431
|
+
wss.close(() => resolve());
|
|
432
|
+
})
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// src/web/server.ts
|
|
437
|
+
var HOST = "127.0.0.1";
|
|
438
|
+
var DEFAULT_PORT = 8080;
|
|
439
|
+
var DEFAULT_RANGE = 10;
|
|
440
|
+
var POLL_MS = 1500;
|
|
441
|
+
var MAX_BODY = 64 * 1024;
|
|
442
|
+
var DEFAULT_WEB_ROOT = join(dirname(fileURLToPath(import.meta.url)), "web");
|
|
443
|
+
var STATIC_ROUTES = {
|
|
444
|
+
"/app.css": { file: "app.css", type: "text/css; charset=utf-8" },
|
|
445
|
+
"/app.js": { file: "app.js", type: "text/javascript; charset=utf-8" },
|
|
446
|
+
"/xterm.css": { file: "xterm.css", type: "text/css; charset=utf-8" },
|
|
447
|
+
"/xterm.js": { file: "xterm.js", type: "text/javascript; charset=utf-8" },
|
|
448
|
+
"/addon-fit.js": { file: "addon-fit.js", type: "text/javascript; charset=utf-8" },
|
|
449
|
+
"/brand-duck.json": { file: "brand-duck.json", type: "application/json; charset=utf-8" }
|
|
450
|
+
};
|
|
451
|
+
function errMessage(err) {
|
|
452
|
+
return err instanceof Error ? err.message : String(err);
|
|
453
|
+
}
|
|
454
|
+
function send2(res, status, body, contentType) {
|
|
455
|
+
res.writeHead(status, {
|
|
456
|
+
"content-type": contentType,
|
|
457
|
+
"cache-control": "no-store",
|
|
458
|
+
"x-content-type-options": "nosniff"
|
|
459
|
+
});
|
|
460
|
+
res.end(body);
|
|
461
|
+
}
|
|
462
|
+
function sendJson(res, status, obj) {
|
|
463
|
+
send2(res, status, JSON.stringify(obj), "application/json; charset=utf-8");
|
|
464
|
+
}
|
|
465
|
+
function webLanguagePayload() {
|
|
466
|
+
const current = loadConfig().global.language;
|
|
467
|
+
return {
|
|
468
|
+
current,
|
|
469
|
+
languages: LANGUAGE_OPTIONS,
|
|
470
|
+
translations: localeCatalog(current)
|
|
471
|
+
};
|
|
472
|
+
}
|
|
473
|
+
function serveAsset(res, file, type, ctx) {
|
|
474
|
+
let buf = ctx.cache.get(file);
|
|
475
|
+
if (!buf) {
|
|
476
|
+
try {
|
|
477
|
+
buf = readFileSync(join(ctx.webRoot, file));
|
|
478
|
+
} catch {
|
|
479
|
+
send2(res, 404, "asset missing; run the build", "text/plain; charset=utf-8");
|
|
480
|
+
return;
|
|
481
|
+
}
|
|
482
|
+
ctx.cache.set(file, buf);
|
|
483
|
+
}
|
|
484
|
+
send2(res, 200, buf, type);
|
|
485
|
+
}
|
|
486
|
+
function serveIndex(res, ctx) {
|
|
487
|
+
let buf = ctx.cache.get("index.html");
|
|
488
|
+
if (!buf) {
|
|
489
|
+
try {
|
|
490
|
+
buf = readFileSync(join(ctx.webRoot, "index.html"));
|
|
491
|
+
ctx.cache.set("index.html", buf);
|
|
492
|
+
} catch {
|
|
493
|
+
send2(res, 200, placeholderPage(), "text/html; charset=utf-8");
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
send2(res, 200, buf, "text/html; charset=utf-8");
|
|
498
|
+
}
|
|
499
|
+
function createSseHub(prebetaOrchestrator) {
|
|
500
|
+
const clients = /* @__PURE__ */ new Set();
|
|
501
|
+
let timer = null;
|
|
502
|
+
let last = "";
|
|
503
|
+
const snapshot = () => {
|
|
504
|
+
autoCleanupRuns({ includeAllModes: prebetaOrchestrator, cleanStale: false });
|
|
505
|
+
return JSON.stringify(buildWebState({ prebetaOrchestrator }));
|
|
506
|
+
};
|
|
507
|
+
const write = (res, payload) => {
|
|
508
|
+
try {
|
|
509
|
+
res.write(`data: ${payload}
|
|
510
|
+
|
|
511
|
+
`);
|
|
512
|
+
} catch {
|
|
513
|
+
}
|
|
514
|
+
};
|
|
515
|
+
const tick = () => {
|
|
516
|
+
const payload = snapshot();
|
|
517
|
+
if (payload === last) return;
|
|
518
|
+
last = payload;
|
|
519
|
+
for (const res of clients) write(res, payload);
|
|
520
|
+
};
|
|
521
|
+
const start = () => {
|
|
522
|
+
if (timer) return;
|
|
523
|
+
last = snapshot();
|
|
524
|
+
timer = setInterval(tick, POLL_MS);
|
|
525
|
+
timer.unref();
|
|
526
|
+
};
|
|
527
|
+
const stop = () => {
|
|
528
|
+
if (timer) {
|
|
529
|
+
clearInterval(timer);
|
|
530
|
+
timer = null;
|
|
531
|
+
}
|
|
532
|
+
};
|
|
533
|
+
return {
|
|
534
|
+
add(res) {
|
|
535
|
+
res.writeHead(200, {
|
|
536
|
+
"content-type": "text/event-stream",
|
|
537
|
+
"cache-control": "no-store",
|
|
538
|
+
"connection": "keep-alive",
|
|
539
|
+
"x-content-type-options": "nosniff"
|
|
540
|
+
});
|
|
541
|
+
write(res, snapshot());
|
|
542
|
+
clients.add(res);
|
|
543
|
+
start();
|
|
544
|
+
res.on("close", () => {
|
|
545
|
+
clients.delete(res);
|
|
546
|
+
if (clients.size === 0) stop();
|
|
547
|
+
});
|
|
548
|
+
},
|
|
549
|
+
close() {
|
|
550
|
+
stop();
|
|
551
|
+
for (const res of clients) {
|
|
552
|
+
try {
|
|
553
|
+
res.end();
|
|
554
|
+
} catch {
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
clients.clear();
|
|
558
|
+
}
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
async function readJsonBody(req) {
|
|
562
|
+
const chunks = [];
|
|
563
|
+
let size = 0;
|
|
564
|
+
for await (const chunk of req) {
|
|
565
|
+
const buf = chunk;
|
|
566
|
+
size += buf.length;
|
|
567
|
+
if (size > MAX_BODY) throw new Error("request body too large");
|
|
568
|
+
chunks.push(buf);
|
|
569
|
+
}
|
|
570
|
+
if (chunks.length === 0) return {};
|
|
571
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
572
|
+
if (!parsed || typeof parsed !== "object") throw new Error("expected a JSON object");
|
|
573
|
+
return parsed;
|
|
574
|
+
}
|
|
575
|
+
function sanitizeNickname(raw) {
|
|
576
|
+
return raw.trim().replace(/[^a-zA-Z0-9_-]/g, "-").replace(/-+/g, "-").slice(0, 40);
|
|
577
|
+
}
|
|
578
|
+
function sanitizeRunName(raw) {
|
|
579
|
+
return raw.trim().replace(/[^\p{L}\p{N} _.-]/gu, " ").replace(/\s+/g, " ").trim().slice(0, 80).trim();
|
|
580
|
+
}
|
|
581
|
+
function normalizeModel(provider, raw) {
|
|
582
|
+
const model = typeof raw === "string" ? raw.trim() : "";
|
|
583
|
+
if (!modelValuesForProvider(provider).includes(model)) {
|
|
584
|
+
throw new Error("unknown model for provider");
|
|
585
|
+
}
|
|
586
|
+
return model;
|
|
587
|
+
}
|
|
588
|
+
function normalizePermissionsInput(raw) {
|
|
589
|
+
if (raw === void 0 || raw === null || raw === "") return void 0;
|
|
590
|
+
if (raw === "ask" || raw === "skip") return raw;
|
|
591
|
+
throw new Error("unknown permission mode");
|
|
592
|
+
}
|
|
593
|
+
async function createTerminal(body, ctx) {
|
|
594
|
+
const provider = body.provider;
|
|
595
|
+
const normalizedProvider = normalizeProvider(provider);
|
|
596
|
+
if (!normalizedProvider) throw new Error("unknown provider");
|
|
597
|
+
const model = normalizeModel(normalizedProvider, body.model);
|
|
598
|
+
const permissions = normalizePermissionsInput(body.permissions);
|
|
599
|
+
const nickname = sanitizeNickname(typeof body.nickname === "string" ? body.nickname : "");
|
|
600
|
+
const runName = sanitizeRunName(typeof body.run_name === "string" ? body.run_name : "");
|
|
601
|
+
const prompt = typeof body.prompt === "string" ? body.prompt : "";
|
|
602
|
+
const runId = typeof body.run_id === "string" && body.run_id ? body.run_id : null;
|
|
603
|
+
if (runId) {
|
|
604
|
+
const run = ctx.prebetaOrchestrator ? readRunAny(runId) : readRun(runId);
|
|
605
|
+
const mode2 = run.mode === "spawner" ? "spawner" : "orchestrator";
|
|
606
|
+
if (mode2 === "orchestrator") {
|
|
607
|
+
if (!ctx.orchestratorRuntime) throw new Error("PRE-BETA orchestrator web mode is not enabled");
|
|
608
|
+
if (!isOrchestratorWebProvider(normalizedProvider)) throw new Error("provider is not supported in PRE-BETA orchestrator mode");
|
|
609
|
+
const agent2 = ctx.orchestratorRuntime.spawnWorker({
|
|
610
|
+
run_id: runId,
|
|
611
|
+
provider: normalizedProvider,
|
|
612
|
+
nickname: nickname || void 0,
|
|
613
|
+
model,
|
|
614
|
+
permissions,
|
|
615
|
+
task: prompt
|
|
616
|
+
});
|
|
617
|
+
return { id: agent2.id, run_id: agent2.run_id };
|
|
618
|
+
}
|
|
619
|
+
const agent = spawnWorker({ run_id: runId, provider: normalizedProvider, nickname: nickname || void 0, model, permissions, task: prompt });
|
|
620
|
+
return { id: agent.id, run_id: agent.run_id };
|
|
621
|
+
}
|
|
622
|
+
const mode = body.mode === "orchestrator" ? "orchestrator" : "spawner";
|
|
623
|
+
const workingDir = typeof body.working_dir === "string" && body.working_dir.trim() ? body.working_dir.trim() : process.cwd();
|
|
624
|
+
if (mode === "orchestrator") {
|
|
625
|
+
if (!ctx.prebetaOrchestrator || !ctx.orchestratorRuntime) throw new Error("PRE-BETA orchestrator web mode is not enabled");
|
|
626
|
+
if (!isOrchestratorWebProvider(normalizedProvider)) throw new Error("provider is not supported in PRE-BETA orchestrator mode");
|
|
627
|
+
const result2 = ctx.orchestratorRuntime.startRun({
|
|
628
|
+
mode: "orchestrator",
|
|
629
|
+
name: runName || nickname || providerDisplayName(normalizedProvider),
|
|
630
|
+
working_dir: workingDir,
|
|
631
|
+
root: { provider: normalizedProvider, nickname: nickname || void 0, model, permissions, task: prompt }
|
|
632
|
+
});
|
|
633
|
+
const root2 = result2.agents[0];
|
|
634
|
+
if (!root2) throw new Error("run created no agent");
|
|
635
|
+
return { id: root2.id, run_id: result2.run.id };
|
|
636
|
+
}
|
|
637
|
+
const result = startRun({
|
|
638
|
+
mode: "spawner",
|
|
639
|
+
name: runName || nickname || providerDisplayName(normalizedProvider),
|
|
640
|
+
working_dir: workingDir,
|
|
641
|
+
root: { provider: normalizedProvider, nickname: nickname || void 0, model, permissions, task: prompt }
|
|
642
|
+
});
|
|
643
|
+
const root = result.agents[0];
|
|
644
|
+
if (!root) throw new Error("run created no agent");
|
|
645
|
+
return { id: root.id, run_id: result.run.id };
|
|
646
|
+
}
|
|
647
|
+
function requireConfirm(body) {
|
|
648
|
+
if (body.confirm !== true) throw new Error("confirmation required");
|
|
649
|
+
}
|
|
650
|
+
function updateLanguage(body) {
|
|
651
|
+
if (!isLanguageCode(body.language)) throw new Error("unknown language");
|
|
652
|
+
const cfg = loadConfig();
|
|
653
|
+
cfg.global.language = body.language;
|
|
654
|
+
saveConfig(cfg);
|
|
655
|
+
return webLanguagePayload();
|
|
656
|
+
}
|
|
657
|
+
function killTerminal(id, ctx) {
|
|
658
|
+
const agent = ctx.prebetaOrchestrator ? findAgentAny(id) : findAgent(id);
|
|
659
|
+
const run = ctx.prebetaOrchestrator ? readRunAny(agent.run_id) : readRun(agent.run_id);
|
|
660
|
+
if (run.mode === "spawner") {
|
|
661
|
+
killAgent(id);
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
if (!ctx.orchestratorRuntime) throw new Error("PRE-BETA orchestrator web mode is not enabled");
|
|
665
|
+
ctx.orchestratorRuntime.killAgent(id);
|
|
666
|
+
}
|
|
667
|
+
function deleteTerminal(id, ctx) {
|
|
668
|
+
const agent = ctx.prebetaOrchestrator ? findAgentAny(id) : findAgent(id);
|
|
669
|
+
if (!agent.ended_at) throw new Error("Stop agent before deleting it");
|
|
670
|
+
deleteAgent(id, { includeAllModes: ctx.prebetaOrchestrator });
|
|
671
|
+
}
|
|
672
|
+
function stopWebRun(id, ctx) {
|
|
673
|
+
const run = ctx.prebetaOrchestrator ? readRunAny(id) : readRun(id);
|
|
674
|
+
if (run.mode === "spawner") {
|
|
675
|
+
stopRun(id);
|
|
676
|
+
return;
|
|
677
|
+
}
|
|
678
|
+
if (!ctx.orchestratorRuntime) throw new Error("PRE-BETA orchestrator web mode is not enabled");
|
|
679
|
+
ctx.orchestratorRuntime.stopRun(id);
|
|
680
|
+
}
|
|
681
|
+
function deleteWebRun(id, ctx) {
|
|
682
|
+
const run = ctx.prebetaOrchestrator ? readRunAny(id) : readRun(id);
|
|
683
|
+
if (run.status !== "ended" && run.ended_at === null) throw new Error("Stop run before deleting it");
|
|
684
|
+
archiveAndRemoveRun(id, "ended");
|
|
685
|
+
}
|
|
686
|
+
function deleteHistoryRecord(id, ctx) {
|
|
687
|
+
const history = listRunHistory({ includeAllModes: ctx.prebetaOrchestrator });
|
|
688
|
+
if (!history.some((record) => record.id === id)) throw new Error("history record not found");
|
|
689
|
+
deleteRunHistory(id);
|
|
690
|
+
}
|
|
691
|
+
async function handleRequest(req, res, ctx) {
|
|
692
|
+
if (!isAllowedHostHeader(req.headers.host)) {
|
|
693
|
+
send2(res, 403, "forbidden host", "text/plain; charset=utf-8");
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
if (isStateChangingMethod(req.method) && !isAllowedOrigin(req.headers.origin, ctx.port())) {
|
|
697
|
+
send2(res, 403, "forbidden origin", "text/plain; charset=utf-8");
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
const path = (req.url ?? "/").split("?")[0];
|
|
701
|
+
const method = req.method ?? "GET";
|
|
702
|
+
if (method === "GET" && (path === "/" || path === "/index.html")) {
|
|
703
|
+
serveIndex(res, ctx);
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
const asset = STATIC_ROUTES[path];
|
|
707
|
+
if (method === "GET" && asset) {
|
|
708
|
+
serveAsset(res, asset.file, asset.type, ctx);
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
if (method === "GET" && path === "/api/state") {
|
|
712
|
+
autoCleanupRuns({ includeAllModes: ctx.prebetaOrchestrator, cleanStale: false });
|
|
713
|
+
sendJson(res, 200, {
|
|
714
|
+
...buildWebState({ prebetaOrchestrator: ctx.prebetaOrchestrator }),
|
|
715
|
+
providers: listWebProviders(),
|
|
716
|
+
prebeta: { orchestrator: ctx.prebetaOrchestrator },
|
|
717
|
+
language: webLanguagePayload()
|
|
718
|
+
});
|
|
719
|
+
return;
|
|
720
|
+
}
|
|
721
|
+
if (method === "GET" && path === "/api/events") {
|
|
722
|
+
ctx.sse.add(res);
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
if (method === "GET" && path === "/healthz") {
|
|
726
|
+
send2(res, 200, "ok", "text/plain; charset=utf-8");
|
|
727
|
+
return;
|
|
728
|
+
}
|
|
729
|
+
if (method === "POST" && path === "/api/terminals") {
|
|
730
|
+
try {
|
|
731
|
+
const body = await readJsonBody(req);
|
|
732
|
+
sendJson(res, 200, await createTerminal(body, ctx));
|
|
733
|
+
} catch (err) {
|
|
734
|
+
sendJson(res, 400, { error: errMessage(err) });
|
|
735
|
+
}
|
|
736
|
+
return;
|
|
737
|
+
}
|
|
738
|
+
if (method === "POST" && path === "/api/language") {
|
|
739
|
+
try {
|
|
740
|
+
const body = await readJsonBody(req);
|
|
741
|
+
sendJson(res, 200, updateLanguage(body));
|
|
742
|
+
} catch (err) {
|
|
743
|
+
sendJson(res, 400, { error: errMessage(err) });
|
|
744
|
+
}
|
|
745
|
+
return;
|
|
746
|
+
}
|
|
747
|
+
const killMatch = path.match(/^\/api\/terminals\/([^/]+)\/kill$/);
|
|
748
|
+
if (method === "POST" && killMatch) {
|
|
749
|
+
try {
|
|
750
|
+
const body = await readJsonBody(req);
|
|
751
|
+
requireConfirm(body);
|
|
752
|
+
killTerminal(decodeURIComponent(killMatch[1]), ctx);
|
|
753
|
+
sendJson(res, 200, { ok: true });
|
|
754
|
+
} catch (err) {
|
|
755
|
+
sendJson(res, 400, { error: errMessage(err) });
|
|
756
|
+
}
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
const deleteTerminalMatch = path.match(/^\/api\/terminals\/([^/]+)\/delete$/);
|
|
760
|
+
if (method === "POST" && deleteTerminalMatch) {
|
|
761
|
+
try {
|
|
762
|
+
const body = await readJsonBody(req);
|
|
763
|
+
requireConfirm(body);
|
|
764
|
+
deleteTerminal(decodeURIComponent(deleteTerminalMatch[1]), ctx);
|
|
765
|
+
sendJson(res, 200, { ok: true });
|
|
766
|
+
} catch (err) {
|
|
767
|
+
sendJson(res, 400, { error: errMessage(err) });
|
|
768
|
+
}
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
const stopMatch = path.match(/^\/api\/runs\/([^/]+)\/stop$/);
|
|
772
|
+
if (method === "POST" && stopMatch) {
|
|
773
|
+
try {
|
|
774
|
+
const body = await readJsonBody(req);
|
|
775
|
+
requireConfirm(body);
|
|
776
|
+
stopWebRun(decodeURIComponent(stopMatch[1]), ctx);
|
|
777
|
+
sendJson(res, 200, { ok: true });
|
|
778
|
+
} catch (err) {
|
|
779
|
+
sendJson(res, 400, { error: errMessage(err) });
|
|
780
|
+
}
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
const deleteRunMatch = path.match(/^\/api\/runs\/([^/]+)\/delete$/);
|
|
784
|
+
if (method === "POST" && deleteRunMatch) {
|
|
785
|
+
try {
|
|
786
|
+
const body = await readJsonBody(req);
|
|
787
|
+
requireConfirm(body);
|
|
788
|
+
deleteWebRun(decodeURIComponent(deleteRunMatch[1]), ctx);
|
|
789
|
+
sendJson(res, 200, { ok: true });
|
|
790
|
+
} catch (err) {
|
|
791
|
+
sendJson(res, 400, { error: errMessage(err) });
|
|
792
|
+
}
|
|
793
|
+
return;
|
|
794
|
+
}
|
|
795
|
+
const deleteHistoryMatch = path.match(/^\/api\/history\/([^/]+)\/delete$/);
|
|
796
|
+
if (method === "POST" && deleteHistoryMatch) {
|
|
797
|
+
try {
|
|
798
|
+
const body = await readJsonBody(req);
|
|
799
|
+
requireConfirm(body);
|
|
800
|
+
deleteHistoryRecord(decodeURIComponent(deleteHistoryMatch[1]), ctx);
|
|
801
|
+
sendJson(res, 200, { ok: true });
|
|
802
|
+
} catch (err) {
|
|
803
|
+
sendJson(res, 400, { error: errMessage(err) });
|
|
804
|
+
}
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
send2(res, 404, "not found", "text/plain; charset=utf-8");
|
|
808
|
+
}
|
|
809
|
+
function listenWithFallback(server, basePort, range) {
|
|
810
|
+
return new Promise((resolve, reject) => {
|
|
811
|
+
let port = basePort;
|
|
812
|
+
const attempt = () => {
|
|
813
|
+
const onError = (err) => {
|
|
814
|
+
if (err.code === "EADDRINUSE" && port < basePort + range - 1) {
|
|
815
|
+
port += 1;
|
|
816
|
+
setTimeout(attempt, 0);
|
|
817
|
+
return;
|
|
818
|
+
}
|
|
819
|
+
reject(err);
|
|
820
|
+
};
|
|
821
|
+
server.once("error", onError);
|
|
822
|
+
server.listen(port, HOST, () => {
|
|
823
|
+
server.removeListener("error", onError);
|
|
824
|
+
resolve(port);
|
|
825
|
+
});
|
|
826
|
+
};
|
|
827
|
+
attempt();
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
async function startWebServer(options = {}) {
|
|
831
|
+
const basePort = options.port && Number.isFinite(options.port) ? options.port : DEFAULT_PORT;
|
|
832
|
+
const range = options.range && options.range > 0 ? options.range : DEFAULT_RANGE;
|
|
833
|
+
const webRoot = options.webRoot ?? DEFAULT_WEB_ROOT;
|
|
834
|
+
const prebetaOrchestrator = options.prebetaOrchestrator === true;
|
|
835
|
+
const orchestratorRuntime = prebetaOrchestrator ? await loadWebOrchestratorRuntime(options.orchestratorRuntime) : void 0;
|
|
836
|
+
const cache = /* @__PURE__ */ new Map();
|
|
837
|
+
const sse = createSseHub(prebetaOrchestrator);
|
|
838
|
+
const sockets = /* @__PURE__ */ new Set();
|
|
839
|
+
let boundPort = basePort;
|
|
840
|
+
const ctx = {
|
|
841
|
+
port: () => boundPort,
|
|
842
|
+
webRoot,
|
|
843
|
+
cache,
|
|
844
|
+
sse,
|
|
845
|
+
prebetaOrchestrator,
|
|
846
|
+
orchestratorRuntime
|
|
847
|
+
};
|
|
848
|
+
const server = createServer((req, res) => {
|
|
849
|
+
handleRequest(req, res, ctx).catch(() => {
|
|
850
|
+
try {
|
|
851
|
+
send2(res, 500, "internal error", "text/plain; charset=utf-8");
|
|
852
|
+
} catch {
|
|
853
|
+
}
|
|
854
|
+
});
|
|
855
|
+
});
|
|
856
|
+
server.on("connection", (socket) => {
|
|
857
|
+
sockets.add(socket);
|
|
858
|
+
socket.on("close", () => sockets.delete(socket));
|
|
859
|
+
});
|
|
860
|
+
const bridge = attachTerminalBridge(server, () => boundPort, { prebetaOrchestrator });
|
|
861
|
+
boundPort = await listenWithFallback(server, basePort, range);
|
|
862
|
+
const url = `http://${HOST}:${boundPort}`;
|
|
863
|
+
if (options.open !== false) {
|
|
864
|
+
const { openBrowser } = await import("./open-browser-DRSIJQ37.js");
|
|
865
|
+
openBrowser(url);
|
|
866
|
+
}
|
|
867
|
+
return {
|
|
868
|
+
url,
|
|
869
|
+
port: boundPort,
|
|
870
|
+
close: async () => {
|
|
871
|
+
sse.close();
|
|
872
|
+
await bridge.close();
|
|
873
|
+
await new Promise((resolve) => {
|
|
874
|
+
for (const socket of sockets) socket.destroy();
|
|
875
|
+
server.close(() => resolve());
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
export {
|
|
881
|
+
startWebServer
|
|
882
|
+
};
|
|
883
|
+
//# sourceMappingURL=server-Z2YTGWSX.js.map
|