agent86-web 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +89 -2
- package/dist/agent-process.js +284 -0
- package/dist/agent86.js +77 -0
- package/dist/auth.js +96 -0
- package/dist/cli.js +156 -0
- package/dist/duration.js +9 -0
- package/dist/files.js +69 -0
- package/dist/policy.js +99 -0
- package/dist/public/agent86-logo.png +0 -0
- package/dist/public/assets/engine-uu4Pp8lX.js +6 -0
- package/dist/public/assets/index-B2J10lb0.css +2 -0
- package/dist/public/assets/index-sMw9P5mz.js +107 -0
- package/dist/public/favicon.png +0 -0
- package/dist/public/index.html +15 -0
- package/dist/server.js +324 -0
- package/dist/sessions.js +61 -0
- package/dist/static.js +66 -0
- package/dist/threads.js +79 -0
- package/dist/trust.js +102 -0
- package/dist/updates.js +70 -0
- package/dist/workspaces.js +24 -0
- package/package.json +50 -3
|
Binary file
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="en">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="UTF-8" />
|
|
5
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
6
|
+
<meta name="referrer" content="no-referrer" />
|
|
7
|
+
<link rel="icon" type="image/png" href="/favicon.png" />
|
|
8
|
+
<title>agent86 web</title>
|
|
9
|
+
<script type="module" crossorigin src="/assets/index-sMw9P5mz.js"></script>
|
|
10
|
+
<link rel="stylesheet" crossorigin href="/assets/index-B2J10lb0.css">
|
|
11
|
+
</head>
|
|
12
|
+
<body>
|
|
13
|
+
<div id="root"></div>
|
|
14
|
+
</body>
|
|
15
|
+
</html>
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
// The bridge's HTTP and WebSocket server (docs/ARCHITECTURE.md §3.2).
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { createServer } from "node:http";
|
|
4
|
+
import { dirname } from "node:path";
|
|
5
|
+
import { WebSocketServer } from "ws";
|
|
6
|
+
import { AgentProcess, MAX_MESSAGE_BYTES } from "./agent-process.js";
|
|
7
|
+
import { MIN_AGENT86_VERSION } from "./agent86.js";
|
|
8
|
+
import { Auth } from "./auth.js";
|
|
9
|
+
import { listDirectories, matchFiles, walkFiles } from "./files.js";
|
|
10
|
+
import { listSessions } from "./sessions.js";
|
|
11
|
+
import { serveStatic } from "./static.js";
|
|
12
|
+
import { ThreadRegistry } from "./threads.js";
|
|
13
|
+
import { readProjectConfig, TrustStore } from "./trust.js";
|
|
14
|
+
import { checkForUpdates } from "./updates.js";
|
|
15
|
+
import { realpath, resolveWorkspace, within } from "./workspaces.js";
|
|
16
|
+
export const BRIDGE_VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
17
|
+
const LOOPBACK = new Set(["127.0.0.1", "::1", "localhost"]);
|
|
18
|
+
export const SECURITY_HEADERS = {
|
|
19
|
+
"content-security-policy": "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; " +
|
|
20
|
+
"connect-src 'self'; font-src 'self'; object-src 'none'; frame-ancestors 'none'; " +
|
|
21
|
+
"base-uri 'none'; form-action 'self'",
|
|
22
|
+
"x-frame-options": "DENY",
|
|
23
|
+
"x-content-type-options": "nosniff",
|
|
24
|
+
"referrer-policy": "no-referrer",
|
|
25
|
+
"cross-origin-opener-policy": "same-origin",
|
|
26
|
+
"cross-origin-resource-policy": "same-origin",
|
|
27
|
+
};
|
|
28
|
+
export const DEFAULT_MAX_AGENTS = 8;
|
|
29
|
+
export const DEFAULT_IDLE_TIMEOUT_MS = 15 * 60 * 1000;
|
|
30
|
+
function json(res, status, body) {
|
|
31
|
+
res.writeHead(status, {
|
|
32
|
+
"content-type": "application/json; charset=utf-8",
|
|
33
|
+
"cache-control": "no-store",
|
|
34
|
+
});
|
|
35
|
+
res.end(JSON.stringify(body));
|
|
36
|
+
}
|
|
37
|
+
function readBody(req, limit) {
|
|
38
|
+
return new Promise((resolve, reject) => {
|
|
39
|
+
let size = 0;
|
|
40
|
+
const chunks = [];
|
|
41
|
+
req.on("data", (chunk) => {
|
|
42
|
+
size += chunk.length;
|
|
43
|
+
if (size > limit) {
|
|
44
|
+
reject(new Error("body too large"));
|
|
45
|
+
req.destroy();
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
chunks.push(chunk);
|
|
49
|
+
});
|
|
50
|
+
req.on("end", () => resolve(Buffer.concat(chunks).toString("utf8")));
|
|
51
|
+
req.on("error", reject);
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
function refuseUpgrade(socket, status, reason) {
|
|
55
|
+
socket.end(`HTTP/1.1 ${status} ${reason}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
|
56
|
+
}
|
|
57
|
+
export async function startBridge(options) {
|
|
58
|
+
if (!LOOPBACK.has(options.host)) {
|
|
59
|
+
throw new Error(`--host ${options.host} is refused: agent86-web listens only on loopback in this version. ` +
|
|
60
|
+
"To use it from another device, forward the port over SSH (see the README).");
|
|
61
|
+
}
|
|
62
|
+
if (options.roots.length === 0)
|
|
63
|
+
throw new Error("at least one --root is needed");
|
|
64
|
+
const log = options.log ?? (() => undefined);
|
|
65
|
+
const trust = new TrustStore(options.stateDir);
|
|
66
|
+
/** Newer releases, filled in the background after startup. */
|
|
67
|
+
let updates = {};
|
|
68
|
+
if (options.updateCheck) {
|
|
69
|
+
void checkForUpdates({
|
|
70
|
+
current: { agent86: options.agent86.version, agent86Web: BRIDGE_VERSION },
|
|
71
|
+
...(options.stateDir ? { stateDir: options.stateDir } : {}),
|
|
72
|
+
...(options.latestVersion ? { latestVersion: options.latestVersion } : {}),
|
|
73
|
+
})
|
|
74
|
+
.then((found) => {
|
|
75
|
+
updates = found;
|
|
76
|
+
if (found.agent86)
|
|
77
|
+
log(`agent86 ${found.agent86} is available (running ${options.agent86.version}): npm install -g agent86@latest`);
|
|
78
|
+
if (found.agent86Web)
|
|
79
|
+
log(`agent86-web ${found.agent86Web} is available (running ${BRIDGE_VERSION}): npm install -g agent86-web@latest`);
|
|
80
|
+
})
|
|
81
|
+
.catch(() => undefined);
|
|
82
|
+
}
|
|
83
|
+
/** agent86's arguments for a workspace, hashing its config file right before the spawn. */
|
|
84
|
+
const agentArgs = (workspace) => trust.isTrusted(workspace)
|
|
85
|
+
? [...options.agent86.args, "--trust-project"]
|
|
86
|
+
: [...options.agent86.args];
|
|
87
|
+
const threads = new ThreadRegistry({
|
|
88
|
+
maxAgents: options.maxAgents ?? DEFAULT_MAX_AGENTS,
|
|
89
|
+
idleTimeoutMs: options.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS,
|
|
90
|
+
log,
|
|
91
|
+
spawn: (thread, workspace) => {
|
|
92
|
+
log(`thread ${thread}: starting agent86 in ${workspace}`);
|
|
93
|
+
const agent = new AgentProcess({
|
|
94
|
+
command: options.agent86.command,
|
|
95
|
+
args: agentArgs(workspace),
|
|
96
|
+
workspace,
|
|
97
|
+
realpath,
|
|
98
|
+
log: (line) => log(`thread ${thread}: ${line}`),
|
|
99
|
+
});
|
|
100
|
+
void agent.exited.then((code) => log(`thread ${thread}: agent86 exited (status ${code ?? "unknown"})`));
|
|
101
|
+
return agent;
|
|
102
|
+
},
|
|
103
|
+
});
|
|
104
|
+
/**
|
|
105
|
+
* Session lists, per workspace. Each one costs an agent86 process, so concurrent requests share
|
|
106
|
+
* one, and an answer is reused for a few seconds (docs/SECURITY.md T12).
|
|
107
|
+
*/
|
|
108
|
+
const sessionLists = new Map();
|
|
109
|
+
const sessionsFor = (workspace) => {
|
|
110
|
+
const cached = sessionLists.get(workspace);
|
|
111
|
+
if (cached && Date.now() - cached.at < 3_000)
|
|
112
|
+
return cached.list;
|
|
113
|
+
const list = listSessions(options.agent86.command, agentArgs(workspace), workspace);
|
|
114
|
+
sessionLists.set(workspace, { at: Date.now(), list });
|
|
115
|
+
// A failure is not cached.
|
|
116
|
+
list.catch(() => sessionLists.delete(workspace));
|
|
117
|
+
return list;
|
|
118
|
+
};
|
|
119
|
+
/** Workspace file lists for @ mentions, briefly cached. */
|
|
120
|
+
const fileCache = new Map();
|
|
121
|
+
// Set once the port is known (after listen); requests before that are refused.
|
|
122
|
+
let auth = undefined;
|
|
123
|
+
const server = createServer((req, res) => {
|
|
124
|
+
for (const [name, value] of Object.entries(SECURITY_HEADERS))
|
|
125
|
+
res.setHeader(name, value);
|
|
126
|
+
void handle(req, res).catch((error) => {
|
|
127
|
+
log(`request failed: ${String(error)}`);
|
|
128
|
+
if (!res.headersSent)
|
|
129
|
+
json(res, 500, { error: "internal" });
|
|
130
|
+
else
|
|
131
|
+
res.end();
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
async function handle(req, res) {
|
|
135
|
+
if (!auth?.hostAllowed(req)) {
|
|
136
|
+
json(res, 403, { error: "host_not_allowed" });
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const url = new URL(req.url ?? "/", "http://bridge.invalid");
|
|
140
|
+
if (url.pathname === "/api/login") {
|
|
141
|
+
if (req.method !== "POST")
|
|
142
|
+
return json(res, 405, { error: "method_not_allowed" });
|
|
143
|
+
if (!auth.originAllowed(req) || !Auth.hasCsrfHeader(req)) {
|
|
144
|
+
return json(res, 403, { error: "origin_not_allowed" });
|
|
145
|
+
}
|
|
146
|
+
let token;
|
|
147
|
+
try {
|
|
148
|
+
token = JSON.parse(await readBody(req, 4096)).token;
|
|
149
|
+
}
|
|
150
|
+
catch {
|
|
151
|
+
return json(res, 400, { error: "bad_request" });
|
|
152
|
+
}
|
|
153
|
+
const session = auth.login(token);
|
|
154
|
+
if (!session)
|
|
155
|
+
return json(res, 401, { error: "token_invalid" });
|
|
156
|
+
res.setHeader("set-cookie", Auth.sessionCookie(session));
|
|
157
|
+
return json(res, 200, { ok: true });
|
|
158
|
+
}
|
|
159
|
+
if (url.pathname.startsWith("/api/")) {
|
|
160
|
+
if (!auth.hasSession(req))
|
|
161
|
+
return json(res, 401, { error: "not_signed_in" });
|
|
162
|
+
if (url.pathname === "/api/info" && req.method === "GET") {
|
|
163
|
+
return json(res, 200, {
|
|
164
|
+
bridge: { version: BRIDGE_VERSION },
|
|
165
|
+
agent86: {
|
|
166
|
+
command: options.agent86.command,
|
|
167
|
+
version: options.agent86.version,
|
|
168
|
+
minVersion: MIN_AGENT86_VERSION,
|
|
169
|
+
},
|
|
170
|
+
roots: options.roots,
|
|
171
|
+
defaultWorkspace: options.roots[0],
|
|
172
|
+
updates,
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
if (url.pathname === "/api/workspaces" && req.method === "GET") {
|
|
176
|
+
const requested = url.searchParams.get("path");
|
|
177
|
+
if (!requested) {
|
|
178
|
+
return json(res, 200, {
|
|
179
|
+
path: null,
|
|
180
|
+
parent: null,
|
|
181
|
+
dirs: options.roots.map((root) => ({ name: root, path: root })),
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
const dir = resolveWorkspace(requested, options.roots);
|
|
185
|
+
if (!dir)
|
|
186
|
+
return json(res, 403, { error: "outside_roots" });
|
|
187
|
+
const parentDir = dirname(dir);
|
|
188
|
+
const parent = options.roots.some((root) => root !== dir && within(parentDir, root))
|
|
189
|
+
? parentDir
|
|
190
|
+
: null;
|
|
191
|
+
return json(res, 200, { path: dir, parent, dirs: listDirectories(dir) });
|
|
192
|
+
}
|
|
193
|
+
if (url.pathname === "/api/sessions" && req.method === "GET") {
|
|
194
|
+
const workspace = resolveWorkspace(url.searchParams.get("workspace") ?? "", options.roots);
|
|
195
|
+
if (!workspace)
|
|
196
|
+
return json(res, 403, { error: "outside_roots" });
|
|
197
|
+
try {
|
|
198
|
+
const sessions = await sessionsFor(workspace);
|
|
199
|
+
return json(res, 200, { sessions });
|
|
200
|
+
}
|
|
201
|
+
catch (error) {
|
|
202
|
+
return json(res, 502, { error: "agent86_failed", message: error.message });
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (url.pathname === "/api/trust") {
|
|
206
|
+
if (req.method === "GET") {
|
|
207
|
+
const workspace = url.searchParams.get("workspace");
|
|
208
|
+
if (!workspace)
|
|
209
|
+
return json(res, 200, { projects: trust.list() });
|
|
210
|
+
const dir = resolveWorkspace(workspace, options.roots);
|
|
211
|
+
if (!dir)
|
|
212
|
+
return json(res, 403, { error: "outside_roots" });
|
|
213
|
+
const config = readProjectConfig(dir) ?? null;
|
|
214
|
+
return json(res, 200, { config, trusted: trust.isTrusted(dir) });
|
|
215
|
+
}
|
|
216
|
+
if (req.method === "POST" || req.method === "DELETE") {
|
|
217
|
+
if (!auth.originAllowed(req) || !Auth.hasCsrfHeader(req)) {
|
|
218
|
+
return json(res, 403, { error: "origin_not_allowed" });
|
|
219
|
+
}
|
|
220
|
+
let body;
|
|
221
|
+
try {
|
|
222
|
+
body = JSON.parse(await readBody(req, 4096));
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
return json(res, 400, { error: "bad_request" });
|
|
226
|
+
}
|
|
227
|
+
if (req.method === "DELETE") {
|
|
228
|
+
if (typeof body.path !== "string")
|
|
229
|
+
return json(res, 400, { error: "bad_request" });
|
|
230
|
+
return json(res, trust.revoke(body.path) ? 200 : 404, { projects: trust.list() });
|
|
231
|
+
}
|
|
232
|
+
const dir = typeof body.workspace === "string"
|
|
233
|
+
? resolveWorkspace(body.workspace, options.roots)
|
|
234
|
+
: undefined;
|
|
235
|
+
if (!dir)
|
|
236
|
+
return json(res, 403, { error: "outside_roots" });
|
|
237
|
+
if (typeof body.sha256 !== "string")
|
|
238
|
+
return json(res, 400, { error: "bad_request" });
|
|
239
|
+
if (!trust.trust(dir, body.sha256)) {
|
|
240
|
+
return json(res, 409, {
|
|
241
|
+
error: "config_changed",
|
|
242
|
+
message: "The file changed since you reviewed it. Review it again.",
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
log(`trusted ${dir}/.agent86/config.toml (sha256 ${body.sha256.slice(0, 12)}…)`);
|
|
246
|
+
return json(res, 200, { trusted: true });
|
|
247
|
+
}
|
|
248
|
+
return json(res, 405, { error: "method_not_allowed" });
|
|
249
|
+
}
|
|
250
|
+
if (url.pathname === "/api/shutdown") {
|
|
251
|
+
if (req.method !== "POST")
|
|
252
|
+
return json(res, 405, { error: "method_not_allowed" });
|
|
253
|
+
if (!auth.originAllowed(req) || !Auth.hasCsrfHeader(req)) {
|
|
254
|
+
return json(res, 403, { error: "origin_not_allowed" });
|
|
255
|
+
}
|
|
256
|
+
const stop = options.onShutdownRequested;
|
|
257
|
+
if (!stop)
|
|
258
|
+
return json(res, 501, { error: "not_supported" });
|
|
259
|
+
log("stop requested from the browser");
|
|
260
|
+
res.once("finish", () => setImmediate(stop));
|
|
261
|
+
return json(res, 200, { stopping: true });
|
|
262
|
+
}
|
|
263
|
+
if (url.pathname === "/api/files" && req.method === "GET") {
|
|
264
|
+
const workspace = resolveWorkspace(url.searchParams.get("workspace") ?? "", options.roots);
|
|
265
|
+
if (!workspace)
|
|
266
|
+
return json(res, 403, { error: "outside_roots" });
|
|
267
|
+
let cached = fileCache.get(workspace);
|
|
268
|
+
if (!cached || Date.now() - cached.at > 10_000) {
|
|
269
|
+
cached = { at: Date.now(), files: walkFiles(workspace) };
|
|
270
|
+
fileCache.set(workspace, cached);
|
|
271
|
+
}
|
|
272
|
+
return json(res, 200, { files: matchFiles(cached.files, url.searchParams.get("q") ?? "") });
|
|
273
|
+
}
|
|
274
|
+
return json(res, 404, { error: "not_found" });
|
|
275
|
+
}
|
|
276
|
+
if (url.pathname.startsWith("/acp/"))
|
|
277
|
+
return json(res, 426, { error: "websocket_required" });
|
|
278
|
+
if (req.method !== "GET" && req.method !== "HEAD")
|
|
279
|
+
return json(res, 405, { error: "method_not_allowed" });
|
|
280
|
+
serveStatic(options.publicDir, url.pathname, res);
|
|
281
|
+
}
|
|
282
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_MESSAGE_BYTES });
|
|
283
|
+
server.on("upgrade", (req, socket, head) => {
|
|
284
|
+
const url = new URL(req.url ?? "/", "http://bridge.invalid");
|
|
285
|
+
if (!auth?.hostAllowed(req))
|
|
286
|
+
return refuseUpgrade(socket, 403, "Forbidden");
|
|
287
|
+
if (!auth.originAllowed(req))
|
|
288
|
+
return refuseUpgrade(socket, 403, "Forbidden");
|
|
289
|
+
if (!auth.hasSession(req))
|
|
290
|
+
return refuseUpgrade(socket, 401, "Unauthorized");
|
|
291
|
+
const match = /^\/acp\/([A-Za-z0-9_-]{1,64})$/.exec(url.pathname);
|
|
292
|
+
if (!match)
|
|
293
|
+
return refuseUpgrade(socket, 404, "Not Found");
|
|
294
|
+
const requested = url.searchParams.get("workspace") ?? options.roots[0];
|
|
295
|
+
const workspace = resolveWorkspace(requested, options.roots);
|
|
296
|
+
if (!workspace)
|
|
297
|
+
return refuseUpgrade(socket, 403, "Forbidden");
|
|
298
|
+
const fresh = url.searchParams.get("fresh") === "1";
|
|
299
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
300
|
+
const result = threads.attach(match[1], workspace, ws, fresh);
|
|
301
|
+
if (!result.ok)
|
|
302
|
+
ws.close(1013, result.reason.slice(0, 120));
|
|
303
|
+
});
|
|
304
|
+
});
|
|
305
|
+
await new Promise((resolve, reject) => {
|
|
306
|
+
server.once("error", reject);
|
|
307
|
+
server.listen(options.port, options.host, () => resolve());
|
|
308
|
+
});
|
|
309
|
+
const port = server.address().port;
|
|
310
|
+
auth = new Auth({ port, devOrigin: options.devOrigin });
|
|
311
|
+
const host = options.host === "::1" ? "[::1]" : options.host === "localhost" ? "127.0.0.1" : options.host;
|
|
312
|
+
const base = options.devOrigin ? new URL(options.devOrigin).origin : `http://${host}:${port}`;
|
|
313
|
+
return {
|
|
314
|
+
port,
|
|
315
|
+
url: `${base}/#token=${auth.launchToken}`,
|
|
316
|
+
async close() {
|
|
317
|
+
await threads.stopAll();
|
|
318
|
+
for (const client of wss.clients)
|
|
319
|
+
client.terminate();
|
|
320
|
+
wss.close();
|
|
321
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
322
|
+
},
|
|
323
|
+
};
|
|
324
|
+
}
|
package/dist/sessions.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// The session list for a workspace, from a short-lived `agent86 acp` (docs/ARCHITECTURE.md §3.3).
|
|
2
|
+
// The bridge never reads agent86's database itself (docs/adr/0003-standalone-bridge.md).
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
import { needsShell } from "./agent86.js";
|
|
5
|
+
export async function listSessions(command, args, workspace, timeoutMs = 20_000) {
|
|
6
|
+
const child = spawn(command, [...args, "acp"], {
|
|
7
|
+
cwd: workspace,
|
|
8
|
+
stdio: ["pipe", "pipe", "ignore"],
|
|
9
|
+
shell: needsShell(command),
|
|
10
|
+
windowsHide: true,
|
|
11
|
+
});
|
|
12
|
+
child.stdin.on("error", () => undefined);
|
|
13
|
+
const send = (message) => child.stdin.write(`${JSON.stringify(message)}\n`);
|
|
14
|
+
try {
|
|
15
|
+
return await new Promise((resolve, reject) => {
|
|
16
|
+
const timer = setTimeout(() => reject(new Error("agent86 did not list its sessions in time")), timeoutMs);
|
|
17
|
+
let buffer = "";
|
|
18
|
+
child.on("error", (error) => {
|
|
19
|
+
clearTimeout(timer);
|
|
20
|
+
reject(error);
|
|
21
|
+
});
|
|
22
|
+
child.on("exit", () => {
|
|
23
|
+
clearTimeout(timer);
|
|
24
|
+
reject(new Error("agent86 exited before listing its sessions"));
|
|
25
|
+
});
|
|
26
|
+
child.stdout.setEncoding("utf8").on("data", (chunk) => {
|
|
27
|
+
buffer += chunk;
|
|
28
|
+
let newline;
|
|
29
|
+
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
30
|
+
const line = buffer.slice(0, newline);
|
|
31
|
+
buffer = buffer.slice(newline + 1);
|
|
32
|
+
let message;
|
|
33
|
+
try {
|
|
34
|
+
message = JSON.parse(line);
|
|
35
|
+
}
|
|
36
|
+
catch {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
if (message.id === 0) {
|
|
40
|
+
// Initialized: now ask for the list.
|
|
41
|
+
send({ jsonrpc: "2.0", id: 1, method: "session/list", params: { cwd: workspace } });
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (message.id !== 1)
|
|
45
|
+
continue;
|
|
46
|
+
clearTimeout(timer);
|
|
47
|
+
if (message.error)
|
|
48
|
+
reject(new Error(message.error.message ?? "agent86 refused to list sessions"));
|
|
49
|
+
else
|
|
50
|
+
resolve(message.result?.sessions ?? []);
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
send({ jsonrpc: "2.0", id: 0, method: "initialize", params: { protocolVersion: 1 } });
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
finally {
|
|
57
|
+
child.stdin.end();
|
|
58
|
+
const timer = setTimeout(() => child.kill(), 2_000);
|
|
59
|
+
child.once("exit", () => clearTimeout(timer));
|
|
60
|
+
}
|
|
61
|
+
}
|
package/dist/static.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Serves the built web client. Paths are confined to the public directory.
|
|
2
|
+
import { createReadStream, statSync } from "node:fs";
|
|
3
|
+
import { extname, join, normalize, sep } from "node:path";
|
|
4
|
+
const TYPES = {
|
|
5
|
+
".html": "text/html; charset=utf-8",
|
|
6
|
+
".js": "text/javascript; charset=utf-8",
|
|
7
|
+
".mjs": "text/javascript; charset=utf-8",
|
|
8
|
+
".css": "text/css; charset=utf-8",
|
|
9
|
+
".json": "application/json; charset=utf-8",
|
|
10
|
+
".svg": "image/svg+xml",
|
|
11
|
+
".png": "image/png",
|
|
12
|
+
".ico": "image/x-icon",
|
|
13
|
+
".webp": "image/webp",
|
|
14
|
+
".woff2": "font/woff2",
|
|
15
|
+
".txt": "text/plain; charset=utf-8",
|
|
16
|
+
".map": "application/json; charset=utf-8",
|
|
17
|
+
};
|
|
18
|
+
function isFile(path) {
|
|
19
|
+
try {
|
|
20
|
+
return statSync(path).isFile();
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Serve `pathname` from `root`, or the SPA's index.html for client-side routes. */
|
|
27
|
+
export function serveStatic(root, pathname, res) {
|
|
28
|
+
let decoded;
|
|
29
|
+
try {
|
|
30
|
+
decoded = decodeURIComponent(pathname);
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
res.writeHead(400).end();
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
if (decoded.includes("\0")) {
|
|
37
|
+
res.writeHead(400).end();
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const candidate = normalize(join(root, decoded));
|
|
41
|
+
if (candidate !== root && !candidate.startsWith(root + sep)) {
|
|
42
|
+
res.writeHead(404).end();
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
let file = candidate;
|
|
46
|
+
if (!isFile(file)) {
|
|
47
|
+
// A path with an extension is a missing asset; anything else is a route in the SPA.
|
|
48
|
+
if (extname(decoded)) {
|
|
49
|
+
res.writeHead(404, { "content-type": "text/plain; charset=utf-8" }).end("Not found");
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
file = join(root, "index.html");
|
|
53
|
+
if (!isFile(file)) {
|
|
54
|
+
res
|
|
55
|
+
.writeHead(503, { "content-type": "text/plain; charset=utf-8" })
|
|
56
|
+
.end("The web client has not been built. Run `pnpm build`.");
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const immutable = file.startsWith(join(root, "assets") + sep);
|
|
61
|
+
res.writeHead(200, {
|
|
62
|
+
"content-type": TYPES[extname(file)] ?? "application/octet-stream",
|
|
63
|
+
"cache-control": immutable ? "public, max-age=31536000, immutable" : "no-cache",
|
|
64
|
+
});
|
|
65
|
+
createReadStream(file).pipe(res);
|
|
66
|
+
}
|
package/dist/threads.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
export class ThreadRegistry {
|
|
2
|
+
options;
|
|
3
|
+
threads = new Map();
|
|
4
|
+
now;
|
|
5
|
+
sweeper;
|
|
6
|
+
constructor(options) {
|
|
7
|
+
this.options = options;
|
|
8
|
+
this.now = options.now ?? Date.now;
|
|
9
|
+
this.sweeper = setInterval(() => this.sweep(), Math.min(30_000, options.idleTimeoutMs));
|
|
10
|
+
this.sweeper.unref();
|
|
11
|
+
}
|
|
12
|
+
get size() {
|
|
13
|
+
return this.threads.size;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Attach `socket` to the thread's process, starting one if there is none, if it runs in another
|
|
17
|
+
* workspace, or if `fresh` asks for a restart (after the project was trusted, for example).
|
|
18
|
+
*/
|
|
19
|
+
attach(thread, workspace, socket, fresh = false) {
|
|
20
|
+
const existing = this.threads.get(thread);
|
|
21
|
+
if (existing && existing.alive && existing.workspace === workspace && !fresh) {
|
|
22
|
+
existing.attach(socket);
|
|
23
|
+
return { ok: true, reused: true };
|
|
24
|
+
}
|
|
25
|
+
if (existing)
|
|
26
|
+
this.stop(thread, existing, "agent86 restarted for this thread");
|
|
27
|
+
if (this.threads.size >= this.options.maxAgents && !this.evictOne()) {
|
|
28
|
+
return {
|
|
29
|
+
ok: false,
|
|
30
|
+
reason: `${this.options.maxAgents} agents are already running, all busy or open in a tab. Close a thread, or start agent86-web with a higher --max-agents.`,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
const agent = this.options.spawn(thread, workspace);
|
|
34
|
+
this.threads.set(thread, agent);
|
|
35
|
+
void agent.exited.then(() => {
|
|
36
|
+
if (this.threads.get(thread) === agent)
|
|
37
|
+
this.threads.delete(thread);
|
|
38
|
+
});
|
|
39
|
+
agent.attach(socket);
|
|
40
|
+
return { ok: true, reused: false };
|
|
41
|
+
}
|
|
42
|
+
/** Stop idle, detached processes that have been quiet for longer than the timeout. */
|
|
43
|
+
sweep() {
|
|
44
|
+
const cutoff = this.now() - this.options.idleTimeoutMs;
|
|
45
|
+
for (const [thread, agent] of this.threads) {
|
|
46
|
+
if (!agent.attached && !agent.busy && agent.lastActivity <= cutoff) {
|
|
47
|
+
this.options.log?.(`thread ${thread}: idle, stopping agent86`);
|
|
48
|
+
this.stop(thread, agent);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
stopAll() {
|
|
53
|
+
clearInterval(this.sweeper);
|
|
54
|
+
const agents = [...this.threads.values()];
|
|
55
|
+
for (const [thread, agent] of this.threads)
|
|
56
|
+
this.stop(thread, agent);
|
|
57
|
+
return Promise.all(agents.map((agent) => agent.exited));
|
|
58
|
+
}
|
|
59
|
+
stop(thread, agent, reason) {
|
|
60
|
+
this.threads.delete(thread);
|
|
61
|
+
agent.stop(reason);
|
|
62
|
+
}
|
|
63
|
+
/** Make room by stopping the least recently used idle, detached process. */
|
|
64
|
+
evictOne() {
|
|
65
|
+
let oldest;
|
|
66
|
+
for (const entry of this.threads) {
|
|
67
|
+
const agent = entry[1];
|
|
68
|
+
if (agent.attached || agent.busy)
|
|
69
|
+
continue;
|
|
70
|
+
if (!oldest || agent.lastActivity < oldest[1].lastActivity)
|
|
71
|
+
oldest = entry;
|
|
72
|
+
}
|
|
73
|
+
if (!oldest)
|
|
74
|
+
return false;
|
|
75
|
+
this.options.log?.(`thread ${oldest[0]}: stopping agent86 to make room`);
|
|
76
|
+
this.stop(oldest[0], oldest[1]);
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
}
|
package/dist/trust.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// Project trust from the browser (docs/adr/0004-project-trust-from-the-browser.md).
|
|
2
|
+
//
|
|
3
|
+
// agent86 ignores a project file's riskier settings until the user trusts the file. Over ACP it
|
|
4
|
+
// never asks, and `--trust-project` trusts for one run without remembering. So the bridge keeps
|
|
5
|
+
// its own record of what the user trusted here, by the file's real path and the SHA-256 of its
|
|
6
|
+
// bytes, and passes `--trust-project` when it starts agent86 for a project whose file still
|
|
7
|
+
// matches. Any change to the file needs trust again. The bridge never writes agent86's own record.
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { dirname, join } from "node:path";
|
|
12
|
+
import { realpath, within } from "./workspaces.js";
|
|
13
|
+
/** The largest project file shown for review. A config file is small; anything bigger is refused. */
|
|
14
|
+
export const MAX_CONFIG_BYTES = 256 * 1024;
|
|
15
|
+
export function sha256(bytes) {
|
|
16
|
+
return createHash("sha256").update(bytes).digest("hex");
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The project's agent86 config file, if it has one (read-only, for review and hashing). A file that
|
|
20
|
+
* is not a regular file inside the workspace (a symlink to `~/.ssh/id_ed25519`, say) is refused, so
|
|
21
|
+
* the review never shows a file from elsewhere.
|
|
22
|
+
*/
|
|
23
|
+
export function readProjectConfig(workspace) {
|
|
24
|
+
let path;
|
|
25
|
+
try {
|
|
26
|
+
path = realpath(join(workspace, ".agent86", "config.toml"));
|
|
27
|
+
if (!within(path, realpath(workspace)) || !statSync(path).isFile())
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
let bytes;
|
|
34
|
+
try {
|
|
35
|
+
bytes = readFileSync(path);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return undefined;
|
|
39
|
+
}
|
|
40
|
+
if (bytes.length > MAX_CONFIG_BYTES)
|
|
41
|
+
return undefined;
|
|
42
|
+
return { path, contents: bytes.toString("utf8"), sha256: sha256(bytes) };
|
|
43
|
+
}
|
|
44
|
+
export class TrustStore {
|
|
45
|
+
file;
|
|
46
|
+
/** `dir` is the bridge's own state directory (default `~/.agent86-web`). */
|
|
47
|
+
constructor(dir = join(homedir(), ".agent86-web")) {
|
|
48
|
+
this.file = join(dir, "trusted-projects.json");
|
|
49
|
+
}
|
|
50
|
+
list() {
|
|
51
|
+
try {
|
|
52
|
+
const parsed = JSON.parse(readFileSync(this.file, "utf8"));
|
|
53
|
+
return Array.isArray(parsed.projects) ? parsed.projects : [];
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return [];
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** Whether the workspace's config file, as it is now, was trusted here. */
|
|
60
|
+
isTrusted(workspace) {
|
|
61
|
+
const config = readProjectConfig(workspace);
|
|
62
|
+
if (!config)
|
|
63
|
+
return false;
|
|
64
|
+
return this.list().some((r) => r.path === config.path && r.sha256 === config.sha256);
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Trust the workspace's config file, if it still has the hash the user reviewed. Returns false
|
|
68
|
+
* when the file is gone or has changed since (the user must review it again).
|
|
69
|
+
*/
|
|
70
|
+
trust(workspace, reviewedSha256) {
|
|
71
|
+
const config = readProjectConfig(workspace);
|
|
72
|
+
if (!config || config.sha256 !== reviewedSha256)
|
|
73
|
+
return false;
|
|
74
|
+
const records = this.list().filter((r) => r.path !== config.path);
|
|
75
|
+
records.push({ path: config.path, sha256: config.sha256, trustedAt: new Date().toISOString() });
|
|
76
|
+
this.write(records);
|
|
77
|
+
return true;
|
|
78
|
+
}
|
|
79
|
+
revoke(path) {
|
|
80
|
+
const records = this.list();
|
|
81
|
+
const kept = records.filter((r) => r.path !== path);
|
|
82
|
+
if (kept.length === records.length)
|
|
83
|
+
return false;
|
|
84
|
+
this.write(kept);
|
|
85
|
+
return true;
|
|
86
|
+
}
|
|
87
|
+
/** Written atomically, readable only by the user (docs/SECURITY.md T16, T17). */
|
|
88
|
+
write(records) {
|
|
89
|
+
mkdirSync(dirname(this.file), { recursive: true, mode: 0o700 });
|
|
90
|
+
const temporary = `${this.file}.${process.pid}.tmp`;
|
|
91
|
+
writeFileSync(temporary, `${JSON.stringify({ projects: records }, null, 2)}\n`, {
|
|
92
|
+
mode: 0o600,
|
|
93
|
+
});
|
|
94
|
+
renameSync(temporary, this.file);
|
|
95
|
+
try {
|
|
96
|
+
chmodSync(this.file, 0o600);
|
|
97
|
+
}
|
|
98
|
+
catch {
|
|
99
|
+
// Windows: permissions are by ACL; the user profile directory already restricts it.
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|