arena-bridge 0.8.12 → 0.9.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 +26 -0
- package/package.json +1 -1
- package/src/catalog.mjs +579 -0
- package/src/cli/browser.mjs +93 -0
- package/src/cli/index.mjs +3 -0
- package/src/cli.mjs +6 -98
- package/src/direct.mjs +11 -23
- package/src/engine.mjs +5 -655
- package/src/engine_helpers.mjs +55 -0
- package/src/gate.mjs +19 -0
- package/src/version.mjs +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,32 @@ All notable changes to this project are documented here.
|
|
|
4
4
|
The format follows [Keep a Changelog](https://keepachangelog.com/) and the project uses
|
|
5
5
|
[Semantic Versioning](https://semver.org/).
|
|
6
6
|
|
|
7
|
+
## 0.9.0
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
- `src/catalog.mjs` is now the single source for `toolCatalog()` (core tools: `bash`, `read_file`, `write_file`, `edit_file`, `list_dir`, `search_files`, `delete_path`, `file_get`, `file_put`, `audit_log`, `audit_artifact`, `sysinfo`, process tools) — `src/engine.mjs` imports from it instead of defining it. Browser/desktop/telegram tools joined via `engine.catalog()` (`browser.mjs`/`mac.mjs`/`telegram.mjs`) as before, now documented in `docs/reference/tools.md` as one set.
|
|
11
|
+
- `src/engine_helpers.mjs` (`clip`, `runShell`) extracted from `engine.mjs` so `catalog.mjs` and `engine.mjs` share them without a circular dependency.
|
|
12
|
+
- `src/gate.mjs` `authorize(tool,args,cfg)` is now used by `src/direct.mjs` `PUT/DELETE /files` (trust → `requireApproval` → `requestApproval` → `approval_denied` audit, `202` for pending vs `403` for denied), single source with `Engine.call()` pipeline (wave 0 S3 + wave 1 R1 fix).
|
|
13
|
+
- `src/cli/browser.mjs` extracted from `src/cli.mjs` (`browser list/login/clean/close`) — plain Chrome launch for `browser login` (no `--remote-debugging-port`, no automation flags) so Google login works, `profile` lifecycle (`profile_busy` check via `profilePids()`), `chrome_activate` without OS focus; `src/cli.mjs` now delegates to it (1139 lines vs 1231, `browser login` string kept for `browser.test.mjs` audit).
|
|
14
|
+
|
|
15
|
+
### Changed
|
|
16
|
+
- **Breaking:** `publicUrl` is runtime state (`~/.arena-bridge/state.json`, atomic `tmp+rename`) not user intent — `src/config.mjs` `loadConfig()` merges `state.publicUrl` if `config.json` lacks it, `saveConfig()` moves `publicUrl` to `state.json` (B7/B12 fix); `src/state.mjs` `loadState`/`saveState`/`STATE_PATH` is the single writer.
|
|
17
|
+
- `src/browser.mjs` DevTools keepalive: `BrowserManager._wireCdp` + `_reconnect` (60 attempts, 1s interval) keeps session/tabs/observations after an idle socket drop; `profile` busy guard, `chrome_profiles` with `running` flag, `chrome_activate` without touching cursor/focus — verified in `test/browser.test.mjs` (fake-chrome, socket destroy → reconnect).
|
|
18
|
+
- `AGENTS.md` module map updated: `catalog.mjs`/`gate.mjs`/`engine_helpers.mjs`/`state.mjs`/`cli/browser.mjs` documented.
|
|
19
|
+
|
|
20
|
+
### Fixed
|
|
21
|
+
- `sysinfo` `os is not defined` after catalog extraction — added `import os from 'node:os'` to `src/catalog.mjs` (MCP `tools/call` `sysinfo` now returns 2025-06-18 `protocolVersion` + `hostname`).
|
|
22
|
+
- `audit_log` `tailAudit is not defined` after catalog extraction — added `import { audit, saveArtifact, tailAudit, readArtifact, auditDir } from './audit.mjs'` to `src/catalog.mjs` (mac `audit_artifact` with `bytes` now listed).
|
|
23
|
+
- `test` suite now single-source: `npm test` `24/39/18/15` (smoke/browser/mac/service + `test_security.mjs` 7 + `test_security.py` 6) all green.
|
|
24
|
+
|
|
25
|
+
## 0.8.13
|
|
26
|
+
|
|
27
|
+
### Added
|
|
28
|
+
- `src/catalog.mjs` single source for `toolCatalog()` (re-export from `engine.mjs` as phase 1), `src/gate.mjs` unified `authorize(tool,args,cfg)` (trust+gate+audit) for `POST /call` and `PUT/DELETE /files`, `src/cli/` modularity scaffold (wave 3 step 1). `docs/reference/security.md` documents `state.json` runtime split.
|
|
29
|
+
|
|
30
|
+
### Changed
|
|
31
|
+
- `state.json` migration: `publicUrl` is runtime state (not user intent) — `config.mjs` `loadConfig()` merges `state.publicUrl` if `config.json` lacks it, `saveConfig()` moves `publicUrl` to `state.json` via `tmp+rename` (B7/B12 fix). `package.json` is still single source for `VERSION`.
|
|
32
|
+
|
|
7
33
|
## 0.8.12
|
|
8
34
|
|
|
9
35
|
### Added
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "arena-bridge",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Give a cloud AI agent (Arena.ai Agent Mode, Claude, Cursor, ...) controlled access to your own machine over HTTP/MCP: files, shell, Chrome and the macOS desktop, with an approval gate, trust windows and an audit log.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
package/src/catalog.mjs
ADDED
|
@@ -0,0 +1,579 @@
|
|
|
1
|
+
import fsp from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { checkPath, resolveTarget } from './policy.mjs';
|
|
6
|
+
import { audit, saveArtifact, tailAudit, readArtifact, auditDir } from './audit.mjs';
|
|
7
|
+
import { clip, runShell } from './engine_helpers.mjs';
|
|
8
|
+
|
|
9
|
+
const S = (o) => ({ type: 'object', properties: o, required: [], additionalProperties: false });
|
|
10
|
+
|
|
11
|
+
export function toolCatalog() {
|
|
12
|
+
return [
|
|
13
|
+
{
|
|
14
|
+
name: 'bash',
|
|
15
|
+
description:
|
|
16
|
+
'Run a shell command on the remote machine. Returns stdout, stderr and the exit code. ' +
|
|
17
|
+
'Use absolute paths; the working directory defaults to the authorized root. This is a side-effecting operation and may require human approval.',
|
|
18
|
+
approval: true,
|
|
19
|
+
schema: S({
|
|
20
|
+
command: { type: 'string', description: 'Shell command to execute' },
|
|
21
|
+
cwd: { type: 'string', description: 'Working directory (must be inside the authorized roots)' },
|
|
22
|
+
timeout_sec: { type: 'number', description: 'Timeout in seconds (default 120, max 1800)' },
|
|
23
|
+
env: { type: 'object', description: 'Extra environment variables' },
|
|
24
|
+
}),
|
|
25
|
+
required: ['command'],
|
|
26
|
+
handler: async (args, ctx) => {
|
|
27
|
+
const command = String(args.command ?? '');
|
|
28
|
+
if (!command.trim()) return { ok: false, error: 'command is required' };
|
|
29
|
+
if (!ctx.cfg.allowShell) return { ok: false, error: 'shell execution is disabled in the config' };
|
|
30
|
+
const base = args.cwd ? resolveTarget(args.cwd, ctx.base) : ctx.base;
|
|
31
|
+
const chk = checkPath(base, ctx.cfg, ctx.base);
|
|
32
|
+
if (!chk.ok) return { ok: false, error: chk.error, reason: chk.reason };
|
|
33
|
+
const timeout = Math.min(
|
|
34
|
+
Number(args.timeout_sec || ctx.cfg.commandTimeoutSec || 120),
|
|
35
|
+
1800,
|
|
36
|
+
);
|
|
37
|
+
const res = await runShell(command, {
|
|
38
|
+
cwd: chk.abs,
|
|
39
|
+
timeout,
|
|
40
|
+
env: args.env || {},
|
|
41
|
+
cap: ctx.cfg.maxOutputBytes,
|
|
42
|
+
});
|
|
43
|
+
return { ok: true, command, cwd: chk.abs, ...res };
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
{
|
|
47
|
+
name: 'read_file',
|
|
48
|
+
description: 'Read a UTF-8 text file from the remote machine.',
|
|
49
|
+
approval: false,
|
|
50
|
+
schema: S({
|
|
51
|
+
path: { type: 'string', description: 'Absolute or root-relative file path' },
|
|
52
|
+
max_bytes: { type: 'number', description: 'Maximum number of bytes to return' },
|
|
53
|
+
}),
|
|
54
|
+
required: ['path'],
|
|
55
|
+
handler: async (args, ctx) => {
|
|
56
|
+
const chk = checkPath(args.path, ctx.cfg, ctx.base);
|
|
57
|
+
if (!chk.ok) return { ok: false, error: chk.error, reason: chk.reason };
|
|
58
|
+
const stat = await fsp.stat(chk.abs).catch(() => null);
|
|
59
|
+
if (!stat) return { ok: false, error: `not found: ${chk.abs}` };
|
|
60
|
+
if (stat.isDirectory()) return { ok: false, error: `is a directory: ${chk.abs}` };
|
|
61
|
+
const max = Math.min(
|
|
62
|
+
Number(args.max_bytes || ctx.cfg.maxOutputBytes),
|
|
63
|
+
ctx.cfg.maxOutputBytes,
|
|
64
|
+
);
|
|
65
|
+
const buf = await fsp.readFile(chk.abs);
|
|
66
|
+
const c = clip(buf, max);
|
|
67
|
+
return {
|
|
68
|
+
ok: true,
|
|
69
|
+
path: chk.abs,
|
|
70
|
+
size: stat.size,
|
|
71
|
+
truncated: c.truncated,
|
|
72
|
+
content: c.data.toString('utf8'),
|
|
73
|
+
};
|
|
74
|
+
},
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
name: 'write_file',
|
|
78
|
+
description: 'Create or overwrite a text file. May require human approval.',
|
|
79
|
+
approval: true,
|
|
80
|
+
schema: S({
|
|
81
|
+
path: { type: 'string' },
|
|
82
|
+
content: { type: 'string' },
|
|
83
|
+
append: { type: 'boolean' },
|
|
84
|
+
}),
|
|
85
|
+
required: ['path', 'content'],
|
|
86
|
+
handler: async (args, ctx) => {
|
|
87
|
+
const chk = checkPath(args.path, ctx.cfg, ctx.base, { write: true });
|
|
88
|
+
if (!chk.ok) return { ok: false, error: chk.error, reason: chk.reason };
|
|
89
|
+
const content = String(args.content ?? '');
|
|
90
|
+
if (Buffer.byteLength(content) > ctx.cfg.maxUploadBytes) {
|
|
91
|
+
return { ok: false, error: 'content exceeds maxUploadBytes' };
|
|
92
|
+
}
|
|
93
|
+
await fsp.mkdir(path.dirname(chk.abs), { recursive: true });
|
|
94
|
+
if (args.append) await fsp.appendFile(chk.abs, content);
|
|
95
|
+
else {
|
|
96
|
+
const dir = path.dirname(chk.abs);
|
|
97
|
+
const tmp = path.join(dir, `.tmp-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
|
98
|
+
await fsp.writeFile(tmp, content);
|
|
99
|
+
await fsp.rename(tmp, chk.abs);
|
|
100
|
+
}
|
|
101
|
+
return { ok: true, path: chk.abs, bytes: Buffer.byteLength(content), appended: !!args.append };
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
{
|
|
105
|
+
name: 'edit_file',
|
|
106
|
+
description: 'Replace an exact string inside a file (old_text must appear exactly once unless replace_all is true).',
|
|
107
|
+
approval: true,
|
|
108
|
+
schema: S({
|
|
109
|
+
path: { type: 'string' },
|
|
110
|
+
old_text: { type: 'string' },
|
|
111
|
+
new_text: { type: 'string' },
|
|
112
|
+
replace_all: { type: 'boolean' },
|
|
113
|
+
}),
|
|
114
|
+
required: ['path', 'old_text', 'new_text'],
|
|
115
|
+
handler: async (args, ctx) => {
|
|
116
|
+
const chk = checkPath(args.path, ctx.cfg, ctx.base, { write: true });
|
|
117
|
+
if (!chk.ok) return { ok: false, error: chk.error, reason: chk.reason };
|
|
118
|
+
const oldText = String(args.old_text ?? '');
|
|
119
|
+
if (!oldText) return { ok: false, error: 'old_text is required' };
|
|
120
|
+
const buf = await fsp.readFile(chk.abs, 'utf8').catch(() => null);
|
|
121
|
+
if (buf === null) return { ok: false, error: `not found: ${chk.abs}` };
|
|
122
|
+
const count = buf.split(oldText).length - 1;
|
|
123
|
+
if (count === 0) return { ok: false, error: 'old_text not found in file' };
|
|
124
|
+
if (count > 1 && !args.replace_all) {
|
|
125
|
+
return { ok: false, error: `old_text appears ${count} times, pass replace_all=true` };
|
|
126
|
+
}
|
|
127
|
+
const next = args.replace_all
|
|
128
|
+
? buf.split(oldText).join(String(args.new_text ?? ''))
|
|
129
|
+
: (() => { const idx = buf.indexOf(oldText); return buf.slice(0, idx) + String(args.new_text ?? '') + buf.slice(idx + oldText.length); })();
|
|
130
|
+
{
|
|
131
|
+
const dir = path.dirname(chk.abs);
|
|
132
|
+
const tmp = path.join(dir, `.tmp-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
|
133
|
+
await fsp.writeFile(tmp, next);
|
|
134
|
+
await fsp.rename(tmp, chk.abs);
|
|
135
|
+
}
|
|
136
|
+
return { ok: true, path: chk.abs, replacements: args.replace_all ? count : 1 };
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
name: 'list_dir',
|
|
141
|
+
description: 'List the contents of a directory on the remote machine.',
|
|
142
|
+
approval: false,
|
|
143
|
+
schema: S({
|
|
144
|
+
path: { type: 'string', description: 'absolute path, "~" or "~/dir" allowed' },
|
|
145
|
+
recursive: { type: 'boolean', description: 'walk into subdirectories (default false)' },
|
|
146
|
+
depth: { type: 'number', description: 'how deep to walk when recursive is set (default 3)' },
|
|
147
|
+
include_hidden: { type: 'boolean', description: 'include dotfiles (default true)' },
|
|
148
|
+
max_entries: { type: 'number' },
|
|
149
|
+
}),
|
|
150
|
+
required: ['path'],
|
|
151
|
+
handler: async (args, ctx) => {
|
|
152
|
+
const chk = checkPath(args.path, ctx.cfg, ctx.base);
|
|
153
|
+
if (!chk.ok) return { ok: false, error: chk.error, reason: chk.reason };
|
|
154
|
+
const stat = await fsp.stat(chk.abs).catch(() => null);
|
|
155
|
+
if (!stat) return { ok: false, error: `not found: ${chk.abs}` };
|
|
156
|
+
if (!stat.isDirectory()) return { ok: false, error: `not a directory: ${chk.abs}` };
|
|
157
|
+
const max = Math.min(Number(args.max_entries || 500), 20000);
|
|
158
|
+
const depth = Math.max(0, Math.min(Number(args.depth ?? (args.recursive ? 3 : 0)), 8));
|
|
159
|
+
const showHidden = args.include_hidden !== false;
|
|
160
|
+
const entries = [];
|
|
161
|
+
const errors = [];
|
|
162
|
+
const walk = async (dir, level) => {
|
|
163
|
+
if (entries.length >= max) return;
|
|
164
|
+
let items;
|
|
165
|
+
try {
|
|
166
|
+
items = await fsp.readdir(dir, { withFileTypes: true });
|
|
167
|
+
} catch (e) {
|
|
168
|
+
errors.push({ path: dir, error: e.code || e.message });
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
for (const it of items) {
|
|
172
|
+
if (entries.length >= max) return;
|
|
173
|
+
if (!showHidden && it.name.startsWith('.')) continue;
|
|
174
|
+
const full = path.join(dir, it.name);
|
|
175
|
+
// enforce protected/roots policy on every element
|
|
176
|
+
try {
|
|
177
|
+
const chkEl = checkPath(full, ctx.cfg, ctx.base);
|
|
178
|
+
if (!chkEl.ok) continue;
|
|
179
|
+
} catch { continue; }
|
|
180
|
+
let size = null;
|
|
181
|
+
let mtime = null;
|
|
182
|
+
let type = 'file';
|
|
183
|
+
try {
|
|
184
|
+
// lstat never follows symlinks: a dead link cannot block the listing
|
|
185
|
+
const st = await fsp.lstat(full);
|
|
186
|
+
size = st.size;
|
|
187
|
+
mtime = st.mtimeMs;
|
|
188
|
+
type = st.isDirectory() ? 'dir' : st.isSymbolicLink() ? 'symlink' : 'file';
|
|
189
|
+
} catch (e) {
|
|
190
|
+
errors.push({ path: full, error: e.code || e.message });
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
entries.push({ path: full, name: it.name, type, size, mtime, depth: level });
|
|
194
|
+
if (level < depth && type === 'dir') await walk(full, level + 1);
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
await walk(chk.abs, 0);
|
|
198
|
+
return {
|
|
199
|
+
ok: true,
|
|
200
|
+
path: chk.abs,
|
|
201
|
+
count: entries.length,
|
|
202
|
+
depth,
|
|
203
|
+
truncated: entries.length >= max,
|
|
204
|
+
errors: errors.length ? errors : undefined,
|
|
205
|
+
entries,
|
|
206
|
+
};
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
{
|
|
210
|
+
name: 'search_files',
|
|
211
|
+
description: 'Search for a text pattern in files under a directory (read-only).',
|
|
212
|
+
approval: false,
|
|
213
|
+
schema: S({
|
|
214
|
+
path: { type: 'string' },
|
|
215
|
+
query: { type: 'string' },
|
|
216
|
+
regex: { type: 'boolean' },
|
|
217
|
+
max_results: { type: 'number' },
|
|
218
|
+
max_file_bytes: { type: 'number' },
|
|
219
|
+
}),
|
|
220
|
+
required: ['path', 'query'],
|
|
221
|
+
handler: async (args, ctx) => {
|
|
222
|
+
const chk = checkPath(args.path, ctx.cfg, ctx.base);
|
|
223
|
+
if (!chk.ok) return { ok: false, error: chk.error, reason: chk.reason };
|
|
224
|
+
const query = String(args.query ?? '');
|
|
225
|
+
if (!query) return { ok: false, error: 'query is required' };
|
|
226
|
+
const maxResults = Math.min(Number(args.max_results || 100), 5000);
|
|
227
|
+
const maxFile = Math.min(Number(args.max_file_bytes || 2 * 1024 * 1024), ctx.cfg.maxOutputBytes);
|
|
228
|
+
let matcher;
|
|
229
|
+
if (args.regex) {
|
|
230
|
+
try {
|
|
231
|
+
matcher = new RegExp(query);
|
|
232
|
+
} catch (e) {
|
|
233
|
+
return { ok: false, error: `invalid regex: ${e.message}` };
|
|
234
|
+
}
|
|
235
|
+
} else {
|
|
236
|
+
const needle = query.toLowerCase();
|
|
237
|
+
matcher = { test: (s) => s.toLowerCase().includes(needle) };
|
|
238
|
+
}
|
|
239
|
+
const results = [];
|
|
240
|
+
const skipDirs = new Set(['node_modules', '.git', '.venv', 'venv', '__pycache__', 'dist', 'build', '.next']);
|
|
241
|
+
const walk = async (dir) => {
|
|
242
|
+
if (results.length >= maxResults) return;
|
|
243
|
+
const items = await fsp.readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
244
|
+
for (const it of items) {
|
|
245
|
+
if (results.length >= maxResults) return;
|
|
246
|
+
const full = path.join(dir, it.name);
|
|
247
|
+
if (it.isDirectory()) {
|
|
248
|
+
if (!skipDirs.has(it.name)) await walk(full);
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
if (!it.isFile()) continue;
|
|
252
|
+
// enforce policy
|
|
253
|
+
try {
|
|
254
|
+
const chkEl = checkPath(full, ctx.cfg, ctx.base);
|
|
255
|
+
if (!chkEl.ok) continue;
|
|
256
|
+
} catch { continue; }
|
|
257
|
+
const st = await fsp.stat(full).catch(() => null);
|
|
258
|
+
if (!st || st.size > maxFile) continue;
|
|
259
|
+
const text = await fsp.readFile(full, 'utf8').catch(() => null);
|
|
260
|
+
if (text === null) continue;
|
|
261
|
+
const lines = text.split('\n');
|
|
262
|
+
for (let i = 0; i < lines.length; i++) {
|
|
263
|
+
if (matcher.test(lines[i])) {
|
|
264
|
+
results.push({ path: full, line: i + 1, text: lines[i].slice(0, 500) });
|
|
265
|
+
if (results.length >= maxResults) return;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
await walk(chk.abs);
|
|
271
|
+
return { ok: true, path: chk.abs, count: results.length, results };
|
|
272
|
+
},
|
|
273
|
+
},
|
|
274
|
+
{
|
|
275
|
+
name: 'delete_path',
|
|
276
|
+
description: 'Delete a file or directory (recursively) on the remote machine. Requires approval.',
|
|
277
|
+
approval: true,
|
|
278
|
+
schema: S({ path: { type: 'string' } }),
|
|
279
|
+
required: ['path'],
|
|
280
|
+
handler: async (args, ctx) => {
|
|
281
|
+
const chk = checkPath(args.path, ctx.cfg, ctx.base, { write: true });
|
|
282
|
+
if (!chk.ok) return { ok: false, error: chk.error, reason: chk.reason };
|
|
283
|
+
if (isInside(chk.abs, ctx.base) && chk.abs === ctx.base) {
|
|
284
|
+
return { ok: false, error: 'refusing to delete the working root' };
|
|
285
|
+
}
|
|
286
|
+
await fsp.rm(chk.abs, { recursive: true, force: true });
|
|
287
|
+
return { ok: true, path: chk.abs, deleted: true };
|
|
288
|
+
},
|
|
289
|
+
},
|
|
290
|
+
{
|
|
291
|
+
name: 'file_get',
|
|
292
|
+
description: 'Download a binary file as base64 (use for images, archives, binaries).',
|
|
293
|
+
approval: false,
|
|
294
|
+
schema: S({ path: { type: 'string' } }),
|
|
295
|
+
required: ['path'],
|
|
296
|
+
handler: async (args, ctx) => {
|
|
297
|
+
const chk = checkPath(args.path, ctx.cfg, ctx.base);
|
|
298
|
+
if (!chk.ok) return { ok: false, error: chk.error, reason: chk.reason };
|
|
299
|
+
const st = await fsp.stat(chk.abs).catch(() => null);
|
|
300
|
+
if (!st || !st.isFile()) return { ok: false, error: `not a file: ${chk.abs}` };
|
|
301
|
+
if (st.size > ctx.cfg.maxUploadBytes) return { ok: false, error: 'file too large' };
|
|
302
|
+
const buf = await fsp.readFile(chk.abs);
|
|
303
|
+
return { ok: true, path: chk.abs, size: st.size, data_base64: buf.toString('base64') };
|
|
304
|
+
},
|
|
305
|
+
},
|
|
306
|
+
{
|
|
307
|
+
name: 'file_put',
|
|
308
|
+
description: 'Upload a binary file (base64 payload). Requires approval.',
|
|
309
|
+
approval: true,
|
|
310
|
+
schema: S({ path: { type: 'string' }, data_base64: { type: 'string' } }),
|
|
311
|
+
required: ['path', 'data_base64'],
|
|
312
|
+
handler: async (args, ctx) => {
|
|
313
|
+
const chk = checkPath(args.path, ctx.cfg, ctx.base, { write: true });
|
|
314
|
+
if (!chk.ok) return { ok: false, error: chk.error, reason: chk.reason };
|
|
315
|
+
const data = Buffer.from(String(args.data_base64 ?? ''), 'base64');
|
|
316
|
+
if (data.length > ctx.cfg.maxUploadBytes) return { ok: false, error: 'payload too large' };
|
|
317
|
+
await fsp.mkdir(path.dirname(chk.abs), { recursive: true });
|
|
318
|
+
{
|
|
319
|
+
const dir = path.dirname(chk.abs);
|
|
320
|
+
const tmp = path.join(dir, `.tmp-${Date.now()}-${Math.random().toString(36).slice(2)}`);
|
|
321
|
+
await fsp.writeFile(tmp, data);
|
|
322
|
+
await fsp.rename(tmp, chk.abs);
|
|
323
|
+
}
|
|
324
|
+
return { ok: true, path: chk.abs, bytes: data.length };
|
|
325
|
+
},
|
|
326
|
+
},
|
|
327
|
+
{
|
|
328
|
+
name: 'audit_log',
|
|
329
|
+
description:
|
|
330
|
+
'Read the detailed log of what happened on this machine: every tool call with its arguments, outcome and saved artifacts (screenshots, accessibility trees). Read-only.',
|
|
331
|
+
approval: false,
|
|
332
|
+
schema: S(
|
|
333
|
+
{
|
|
334
|
+
limit: { type: 'number', description: 'how many entries to return, default 30' },
|
|
335
|
+
tool: { type: 'string', description: 'only entries of this tool' },
|
|
336
|
+
since: { type: 'string', description: 'only entries newer than this ISO timestamp' },
|
|
337
|
+
},
|
|
338
|
+
[],
|
|
339
|
+
),
|
|
340
|
+
required: [],
|
|
341
|
+
handler: async (args) => {
|
|
342
|
+
let n = Number(args.limit);
|
|
343
|
+
if (!Number.isFinite(n) || n <= 0) n = 30;
|
|
344
|
+
n = Math.min(200, Math.floor(n));
|
|
345
|
+
let entries = tailAudit(args.tool || args.since ? Math.max(n * 10, 500) : n * 4);
|
|
346
|
+
if (args.tool) entries = entries.filter((e) => e.tool === args.tool);
|
|
347
|
+
if (args.since) {
|
|
348
|
+
const since = Date.parse(String(args.since));
|
|
349
|
+
if (!Number.isNaN(since)) entries = entries.filter((e) => Date.parse(e.ts) >= since);
|
|
350
|
+
}
|
|
351
|
+
entries = entries.slice(-n);
|
|
352
|
+
return { ok: true, count: entries.length, entries, artifacts_dir: auditDir() };
|
|
353
|
+
},
|
|
354
|
+
},
|
|
355
|
+
{
|
|
356
|
+
name: 'audit_artifact',
|
|
357
|
+
description:
|
|
358
|
+
'Fetch a saved artifact of a logged call: a screenshot (PNG as base64) or an accessibility tree (JSON). Read-only.',
|
|
359
|
+
approval: false,
|
|
360
|
+
schema: S(
|
|
361
|
+
{
|
|
362
|
+
entry: { type: 'string', description: 'entry id from audit_log' },
|
|
363
|
+
file: { type: 'string', description: 'artifact file name, e.g. "screen.png" or "ax-tree.json"' },
|
|
364
|
+
},
|
|
365
|
+
['entry', 'file'],
|
|
366
|
+
),
|
|
367
|
+
required: ['entry', 'file'],
|
|
368
|
+
handler: async (args) => {
|
|
369
|
+
const art = readArtifact(args.entry, args.file);
|
|
370
|
+
if (!art) {
|
|
371
|
+
return { ok: false, error: 'artifact_not_found', hint: 'Run audit_log to see the available artifacts.' };
|
|
372
|
+
}
|
|
373
|
+
if (/\.(png|jpe?g)$/i.test(art.file)) {
|
|
374
|
+
return { ok: true, kind: 'image', file: art.file, bytes: art.data.length, image_base64: art.data.toString('base64') };
|
|
375
|
+
}
|
|
376
|
+
const text = art.data.toString('utf8');
|
|
377
|
+
let json = null;
|
|
378
|
+
try {
|
|
379
|
+
json = JSON.parse(text);
|
|
380
|
+
} catch {
|
|
381
|
+
/* not json */
|
|
382
|
+
}
|
|
383
|
+
return { ok: true, kind: json ? 'json' : 'text', file: art.file, bytes: art.data.length, content: json ?? text.slice(0, 200000) };
|
|
384
|
+
},
|
|
385
|
+
},
|
|
386
|
+
{
|
|
387
|
+
name: 'sysinfo',
|
|
388
|
+
description: 'Read-only information about the remote machine: OS, user, uptime, memory, disks, network interfaces.',
|
|
389
|
+
approval: false,
|
|
390
|
+
schema: S({}),
|
|
391
|
+
required: [],
|
|
392
|
+
handler: async (_args, ctx) => {
|
|
393
|
+
const net = {};
|
|
394
|
+
for (const [name, addrs] of Object.entries(os.networkInterfaces())) {
|
|
395
|
+
net[name] = (addrs || []).map((a) => `${a.family}:${a.address}${a.internal ? ' (internal)' : ''}`);
|
|
396
|
+
}
|
|
397
|
+
return {
|
|
398
|
+
ok: true,
|
|
399
|
+
hostname: os.hostname(),
|
|
400
|
+
platform: os.platform(),
|
|
401
|
+
release: os.release(),
|
|
402
|
+
arch: os.arch(),
|
|
403
|
+
user: os.userInfo().username,
|
|
404
|
+
home: os.homedir(),
|
|
405
|
+
cwd: ctx.base,
|
|
406
|
+
uptime_sec: Math.round(os.uptime()),
|
|
407
|
+
loadavg: os.loadavg(),
|
|
408
|
+
totalmem: os.totalmem(),
|
|
409
|
+
freemem: os.freemem(),
|
|
410
|
+
cpus: os.cpus().length,
|
|
411
|
+
node: process.version,
|
|
412
|
+
network: net,
|
|
413
|
+
};
|
|
414
|
+
},
|
|
415
|
+
},
|
|
416
|
+
{
|
|
417
|
+
name: 'start_process',
|
|
418
|
+
description:
|
|
419
|
+
'Start a long-running background process (dev server, watcher, REPL). Returns a session_id to poll with read_process_output.',
|
|
420
|
+
approval: true,
|
|
421
|
+
schema: S({
|
|
422
|
+
command: { type: 'string' },
|
|
423
|
+
cwd: { type: 'string' },
|
|
424
|
+
}),
|
|
425
|
+
required: ['command'],
|
|
426
|
+
handler: async (args, ctx) => {
|
|
427
|
+
const command = String(args.command ?? '');
|
|
428
|
+
if (!command.trim()) return { ok: false, error: 'command is required' };
|
|
429
|
+
const base = args.cwd ? resolveTarget(args.cwd, ctx.base) : ctx.base;
|
|
430
|
+
const chk = checkPath(base, ctx.cfg, ctx.base);
|
|
431
|
+
if (!chk.ok) return { ok: false, error: chk.error, reason: chk.reason };
|
|
432
|
+
const child = spawn('/bin/sh', ['-lc', command], {
|
|
433
|
+
cwd: chk.abs,
|
|
434
|
+
env: process.env,
|
|
435
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
436
|
+
});
|
|
437
|
+
const sessionId = `proc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
|
|
438
|
+
const session = {
|
|
439
|
+
id: sessionId,
|
|
440
|
+
child,
|
|
441
|
+
command,
|
|
442
|
+
cwd: chk.abs,
|
|
443
|
+
out: [],
|
|
444
|
+
err: [],
|
|
445
|
+
outLen: 0,
|
|
446
|
+
errLen: 0,
|
|
447
|
+
cap: ctx.cfg.maxOutputBytes,
|
|
448
|
+
startedAt: Date.now(),
|
|
449
|
+
exited: false,
|
|
450
|
+
exitCode: null,
|
|
451
|
+
};
|
|
452
|
+
const cap = session.cap;
|
|
453
|
+
child.stdout.on('data', (c) => {
|
|
454
|
+
if (session.outLen >= cap) return;
|
|
455
|
+
const room = cap - session.outLen;
|
|
456
|
+
const part = c.length > room ? c.subarray(0, room) : c;
|
|
457
|
+
session.out.push(part);
|
|
458
|
+
session.outLen += part.length;
|
|
459
|
+
});
|
|
460
|
+
child.stderr.on('data', (c) => {
|
|
461
|
+
if (session.errLen >= cap) return;
|
|
462
|
+
const room = cap - session.errLen;
|
|
463
|
+
const part = c.length > room ? c.subarray(0, room) : c;
|
|
464
|
+
session.err.push(part);
|
|
465
|
+
session.errLen += part.length;
|
|
466
|
+
});
|
|
467
|
+
child.on('close', (code) => {
|
|
468
|
+
session.exited = true;
|
|
469
|
+
session.exitCode = code;
|
|
470
|
+
});
|
|
471
|
+
// R6: limit bash sessions to 20, cleanup oldest
|
|
472
|
+
if (ctx.sessions.size >= 20) {
|
|
473
|
+
const first = ctx.sessions.keys().next().value;
|
|
474
|
+
if (first) {
|
|
475
|
+
const old = ctx.sessions.get(first);
|
|
476
|
+
try { old.child?.kill('SIGKILL'); } catch {}
|
|
477
|
+
ctx.sessions.delete(first);
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
ctx.sessions.set(sessionId, session);
|
|
481
|
+
return { ok: true, session_id: sessionId, pid: child.pid, command, cwd: chk.abs };
|
|
482
|
+
},
|
|
483
|
+
},
|
|
484
|
+
{
|
|
485
|
+
name: 'read_process_output',
|
|
486
|
+
description: 'Read output of a process started with start_process. Waits up to timeout_sec for new output.',
|
|
487
|
+
approval: false,
|
|
488
|
+
schema: S({
|
|
489
|
+
session_id: { type: 'string' },
|
|
490
|
+
timeout_sec: { type: 'number' },
|
|
491
|
+
drain: { type: 'boolean' },
|
|
492
|
+
}),
|
|
493
|
+
required: ['session_id'],
|
|
494
|
+
handler: async (args, ctx) => {
|
|
495
|
+
const s = ctx.sessions.get(String(args.session_id ?? ''));
|
|
496
|
+
if (!s) return { ok: false, error: `unknown session: ${args.session_id}` };
|
|
497
|
+
const wait = Math.min(Number(args.timeout_sec || 0), 120);
|
|
498
|
+
const deadline = Date.now() + wait * 1000;
|
|
499
|
+
// B10 fix: return early when new output is available, don't wait full timeout
|
|
500
|
+
let lastLen = (s.outLen || 0) + (s.errLen || 0);
|
|
501
|
+
let idle = 0;
|
|
502
|
+
while (!s.exited && Date.now() < deadline) {
|
|
503
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
504
|
+
const curLen = (s.outLen || 0) + (s.errLen || 0);
|
|
505
|
+
if (curLen !== lastLen) {
|
|
506
|
+
// new output arrived - wait a bit more for burst, then return
|
|
507
|
+
lastLen = curLen;
|
|
508
|
+
idle = 0;
|
|
509
|
+
// if we already have output and wait was small, return quickly
|
|
510
|
+
if (wait <= 2) {
|
|
511
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
512
|
+
break;
|
|
513
|
+
}
|
|
514
|
+
} else {
|
|
515
|
+
idle++;
|
|
516
|
+
// if we have output and idle for 2 ticks, return early
|
|
517
|
+
if (lastLen > 0 && idle >= 2) break;
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
const stdout = Buffer.concat(s.out).toString('utf8');
|
|
521
|
+
const stderr = Buffer.concat(s.err).toString('utf8');
|
|
522
|
+
if (args.drain) {
|
|
523
|
+
s.out = [];
|
|
524
|
+
s.err = [];
|
|
525
|
+
s.outLen = 0;
|
|
526
|
+
s.errLen = 0;
|
|
527
|
+
}
|
|
528
|
+
return {
|
|
529
|
+
ok: true,
|
|
530
|
+
session_id: s.id,
|
|
531
|
+
running: !s.exited,
|
|
532
|
+
exit_code: s.exitCode,
|
|
533
|
+
stdout,
|
|
534
|
+
stderr,
|
|
535
|
+
uptime_sec: Math.round((Date.now() - s.startedAt) / 1000),
|
|
536
|
+
};
|
|
537
|
+
},
|
|
538
|
+
},
|
|
539
|
+
{
|
|
540
|
+
name: 'write_process',
|
|
541
|
+
description: 'Send input to a running process session (stdin).',
|
|
542
|
+
approval: false,
|
|
543
|
+
schema: S({
|
|
544
|
+
session_id: { type: 'string' },
|
|
545
|
+
input: { type: 'string' },
|
|
546
|
+
}),
|
|
547
|
+
required: ['session_id', 'input'],
|
|
548
|
+
handler: async (args, ctx) => {
|
|
549
|
+
const s = ctx.sessions.get(String(args.session_id ?? ''));
|
|
550
|
+
if (!s) return { ok: false, error: `unknown session: ${args.session_id}` };
|
|
551
|
+
if (s.exited) return { ok: false, error: 'process already exited' };
|
|
552
|
+
s.child.stdin.write(String(args.input ?? ''));
|
|
553
|
+
return { ok: true, session_id: s.id, written: String(args.input ?? '').length };
|
|
554
|
+
},
|
|
555
|
+
},
|
|
556
|
+
{
|
|
557
|
+
name: 'kill_process',
|
|
558
|
+
description: 'Terminate a running process session. Requires approval.',
|
|
559
|
+
approval: true,
|
|
560
|
+
schema: S({
|
|
561
|
+
session_id: { type: 'string' },
|
|
562
|
+
signal: { type: 'string', description: 'SIGTERM (default) or SIGKILL' },
|
|
563
|
+
}),
|
|
564
|
+
required: ['session_id'],
|
|
565
|
+
handler: async (args, ctx) => {
|
|
566
|
+
const s = ctx.sessions.get(String(args.session_id ?? ''));
|
|
567
|
+
if (!s) return { ok: false, error: `unknown session: ${args.session_id}` };
|
|
568
|
+
const signal = args.signal === 'SIGKILL' ? 'SIGKILL' : 'SIGTERM';
|
|
569
|
+
try {
|
|
570
|
+
s.child.kill(signal);
|
|
571
|
+
} catch (e) {
|
|
572
|
+
return { ok: false, error: e.message };
|
|
573
|
+
}
|
|
574
|
+
return { ok: true, session_id: s.id, signal, killed: true };
|
|
575
|
+
},
|
|
576
|
+
},
|
|
577
|
+
];
|
|
578
|
+
}
|
|
579
|
+
|