agent86-web 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.
package/dist/cli.js ADDED
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ // agent86-web: a browser interface for agent86. See docs/ARCHITECTURE.md §3.1.
3
+ import { spawn } from "node:child_process";
4
+ import { dirname, join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { parseArgs } from "node:util";
7
+ import { Agent86Error, detectAgent86 } from "./agent86.js";
8
+ import { parseDuration } from "./duration.js";
9
+ import { updateCheckDisabled } from "./updates.js";
10
+ import { BRIDGE_VERSION, startBridge } from "./server.js";
11
+ import { realpath } from "./workspaces.js";
12
+ const HELP = `agent86-web ${BRIDGE_VERSION}: a browser interface for agent86
13
+
14
+ Usage: agent86-web [options]
15
+
16
+ Options:
17
+ --root <dir> A directory threads may run in (repeatable; default: the current directory)
18
+ --port <n> Port to listen on (default: any free port)
19
+ --host <addr> Loopback address to bind: 127.0.0.1 (default), ::1, or localhost
20
+ --agent86 <path> The agent86 command (default: agent86 on PATH)
21
+ --agent-arg=<arg> An argument for agent86, placed before \`acp\` (repeatable),
22
+ e.g. --agent-arg=--model --agent-arg=openrouter:<model>
23
+ --no-open Print the URL instead of opening the browser
24
+ --max-agents <n> The most agent86 processes running at once (default: 8)
25
+ --idle-timeout <d> Stop an agent86 with no tab and no turn after this long: 90s, 15m, 1h
26
+ (default: 15m)
27
+ --no-update-check Don't check npm for newer agent86 or agent86-web releases
28
+ (also AGENT86_WEB_NO_UPDATE_CHECK=1)
29
+ --dev-origin <url> Also allow this origin (the Vite dev server, for development)
30
+ --static <dir> Serve the web client from this directory
31
+ -h, --help Show this help
32
+ -v, --version Show the version
33
+ `;
34
+ function openBrowser(url) {
35
+ const [command, args] = process.platform === "darwin"
36
+ ? ["open", [url]]
37
+ : process.platform === "win32"
38
+ ? ["cmd", ["/c", "start", '""', url]]
39
+ : ["xdg-open", [url]];
40
+ try {
41
+ const child = spawn(command, args, { stdio: "ignore", detached: true, windowsHide: true });
42
+ child.on("error", () => undefined);
43
+ child.unref();
44
+ }
45
+ catch {
46
+ // Opening the browser is a convenience; the URL is printed either way.
47
+ }
48
+ }
49
+ async function main() {
50
+ let parsed;
51
+ try {
52
+ parsed = parseArgs({
53
+ options: {
54
+ root: { type: "string", multiple: true },
55
+ port: { type: "string" },
56
+ host: { type: "string", default: "127.0.0.1" },
57
+ agent86: { type: "string", default: "agent86" },
58
+ "agent-arg": { type: "string", multiple: true },
59
+ "no-open": { type: "boolean", default: false },
60
+ "max-agents": { type: "string" },
61
+ "idle-timeout": { type: "string" },
62
+ "no-update-check": { type: "boolean", default: false },
63
+ "dev-origin": { type: "string" },
64
+ static: { type: "string" },
65
+ help: { type: "boolean", short: "h", default: false },
66
+ version: { type: "boolean", short: "v", default: false },
67
+ },
68
+ strict: true,
69
+ allowPositionals: false,
70
+ });
71
+ }
72
+ catch (error) {
73
+ process.stderr.write(`agent86-web: ${error.message}\n\n${HELP}`);
74
+ return 2;
75
+ }
76
+ const { values } = parsed;
77
+ if (values.help) {
78
+ process.stdout.write(HELP);
79
+ return 0;
80
+ }
81
+ if (values.version) {
82
+ process.stdout.write(`agent86-web ${BRIDGE_VERSION}\n`);
83
+ return 0;
84
+ }
85
+ const port = values.port === undefined ? 0 : Number(values.port);
86
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
87
+ process.stderr.write(`agent86-web: --port must be a number from 0 to 65535\n`);
88
+ return 2;
89
+ }
90
+ const maxAgents = values["max-agents"] === undefined ? undefined : Number(values["max-agents"]);
91
+ if (maxAgents !== undefined && (!Number.isInteger(maxAgents) || maxAgents < 1)) {
92
+ process.stderr.write("agent86-web: --max-agents must be a whole number of at least 1\n");
93
+ return 2;
94
+ }
95
+ const idleTimeoutMs = values["idle-timeout"] === undefined ? undefined : parseDuration(values["idle-timeout"]);
96
+ if (idleTimeoutMs === null) {
97
+ process.stderr.write("agent86-web: --idle-timeout must look like 90s, 15m, or 1h\n");
98
+ return 2;
99
+ }
100
+ const roots = [];
101
+ for (const root of values.root ?? [process.cwd()]) {
102
+ try {
103
+ roots.push(realpath(root));
104
+ }
105
+ catch {
106
+ process.stderr.write(`agent86-web: --root ${root} does not exist\n`);
107
+ return 2;
108
+ }
109
+ }
110
+ let version;
111
+ try {
112
+ version = await detectAgent86(values.agent86);
113
+ }
114
+ catch (error) {
115
+ if (error instanceof Agent86Error) {
116
+ process.stderr.write(`agent86-web: ${error.message}\n`);
117
+ return 1;
118
+ }
119
+ throw error;
120
+ }
121
+ const here = dirname(fileURLToPath(import.meta.url));
122
+ const publicDir = values.static ?? join(here, "public");
123
+ const bridge = await startBridge({
124
+ roots,
125
+ host: values.host,
126
+ port,
127
+ agent86: { command: values.agent86, version, args: values["agent-arg"] ?? [] },
128
+ publicDir,
129
+ devOrigin: values["dev-origin"],
130
+ maxAgents,
131
+ idleTimeoutMs,
132
+ updateCheck: !values["no-update-check"] && !updateCheckDisabled() && !values["dev-origin"],
133
+ log: (line) => process.stderr.write(`${line}\n`),
134
+ });
135
+ process.stdout.write(`agent86-web ${BRIDGE_VERSION} (agent86 ${version})\n` +
136
+ `Workspaces: ${roots.join(", ")}\n` +
137
+ `Open: ${bridge.url}\n` +
138
+ `The link works once and expires in 5 minutes. Press Ctrl+C to stop.\n`);
139
+ if (!values["no-open"])
140
+ openBrowser(bridge.url);
141
+ await new Promise((resolve) => {
142
+ const stop = () => resolve();
143
+ process.once("SIGINT", stop);
144
+ process.once("SIGTERM", stop);
145
+ });
146
+ await bridge.close();
147
+ return 0;
148
+ }
149
+ main().then((code) => process.exit(code), (error) => {
150
+ process.stderr.write(`agent86-web: ${error instanceof Error ? error.message : String(error)}\n`);
151
+ process.exit(1);
152
+ });
@@ -0,0 +1,9 @@
1
+ /** `90s`, `15m`, `1h` (or a bare number of seconds) in milliseconds; null when unreadable. */
2
+ export function parseDuration(text) {
3
+ const match = /^(\d+(?:\.\d+)?)\s*(s|m|h)?$/.exec(text.trim());
4
+ if (!match)
5
+ return null;
6
+ const unit = { s: 1_000, m: 60_000, h: 3_600_000 }[(match[2] ?? "s")];
7
+ const ms = Number(match[1]) * unit;
8
+ return ms > 0 ? ms : null;
9
+ }
package/dist/files.js ADDED
@@ -0,0 +1,69 @@
1
+ // Directory and file names for the workspace picker and @ mentions. Names only: the bridge never
2
+ // reads a file's contents for the browser (docs/SECURITY.md T7).
3
+ import { readdirSync } from "node:fs";
4
+ import { join, relative, sep } from "node:path";
5
+ /** Directories never listed or walked. */
6
+ const SKIPPED = new Set(["node_modules", "target", "__pycache__"]);
7
+ const hidden = (name) => name.startsWith(".") || SKIPPED.has(name);
8
+ function entries(dir) {
9
+ try {
10
+ return readdirSync(dir, { withFileTypes: true });
11
+ }
12
+ catch {
13
+ return [];
14
+ }
15
+ }
16
+ /** The subdirectories of `dir`, by name, without hidden ones. */
17
+ export function listDirectories(dir) {
18
+ return entries(dir)
19
+ .filter((entry) => entry.isDirectory() && !hidden(entry.name))
20
+ .map((entry) => ({ name: entry.name, path: join(dir, entry.name) }))
21
+ .sort((a, b) => a.name.localeCompare(b.name));
22
+ }
23
+ const MAX_WALK = 5000;
24
+ const MAX_DEPTH = 8;
25
+ /** Workspace-relative paths of files under `root` (breadth first, bounded), with `/` separators. */
26
+ export function walkFiles(root) {
27
+ const files = [];
28
+ let level = [root];
29
+ for (let depth = 0; depth < MAX_DEPTH && level.length > 0 && files.length < MAX_WALK; depth++) {
30
+ const next = [];
31
+ for (const dir of level) {
32
+ for (const entry of entries(dir)) {
33
+ if (hidden(entry.name))
34
+ continue;
35
+ const path = join(dir, entry.name);
36
+ if (entry.isDirectory())
37
+ next.push(path);
38
+ else if (entry.isFile())
39
+ files.push(relative(root, path).split(sep).join("/"));
40
+ if (files.length >= MAX_WALK)
41
+ break;
42
+ }
43
+ }
44
+ level = next;
45
+ }
46
+ return files;
47
+ }
48
+ /** Files matching `query`, best first: a file name that starts with it, then one containing it. */
49
+ export function matchFiles(files, query, limit = 50) {
50
+ const q = query.toLowerCase();
51
+ const scored = [];
52
+ for (const file of files) {
53
+ const lower = file.toLowerCase();
54
+ const base = lower.slice(lower.lastIndexOf("/") + 1);
55
+ const score = !q
56
+ ? 2
57
+ : base.startsWith(q)
58
+ ? 0
59
+ : base.includes(q)
60
+ ? 1
61
+ : lower.includes(q)
62
+ ? 2
63
+ : -1;
64
+ if (score >= 0)
65
+ scored.push([score, file]);
66
+ }
67
+ scored.sort((a, b) => a[0] - b[0] || a[1].length - b[1].length || a[1].localeCompare(b[1]));
68
+ return scored.slice(0, limit).map(([, file]) => file);
69
+ }
package/dist/policy.js ADDED
@@ -0,0 +1,99 @@
1
+ // The policy filter: the bridge's checks on messages from the browser to agent86.
2
+ // See docs/ARCHITECTURE.md §3.4 and docs/SECURITY.md (T7, T8, T9).
3
+ //
4
+ // The filter only ever narrows what the browser can do. It never rewrites messages from agent86.
5
+ /** Methods the browser may call on the agent. Anything else is refused. */
6
+ export const ALLOWED_CLIENT_METHODS = new Set([
7
+ "initialize",
8
+ "session/new",
9
+ "session/load",
10
+ "session/list",
11
+ "session/prompt",
12
+ "session/cancel",
13
+ "session/set_config_option",
14
+ "session/set_mode",
15
+ "$/cancel_request",
16
+ ]);
17
+ /** The capabilities the browser is allowed to claim: none that hand it files or terminals. */
18
+ export const FORCED_CLIENT_CAPABILITIES = {
19
+ fs: { readTextFile: false, writeTextFile: false },
20
+ terminal: false,
21
+ };
22
+ const INVALID_REQUEST = -32600;
23
+ const METHOD_NOT_FOUND = -32601;
24
+ const INVALID_PARAMS = -32602;
25
+ function isObject(value) {
26
+ return typeof value === "object" && value !== null && !Array.isArray(value);
27
+ }
28
+ function reject(id, code, reason) {
29
+ const hasId = typeof id === "string" || typeof id === "number";
30
+ return {
31
+ action: "reject",
32
+ reason,
33
+ // A notification gets no answer, as JSON-RPC requires.
34
+ error: hasId
35
+ ? { jsonrpc: "2.0", id, error: { code, message: `agent86-web bridge: ${reason}` } }
36
+ : undefined,
37
+ };
38
+ }
39
+ function cwdAllowed(cwd, ctx) {
40
+ if (typeof cwd !== "string" || cwd.length === 0)
41
+ return false;
42
+ try {
43
+ return ctx.realpath(cwd) === ctx.workspace;
44
+ }
45
+ catch {
46
+ return false;
47
+ }
48
+ }
49
+ /** Decide what to do with one frame the browser sent. */
50
+ export function filterClientMessage(raw, ctx) {
51
+ let message;
52
+ try {
53
+ message = JSON.parse(raw);
54
+ }
55
+ catch {
56
+ return reject(null, INVALID_REQUEST, "the message is not JSON");
57
+ }
58
+ if (!isObject(message) || message.jsonrpc !== "2.0") {
59
+ return reject(null, INVALID_REQUEST, "the message is not a JSON-RPC 2.0 object");
60
+ }
61
+ const { id, method } = message;
62
+ // A response to a request agent86 made (a permission answer, for example): pass it on.
63
+ if (method === undefined) {
64
+ if (("result" in message || "error" in message) && id !== undefined) {
65
+ return { action: "forward", message };
66
+ }
67
+ return reject(null, INVALID_REQUEST, "the message is neither a request nor a response");
68
+ }
69
+ if (typeof method !== "string" || !ALLOWED_CLIENT_METHODS.has(method)) {
70
+ return reject(id, METHOD_NOT_FOUND, `the method ${JSON.stringify(method)} is not allowed`);
71
+ }
72
+ const params = message.params;
73
+ if (params !== undefined && !isObject(params)) {
74
+ return reject(id, INVALID_PARAMS, "params must be an object");
75
+ }
76
+ switch (method) {
77
+ case "initialize": {
78
+ const next = { ...params, clientCapabilities: FORCED_CLIENT_CAPABILITIES };
79
+ return { action: "forward", message: { ...message, params: next } };
80
+ }
81
+ case "session/new":
82
+ case "session/load": {
83
+ if (!cwdAllowed(params?.cwd, ctx)) {
84
+ return reject(id, INVALID_PARAMS, "cwd must be the workspace this thread was opened in");
85
+ }
86
+ // A browser-supplied MCP server would be a program run as the user (T8).
87
+ const next = { ...params, cwd: ctx.workspace, mcpServers: [] };
88
+ return { action: "forward", message: { ...message, params: next } };
89
+ }
90
+ case "session/list": {
91
+ if (params?.cwd !== undefined && !cwdAllowed(params.cwd, ctx)) {
92
+ return reject(id, INVALID_PARAMS, "cwd must be the workspace this thread was opened in");
93
+ }
94
+ return { action: "forward", message };
95
+ }
96
+ default:
97
+ return { action: "forward", message };
98
+ }
99
+ }
Binary file