arena-bridge 0.10.0 → 0.12.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/src/cli.mjs CHANGED
@@ -14,7 +14,8 @@ import { pruneInbox } from './telegram.mjs';
14
14
  import { pruneApprovals } from './approvals.mjs';
15
15
  import { startTunnel, isPortOpen } from './tunnel.mjs';
16
16
  import { spawn, execSync, spawnSync } from 'node:child_process';
17
- import { parseDuration, trustState, saveTrust, clearTrust } from './trust.mjs';
17
+ import { parseDuration, trustState, openTrust, closeTrust, reconcileTrust } from './trust.mjs';
18
+ import { bridgeEvent, tunnelEvent } from './lifecycle.mjs';
18
19
  import { findPeekaboo } from './mac.mjs';
19
20
  import { coldStartMs, mem, uptimeSec } from './telemetry.mjs';
20
21
  import { tailLog, logPathForCli } from './log.mjs';
@@ -96,7 +97,7 @@ Commands:
96
97
  --paths p1,p2 only these paths (bash is not covered)
97
98
  --off | --status | --extend --for 1h
98
99
  audit [-n N] [--tool NAME] [--since DUR] [--from DATE] [--to DATE] [--json] Show the audit log
99
- cleanup [--days N] Remove old artifacts + approvals (default 14 days)
100
+ cleanup [--days N] Remove old artifacts + approvals (default 7 days)
100
101
  events [--json] Stream live events (approvals/audit) via SSE /v1/events
101
102
  logs [-n N] [--json] Show bridge.log (structured logs)
102
103
  config Manage configuration (get/set/edit)
@@ -189,11 +190,11 @@ async function cmdStart(args) {
189
190
  process.exit(1);
190
191
  }
191
192
  try {
192
- const { trustState, saveTrust } = await import('./trust.mjs');
193
+ const { trustState, openTrust } = await import('./trust.mjs');
193
194
  const st = trustState();
194
195
  if (!st.active) {
195
196
  const now = Date.now();
196
- saveTrust({ enabled: true, until: now + 3 * 3600 * 1000, tools: [], paths: [], createdAt: now });
197
+ openTrust({ until: now + 3 * 3600 * 1000, tools: [], paths: [], createdAt: now }, { via: 'launch', source: { channel: 'local' } });
197
198
  console.log('✓ trust window auto-opened for 3 h (all tools, any agent) — no approvals needed');
198
199
  }
199
200
  } catch {}
@@ -212,6 +213,7 @@ async function cmdStart(args) {
212
213
  process.exit(1);
213
214
  });
214
215
  server.listen(cfg.port, cfg.host, () => {
216
+ bridgeEvent('start', { port: cfg.port });
215
217
  const local = `http://${cfg.host}:${cfg.port}`;
216
218
  console.log(`arena-bridge listening on ${local} (device "${cfg.device}")`);
217
219
  console.log(`\nExpose it to the cloud agent, e.g.:\n cloudflared tunnel --url ${local}\n ngrok http ${cfg.port}\n tailscale funnel --bg ${cfg.port}\n`);
@@ -221,6 +223,7 @@ async function cmdStart(args) {
221
223
  console.log('-----8<-----');
222
224
  });
223
225
  const bye = () => {
226
+ bridgeEvent('stop', { reason: 'signal' });
224
227
  server.close(() => process.exit(0));
225
228
  setTimeout(() => process.exit(0), 2000).unref();
226
229
  };
@@ -241,11 +244,11 @@ async function cmdTunnel(args) {
241
244
 
242
245
  // Auto-open blanket trust window on start (3h, all tools, any agent) per user request
243
246
  try {
244
- const { trustState, saveTrust } = await import('./trust.mjs');
247
+ const { trustState, openTrust } = await import('./trust.mjs');
245
248
  const st = trustState();
246
249
  if (!st.active) {
247
250
  const now = Date.now();
248
- saveTrust({ enabled: true, until: now + 3 * 3600 * 1000, tools: [], paths: [], createdAt: now });
251
+ openTrust({ until: now + 3 * 3600 * 1000, tools: [], paths: [], createdAt: now }, { via: 'launch', source: { channel: 'local' } });
249
252
  console.log('✓ trust window auto-opened for 3 h (all tools, any agent) — no approvals needed');
250
253
  }
251
254
  } catch {}
@@ -256,6 +259,7 @@ async function cmdTunnel(args) {
256
259
  } else {
257
260
  server = createDirectServer(cfg, engine);
258
261
  await new Promise((r) => server.listen(port, cfg.host, r));
262
+ bridgeEvent('start', { port });
259
263
  console.log(`arena-bridge API on http://${cfg.host}:${port}`);
260
264
  }
261
265
 
@@ -266,6 +270,7 @@ async function cmdTunnel(args) {
266
270
  bin,
267
271
  authtoken: args.flags.authtoken,
268
272
  domain: args.flags.domain,
273
+ onExit: (code) => tunnelEvent('down', { code }),
269
274
  });
270
275
 
271
276
  let publicUrl;
@@ -288,6 +293,7 @@ async function cmdTunnel(args) {
288
293
 
289
294
  cfg.publicUrl = publicUrl;
290
295
  cfg.port = port;
296
+ tunnelEvent('up', { url: new URL(publicUrl).host });
291
297
  saveConfig(cfg);
292
298
 
293
299
  onUrl((url) => {
@@ -295,6 +301,7 @@ async function cmdTunnel(args) {
295
301
  publicUrl = url;
296
302
  cfg.publicUrl = url;
297
303
  saveConfig(cfg);
304
+ tunnelEvent('up', { url: new URL(url).host, reason: 'reconnected' });
298
305
  console.log(`\n⚠ tunnel reconnected — new public URL: ${url}`);
299
306
  console.log('Update the base URL in the agent chat (arena-bridge prompt prints a fresh copy).');
300
307
  });
@@ -307,6 +314,7 @@ async function cmdTunnel(args) {
307
314
  console.log('Ctrl+C stops both the tunnel and the API.');
308
315
 
309
316
  const bye = () => {
317
+ bridgeEvent('stop', { reason: 'signal' });
310
318
  try {
311
319
  child.kill();
312
320
  } catch {
@@ -411,11 +419,14 @@ function cmdApprove(args) {
411
419
 
412
420
  function cmdTrust(args) {
413
421
  const state = trustState();
422
+ reconcileTrust();
423
+ const via = /^[a-z]{1,20}$/.test(String(args.flags.source || '')) ? args.flags.source : 'cli';
424
+ const source = { channel: 'cli' };
414
425
  if (args.flags.extend || args.flags.extend) {
415
426
  const cur = trustState();
416
427
  if (!cur.active) { console.error('no active trust window to extend — use arena-bridge trust --for 2h'); process.exit(1); }
417
428
  const ms = parseDuration(args.flags.for || args.flags.extend || '1h');
418
- const saved = saveTrust({ ...cur, until: cur.until + ms, enabled: true, createdAt: cur.createdAt || Date.now() });
429
+ const saved = openTrust({ ...cur, until: cur.until + ms, createdAt: cur.createdAt || Date.now() }, { via, source });
419
430
  console.log(`✓ trust window extended: until ${new Date(saved.until).toLocaleString()} (+${Math.round(ms/60000)} min)`);
420
431
  return;
421
432
  }
@@ -430,7 +441,7 @@ function cmdTrust(args) {
430
441
  return;
431
442
  }
432
443
  if (args.flags.off) {
433
- clearTrust();
444
+ closeTrust({ via, source });
434
445
  console.log('✓ trust window cleared — every side-effecting action needs approval again');
435
446
  return;
436
447
  }
@@ -465,13 +476,7 @@ function cmdTrust(args) {
465
476
  .filter(Boolean);
466
477
  const tools = list(args.flags.tools);
467
478
  const paths = list(args.flags.paths).map((p) => path.resolve(p.replace(/^~/, os.homedir())));
468
- const saved = saveTrust({
469
- enabled: true,
470
- until: Date.now() + ms,
471
- tools,
472
- paths,
473
- createdAt: Date.now(),
474
- });
479
+ const saved = openTrust({ until: Date.now() + ms, tools, paths, createdAt: Date.now() }, { via, source });
475
480
  console.log(`✓ trust window: until ${new Date(saved.until).toLocaleString()} (${Math.round(ms / 60000)} min)`);
476
481
  console.log(` tools: ${tools.length ? tools.join(', ') : 'all side-effecting tools'}`);
477
482
  console.log(` paths: ${paths.length ? paths.join(', ') : 'no path restriction'}`);
@@ -485,7 +490,7 @@ function cmdAudit(args) {
485
490
  return;
486
491
  }
487
492
  if (what === 'prune') {
488
- const res = pruneArtifacts(Number(args.flags.days || 14));
493
+ const res = pruneArtifacts(Number(args.flags.days || 7));
489
494
  console.log(`removed ${res.removed} artifact folder(s), ${res.freed_bytes} bytes`);
490
495
  return;
491
496
  }
package/src/device.mjs CHANGED
@@ -43,7 +43,7 @@ export async function runDevice(cfg, engine, { log = console.log } = {}) {
43
43
 
44
44
  let result;
45
45
  try {
46
- result = await engine.call(job.tool, job.args || {});
46
+ result = await engine.call(job.tool, job.args || {}, { source: job.source || { channel: 'hub', ip: null, country: null, host: null, client: null } });
47
47
  } catch (e) {
48
48
  result = { ok: false, error: e.message };
49
49
  }
package/src/direct.mjs CHANGED
@@ -8,7 +8,10 @@ import { buildPrompt } from './prompt.mjs';
8
8
  import { listApprovals, decide, settle } from './approvals.mjs';
9
9
  import { checkPath } from './policy.mjs';
10
10
  import { loadConfig } from './config.mjs';
11
- import { tailAudit, readArtifact, auditDir } from './audit.mjs';
11
+ import { tailAudit, readArtifact, auditDir, audit, auditPage, findEntry, lean, headCursor, LEVELS, pruneAudit, pruneArtifacts } from './audit.mjs';
12
+ import { reconcileTrust } from './trust.mjs';
13
+ import { describeSource, sourceOf, admitUnauthorized } from './source.mjs';
14
+ import { errorResponse } from './errors.mjs';
12
15
  import { startPoller, parseCommand, sendTelegram, answerCallback, editMessageText } from './telegram.mjs';
13
16
 
14
17
  export function createDirectServer(cfg, engine) {
@@ -95,6 +98,14 @@ export function createDirectServer(cfg, engine) {
95
98
  const cfgNow = loadConfig();
96
99
  mcpCtx.cfg = cfgNow;
97
100
  if (!isAuthorized(req, cfgNow)) {
101
+ const source = describeSource(req, 'http');
102
+ const seen = admitUnauthorized(source.ip);
103
+ if (seen.previousSuppressed) {
104
+ audit({ kind: 'auth', tool: null, status: 'unauthorized', error: 'UNAUTHORIZED', via: 'direct', actor: 'system', source, args: { path: p, suppressed: seen.previousSuppressed } });
105
+ }
106
+ if (seen.write) {
107
+ audit({ kind: 'auth', tool: null, status: 'unauthorized', error: 'UNAUTHORIZED', via: 'direct', actor: 'system', source, args: { path: p, method: req.method, count_in_minute: seen.count } });
108
+ }
98
109
  res.setHeader('www-authenticate', 'Bearer');
99
110
  return sendJson(res, 401, { ok: false, error: 'unauthorized' });
100
111
  }
@@ -126,14 +137,49 @@ export function createDirectServer(cfg, engine) {
126
137
  }
127
138
 
128
139
  if (req.method === 'GET' && p === '/audit') {
129
- const raw = url.searchParams.get('limit');
130
- let limit = 30;
131
- if (raw !== null && raw !== '') {
132
- const parsed = Number(raw);
133
- if (!Number.isFinite(parsed) || parsed <= 0) return sendJson(res, 400, { ok: false, error: 'invalid limit' });
134
- limit = Math.min(200, Math.floor(parsed));
135
- }
136
- return sendJson(res, 200, { ok: true, entries: tailAudit(limit), artifacts_dir: auditDir() });
140
+ const q = url.searchParams;
141
+ const raw = q.get('limit');
142
+ const limit = raw === null || raw === '' ? 100 : Number(raw);
143
+ if (!Number.isFinite(limit) || limit <= 0) return sendJson(res, 400, { ok: false, error: 'invalid limit' });
144
+ const page = auditPage({
145
+ limit: Math.min(500, Math.floor(limit)),
146
+ before: q.get('before') || undefined,
147
+ after: q.get('after') || undefined,
148
+ tool: q.get('tool') || undefined,
149
+ kind: q.get('kind') || undefined,
150
+ level: q.get('level') || undefined,
151
+ });
152
+ if (page.error) return sendJson(res, 400, { ok: false, error: page.error });
153
+ return sendJson(res, 200, {
154
+ ok: true,
155
+ entries: page.entries.map(lean),
156
+ next: page.next,
157
+ has_more: page.has_more,
158
+ reset: page.reset,
159
+ head: headCursor(),
160
+ artifacts_dir: auditDir(),
161
+ });
162
+ }
163
+
164
+ if (req.method === 'GET' && p === '/audit/entry') {
165
+ const id = url.searchParams.get('id');
166
+ if (!id) return sendJson(res, 400, { ok: false, error: 'id query parameter is required' });
167
+ const entry = findEntry(id);
168
+ if (!entry) return sendJson(res, 404, { ok: false, error: 'entry_not_found' });
169
+ return sendJson(res, 200, { ok: true, entry });
170
+ }
171
+
172
+ if (req.method === 'POST' && p === '/log/event') {
173
+ // Interface steps only: trust and service events are written by their own modules.
174
+ const body = await readJson(req, 16 * 1024);
175
+ const tool = typeof body.tool === 'string' ? body.tool : 'gui';
176
+ const level = body.level ?? 'notice';
177
+ const ok = body.kind === 'step' && typeof body.status === 'string' && body.status.length <= 20
178
+ && typeof body.message === 'string' && body.message.length <= 500
179
+ && LEVELS.includes(level) && /^[\w.-]{1,40}$/.test(tool);
180
+ if (!ok) return sendJson(res, 400, { ok: false, error: 'invalid event' });
181
+ audit({ kind: 'step', tool, status: body.status, level, message: body.message, via: 'gui', actor: 'user', source: describeSource(req, 'http') });
182
+ return sendJson(res, 200, { ok: true });
137
183
  }
138
184
 
139
185
  if (req.method === 'GET' && p === '/audit/artifact') {
@@ -171,6 +217,7 @@ export function createDirectServer(cfg, engine) {
171
217
  const expected = loadConfig().localToken;
172
218
  const presented = bearer(req);
173
219
  if (!expected || !presented || !safeEqual(presented, expected)) {
220
+ audit({ kind: 'approval', tool: null, status: 'forbidden', error: 'FORBIDDEN', via: 'api', actor: 'agent', source: await sourceOf(req, 'http'), args: { approval_id: approveMatch[1] } });
174
221
  return sendJson(res, 403, {
175
222
  ok: false,
176
223
  error: 'forbidden',
@@ -185,20 +232,25 @@ export function createDirectServer(cfg, engine) {
185
232
 
186
233
  if (req.method === 'POST' && p === '/exec') {
187
234
  const body = await readJson(req, cfgNow.maxUploadBytes);
235
+ const source = await sourceOf(req, 'http');
188
236
  const result = await engine.call('bash', {
189
237
  command: body.command,
190
238
  cwd: body.cwd,
191
239
  timeout_sec: body.timeout_sec,
192
240
  env: body.env,
193
- });
241
+ }, { source });
194
242
  const status = result.ok ? 200 : (result.error === 'APPROVAL_PENDING' ? 202 : 400);
195
243
  return sendJson(res, status, result);
196
244
  }
197
245
 
198
246
  if (req.method === 'POST' && p === '/call') {
199
247
  const body = await readJson(req, cfgNow.maxUploadBytes);
200
- if (!body.tool) return sendJson(res, 400, { ok: false, error: 'tool is required' });
201
- const result = await engine.call(String(body.tool), body.args || {});
248
+ const source = await sourceOf(req, 'http');
249
+ if (!body.tool) {
250
+ audit({ kind: 'call', tool: null, status: 'rejected', error: 'INVALID_ARGS', via: 'direct', source, args: {} });
251
+ return sendJson(res, 400, { ok: false, error: 'tool is required' });
252
+ }
253
+ const result = await engine.call(String(body.tool), body.args || {}, { source });
202
254
  // R5: return 202 for pending approvals, so client can poll GET /approvals/:id
203
255
  const status = result.ok ? 200 : (result.error === 'APPROVAL_PENDING' ? 202 : 400);
204
256
  return sendJson(res, status, result);
@@ -206,14 +258,18 @@ export function createDirectServer(cfg, engine) {
206
258
 
207
259
  if (p === '/files') {
208
260
  const target = url.searchParams.get('path');
261
+ const source = await sourceOf(req, 'http');
262
+ const toolName = req.method === 'GET' ? 'file_get' : req.method === 'DELETE' ? 'delete_path' : 'file_put';
209
263
  if (!target) return sendJson(res, 400, { ok: false, error: 'path query parameter is required' });
210
264
  const chk = checkPath(target, cfgNow, engine.base, { write: req.method !== 'GET' });
211
- if (!chk.ok) return sendJson(res, 403, { ok: false, error: chk.error, reason: chk.reason });
265
+ if (!chk.ok) {
266
+ audit({ tool: toolName, args: { path: target }, status: 'error', error: chk.error, via: 'files_api', source });
267
+ return sendJson(res, 403, { ok: false, error: chk.error, reason: chk.reason });
268
+ }
212
269
  // PUT/DELETE must go through the approval gate and audit, like the tools
213
270
  if (req.method !== 'GET') {
214
- const toolName = req.method === 'DELETE' ? 'delete_path' : 'file_put';
215
271
  const { authorize } = await import('./gate.mjs');
216
- const resAuth = await authorize(toolName, { path: target }, cfgNow);
272
+ const resAuth = await authorize(toolName, { path: target }, cfgNow, source);
217
273
  if (!resAuth.ok) {
218
274
  const status = resAuth.status || 'denied';
219
275
  const pending = resAuth.pending;
@@ -228,21 +284,23 @@ export function createDirectServer(cfg, engine) {
228
284
  try {
229
285
  if (req.method === 'GET') {
230
286
  const buf = await fsp.readFile(chk.abs);
287
+ audit({ tool: 'file_get', args: { path: target }, status: 'ok', via: 'files_api', source, bytes: buf.length });
231
288
  return sendRaw(res, 200, buf);
232
289
  }
233
290
  if (req.method === 'PUT' || req.method === 'POST') {
234
291
  const buf = await readBody(req, cfgNow.maxUploadBytes);
235
292
  await fsp.mkdir(path.dirname(chk.abs), { recursive: true });
236
293
  await fsp.writeFile(chk.abs, buf);
237
- try { const { audit } = await import('./audit.mjs'); audit({ tool: 'file_put', args: { path: target }, status: 'ok', via: 'files_api' }); } catch {}
294
+ audit({ tool: 'file_put', args: { path: target }, status: 'ok', via: 'files_api', source, bytes: buf.length });
238
295
  return sendJson(res, 200, { ok: true, path: chk.abs, bytes: buf.length });
239
296
  }
240
297
  if (req.method === 'DELETE') {
241
298
  await fsp.rm(chk.abs, { recursive: true, force: true });
242
- try { const { audit } = await import('./audit.mjs'); audit({ tool: 'delete_path', args: { path: target }, status: 'ok', via: 'files_api' }); } catch {}
299
+ audit({ tool: 'delete_path', args: { path: target }, status: 'ok', via: 'files_api', source });
243
300
  return sendJson(res, 200, { ok: true, path: chk.abs, deleted: true });
244
301
  }
245
302
  } catch (e) {
303
+ audit({ tool: toolName, args: { path: target }, status: 'error', error: e.message, via: 'files_api', source });
246
304
  return sendJson(res, 400, { ok: false, error: e.message });
247
305
  }
248
306
  return sendJson(res, 405, { ok: false, error: 'method not allowed' });
@@ -270,11 +328,15 @@ export function createDirectServer(cfg, engine) {
270
328
  const pending = listApprovals().filter(a=>a.status==='pending');
271
329
  send('approvals', { pending: pending.length, approvals: pending.slice(0,10) });
272
330
  } catch {}
273
- try { const { tailAudit } = await import('./audit.mjs'); send('audit', { entries: tailAudit(5) }); } catch {}
331
+ let cursor = headCursor();
332
+ try { send('audit', { entries: tailAudit(5).map(lean) }); } catch {}
274
333
  send('hello', { version: VERSION, time: new Date().toISOString() });
275
334
  const interval = setInterval(async ()=>{
276
335
  if (closed) { clearInterval(interval); return; }
277
336
  try {
337
+ const delta = auditPage({ after: cursor, limit: 200 });
338
+ cursor = delta.next || cursor;
339
+ if (delta.entries.length) send('audit', { entries: delta.entries.map(lean) });
278
340
  const pending = listApprovals().filter(a=>a.status==='pending');
279
341
  // simple: send heartbeat + counts every tick; client can diff
280
342
  send('heartbeat', { ts: Date.now(), pending_approvals: pending.length });
@@ -288,17 +350,28 @@ export function createDirectServer(cfg, engine) {
288
350
  if (req.method !== 'POST') {
289
351
  return sendJson(res, 405, { ok: false, error: 'method not allowed', hint: 'use POST /mcp' });
290
352
  }
291
- return handleMcp(req, res, mcpCtx);
353
+ const source = await sourceOf(req, 'mcp');
354
+ return handleMcp(req, res, { ...mcpCtx, callTool: (name, args) => engine.call(name, args, { source }) });
292
355
  }
293
356
 
294
357
  return sendJson(res, 404, { ok: false, error: `no route for ${req.method} ${p}` });
295
358
  } catch (e) {
296
- return sendJson(res, 500, { ok: false, error: e.message });
359
+ const code = /invalid JSON/.test(e.message) ? 'INVALID_JSON' : /too large/.test(e.message) ? 'PAYLOAD_TOO_LARGE' : null;
360
+ if (!code) return sendJson(res, 500, { ok: false, error: e.message });
361
+ if (p === '/call' || p === '/exec') {
362
+ audit({ kind: 'call', tool: null, status: 'rejected', error: code, via: 'direct', source: describeSource(req, 'http'), args: {} });
363
+ }
364
+ return sendJson(res, code === 'PAYLOAD_TOO_LARGE' ? 413 : 400, errorResponse(code));
297
365
  }
298
366
  });
299
367
 
300
368
  const poller = startPoller(cfg, { onMessage: handleTelegramMessage, onCallback: handleTelegramCallback });
301
- server.on('close', () => poller?.stop());
369
+ try { reconcileTrust(); pruneAudit(); pruneArtifacts(); } catch {}
370
+ const maint = setInterval(() => { try { reconcileTrust(); } catch {} }, 5000);
371
+ const sweep = setInterval(() => { try { pruneAudit(); pruneArtifacts(); } catch {} }, 3600000);
372
+ maint.unref();
373
+ sweep.unref();
374
+ server.on('close', () => { poller?.stop(); clearInterval(maint); clearInterval(sweep); });
302
375
 
303
376
  return server;
304
377
  }
package/src/engine.mjs CHANGED
@@ -43,7 +43,7 @@ export class Engine {
43
43
  return [...toolCatalog(), ...this.browser.tools(), ...macTools(this.cfg), ...telegramTools(this.cfg)];
44
44
  }
45
45
 
46
- async call(name, args = {}, { requireApproval, cfg } = {}) {
46
+ async call(name, args = {}, { requireApproval, cfg, source } = {}) {
47
47
  let cfgNow;
48
48
  if (cfg) {
49
49
  cfgNow = cfg;
@@ -56,6 +56,10 @@ export class Engine {
56
56
  }
57
57
  }
58
58
  this.cfg = cfgNow;
59
+ const src = source || { channel: 'local', ip: null, country: null, host: null, client: null };
60
+ const record = (fields) => {
61
+ if (this.cfg.audit !== false) audit({ tool: name, args, source: src, kind: name === 'log_note' ? 'note' : 'call', ...fields });
62
+ };
59
63
  const tool = this.catalog().find((t) => t.name === name);
60
64
  if (!tool) {
61
65
  const all = this.catalog().map(t=>t.name);
@@ -63,6 +67,7 @@ export class Engine {
63
67
  const lev=(a,b)=>{ a=String(a); b=String(b); const m=a.length,n=b.length; const dp=Array(m+1).fill(null).map(()=>Array(n+1).fill(0)); for(let i=0;i<=m;i++) dp[i][0]=i; for(let j=0;j<=n;j++) dp[0][j]=j; for(let i=1;i<=m;i++) for(let j=1;j<=n;j++) dp[i][j]=Math.min(dp[i-1][j]+1, dp[i][j-1]+1, dp[i-1][j-1]+(a[i-1]===b[j-1]?0:1)); return dp[m][n]; };
64
68
  for (const n of all) { const d=lev(name,n); if(d<bestD){bestD=d; best=n;} }
65
69
  const hint = best && bestD <= 3 ? `did you mean '${best}'?` : `available: ${all.slice(0,10).join(', ')}`;
70
+ record({ kind: 'call', status: 'rejected', error: 'UNKNOWN_TOOL', via: 'direct' });
66
71
  return errorResponse('UNKNOWN_TOOL', { message: `unknown tool: ${name}`, tool: name, hint });
67
72
  }
68
73
  const started = Date.now();
@@ -73,6 +78,7 @@ export class Engine {
73
78
  const ctx = Object.create(this);
74
79
  ctx.entryId = entryId;
75
80
  ctx.artifacts = [];
81
+ ctx.source = src;
76
82
  ctx.artifact = (kind, file, data, meta) => {
77
83
  const saved = saveArtifact(entryId, kind, file, data, meta);
78
84
  if (saved) ctx.artifacts.push(saved);
@@ -84,25 +90,24 @@ export class Engine {
84
90
  if (requireApproval === true) needApproval = true;
85
91
  else if (requireApproval === false) needApproval = false;
86
92
 
93
+ const artifactsOf = () => (ctx.artifacts.length ? ctx.artifacts : undefined);
94
+
87
95
  if (needApproval) {
88
96
  const trust = trustState();
89
97
  if (trustAllows(trust, tool.name, args, this.cfg)) {
90
98
  const res = await tool.handler(args, ctx);
91
- if (this.cfg.audit !== false) {
92
- audit({ id: entryId, tool: tool.name, args, status: res.ok ? 'ok' : 'error', duration_ms: Date.now() - started, via: 'trust_window', exit_code: res.exit_code, error: res.ok ? undefined : res.error, artifacts: ctx.artifacts.length ? ctx.artifacts : undefined });
93
- }
99
+ record({ id: entryId, status: res.ok ? 'ok' : 'error', duration_ms: Date.now() - started, via: 'trust_window', exit_code: res.exit_code, error: res.ok ? undefined : res.error, artifacts: artifactsOf() });
94
100
  return res;
95
101
  }
96
102
  approval = await requestApproval(tool.name, args, this.cfg);
97
103
  if (!approval.approved) {
98
104
  const status = approval.rec?.status || 'denied';
99
- if (this.cfg.audit !== false) {
100
- audit({ id: entryId, tool: tool.name, args, status: 'approval_denied', approval_status: status });
101
- }
102
105
  const pending = status === 'pending' || status === 'timeout' || status === 'expired';
106
+ const code = pending ? 'APPROVAL_PENDING' : 'APPROVAL_DENIED';
107
+ record({ id: entryId, status: 'approval_denied', approval_status: status, error: code, via: 'approval', duration_ms: Date.now() - started });
103
108
  return {
104
109
  ok: false,
105
- error: pending ? 'APPROVAL_PENDING' : 'APPROVAL_DENIED',
110
+ error: code,
106
111
  status,
107
112
  pending,
108
113
  reason: pending
@@ -116,33 +121,21 @@ export class Engine {
116
121
  }
117
122
  }
118
123
 
124
+ const via = approval ? 'approval' : 'direct';
119
125
  try {
120
126
  const res = await tool.handler(args, ctx);
121
- if (this.cfg.audit !== false) {
122
- audit({
123
- id: entryId,
124
- tool: tool.name,
125
- args,
126
- status: res.ok ? 'ok' : 'error',
127
- duration_ms: Date.now() - started,
128
- exit_code: res.exit_code,
129
- error: res.ok ? undefined : res.error,
130
- artifacts: ctx.artifacts.length ? ctx.artifacts : undefined,
131
- });
132
- }
127
+ record({
128
+ id: entryId,
129
+ status: res.ok ? 'ok' : 'error',
130
+ duration_ms: Date.now() - started,
131
+ exit_code: res.exit_code,
132
+ error: res.ok ? undefined : res.error,
133
+ via,
134
+ artifacts: artifactsOf(),
135
+ });
133
136
  return res;
134
137
  } catch (e) {
135
- if (this.cfg.audit !== false) {
136
- audit({
137
- id: entryId,
138
- tool: tool.name,
139
- args,
140
- status: 'exception',
141
- duration_ms: Date.now() - started,
142
- error: e.message,
143
- artifacts: ctx.artifacts.length ? ctx.artifacts : undefined,
144
- });
145
- }
138
+ record({ id: entryId, status: 'exception', duration_ms: Date.now() - started, error: e.message, via, artifacts: artifactsOf() });
146
139
  return { ok: false, error: e.message };
147
140
  }
148
141
  }
package/src/errors.mjs CHANGED
@@ -15,6 +15,8 @@ export const ERROR_CODES = {
15
15
  PAYLOAD_TOO_LARGE: { message: 'payload exceeds maxUploadBytes', hint: 'reduce file size or increase limit', retryable: false },
16
16
  INVALID_JSON: { message: 'invalid JSON body', hint: 'check JSON syntax', retryable: false },
17
17
  UNKNOWN_TOOL: { message: 'unknown tool', hint: 'GET /tools for catalog', retryable: false },
18
+ INVALID_ARGS: { message: 'arguments are missing or malformed', hint: 'check the tool schema in GET /tools', retryable: false },
19
+ RATE_LIMITED: { message: 'too many calls in a short time', hint: 'wait a second and retry', retryable: true },
18
20
  };
19
21
 
20
22
  export function errorResponse(code, extra = {}) {
package/src/gate.mjs CHANGED
@@ -2,7 +2,7 @@ import { trustState, trustAllows } from './trust.mjs';
2
2
  import { requestApproval } from './approvals.mjs';
3
3
  import { audit } from './audit.mjs';
4
4
 
5
- export async function authorize(tool, args, cfg) {
5
+ export async function authorize(tool, args, cfg, source = null) {
6
6
  const trust = trustState();
7
7
  let needApproval = true;
8
8
  if (trustAllows(trust, tool, args, cfg)) needApproval = false;
@@ -11,8 +11,8 @@ export async function authorize(tool, args, cfg) {
11
11
  const approval = await requestApproval(tool, args, cfg);
12
12
  if (!approval.approved) {
13
13
  const status = approval.rec?.status || "denied";
14
- try { audit({ tool, args, status: "approval_denied", approval_status: status }); } catch {}
15
14
  const pending = status === "pending" || status === "timeout" || status === "expired";
15
+ try { audit({ tool, args, status: "approval_denied", approval_status: status, via: "approval", source, error: pending ? "APPROVAL_PENDING" : "APPROVAL_DENIED" }); } catch {}
16
16
  return { ok: false, status, approval_id: approval.rec?.id || null, pending };
17
17
  }
18
18
  return { ok: true };
package/src/hub.mjs CHANGED
@@ -9,6 +9,8 @@ import { listApprovals, decide } from './approvals.mjs';
9
9
  import { checkPath } from './policy.mjs';
10
10
  import { loadConfig } from './config.mjs';
11
11
  import fsp from 'node:fs/promises';
12
+ import { audit } from './audit.mjs';
13
+ import { sourceOf, describeSource, admitUnauthorized } from './source.mjs';
12
14
 
13
15
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
14
16
 
@@ -32,7 +34,7 @@ export function createHubServer(cfg) {
32
34
  const queues = new Map(); // name -> [{id, tool, args}]
33
35
  const jobs = new Map(); // id -> { resolve, timer }
34
36
 
35
- const dispatch = (device, tool, args, timeoutSec = 120) =>
37
+ const dispatch = (device, tool, args, timeoutSec = 120, source = null) =>
36
38
  new Promise((resolve) => {
37
39
  const id = crypto.randomUUID();
38
40
  const timer = setTimeout(() => {
@@ -45,11 +47,11 @@ export function createHubServer(cfg) {
45
47
  }, (timeoutSec + 15) * 1000);
46
48
  jobs.set(id, { resolve, timer });
47
49
  const q = queues.get(device) || [];
48
- q.push({ id, tool, args });
50
+ q.push({ id, tool, args, source });
49
51
  queues.set(device, q);
50
52
  });
51
53
 
52
- const callTool = async (tool, args) => {
54
+ const callTool = async (tool, args, source = null) => {
53
55
  const device = args?.device || cfg.device;
54
56
  if (!device) return { ok: false, error: 'no target device specified' };
55
57
  const known = devices.get(device);
@@ -58,7 +60,7 @@ export function createHubServer(cfg) {
58
60
  }
59
61
  const clean = { ...args };
60
62
  delete clean.device;
61
- return dispatch(device, tool, clean, Number(args?.timeout_sec || 120));
63
+ return dispatch(device, tool, clean, Number(args?.timeout_sec || 120), source);
62
64
  };
63
65
 
64
66
  const mcpCtx = {
@@ -112,7 +114,7 @@ export function createHubServer(cfg) {
112
114
  res.writeHead(204).end();
113
115
  return;
114
116
  }
115
- return sendJson(res, 200, { id: job.id, tool: job.tool, args: job.args });
117
+ return sendJson(res, 200, { id: job.id, tool: job.tool, args: job.args, source: job.source });
116
118
  }
117
119
  if (req.method === 'POST' && p === '/device/result') {
118
120
  const body = await readJson(req, cfg.maxUploadBytes);
@@ -128,6 +130,14 @@ export function createHubServer(cfg) {
128
130
 
129
131
  /* ---------- agent side (agent token) ---------- */
130
132
  if (!isAuthorized(req, loadConfig())) {
133
+ const source = describeSource(req, 'http');
134
+ const seen = admitUnauthorized(source.ip);
135
+ if (seen.previousSuppressed) {
136
+ audit({ kind: 'auth', tool: null, status: 'unauthorized', error: 'UNAUTHORIZED', via: 'hub', actor: 'system', source, args: { path: p, suppressed: seen.previousSuppressed } });
137
+ }
138
+ if (seen.write) {
139
+ audit({ kind: 'auth', tool: null, status: 'unauthorized', error: 'UNAUTHORIZED', via: 'hub', actor: 'system', source, args: { path: p, method: req.method, count_in_minute: seen.count } });
140
+ }
131
141
  res.setHeader('www-authenticate', 'Bearer');
132
142
  return sendJson(res, 401, { ok: false, error: 'unauthorized' });
133
143
  }
@@ -177,20 +187,22 @@ export function createHubServer(cfg) {
177
187
 
178
188
  if (req.method === 'POST' && p === '/exec') {
179
189
  const body = await readJson(req, cfg.maxUploadBytes);
190
+ const source = await sourceOf(req, 'http');
180
191
  const result = await callTool('bash', {
181
192
  device: body.device,
182
193
  command: body.command,
183
194
  cwd: body.cwd,
184
195
  timeout_sec: body.timeout_sec,
185
196
  env: body.env,
186
- });
197
+ }, source);
187
198
  return sendJson(res, result.ok ? 200 : 400, result);
188
199
  }
189
200
 
190
201
  if (req.method === 'POST' && p === '/call') {
191
202
  const body = await readJson(req, cfg.maxUploadBytes);
192
203
  if (!body.tool) return sendJson(res, 400, { ok: false, error: 'tool is required' });
193
- const result = await callTool(String(body.tool), body.args || {});
204
+ const source = await sourceOf(req, 'http');
205
+ const result = await callTool(String(body.tool), body.args || {}, source);
194
206
  return sendJson(res, result.ok ? 200 : 400, result);
195
207
  }
196
208
 
@@ -222,7 +234,8 @@ export function createHubServer(cfg) {
222
234
  }
223
235
 
224
236
  if (req.method === 'POST' && p === '/mcp') {
225
- return handleMcp(req, res, mcpCtx);
237
+ const source = await sourceOf(req, 'mcp');
238
+ return handleMcp(req, res, { ...mcpCtx, callTool: (name, args) => callTool(name, args, source) });
226
239
  }
227
240
 
228
241
  return sendJson(res, 404, { ok: false, error: `no route for ${req.method} ${p}` });
@@ -0,0 +1,13 @@
1
+ import { audit } from './audit.mjs';
2
+ import { VERSION } from './version.mjs';
3
+
4
+ /** Launchd jobs set XPC_SERVICE_NAME; anything else was started by hand. */
5
+ const origin = () => (process.env.XPC_SERVICE_NAME ? 'launchd' : 'cli');
6
+
7
+ export function bridgeEvent(status, { port, reason } = {}) {
8
+ audit({ kind: 'service', tool: 'bridge', status, via: origin(), source: { channel: 'local' }, pid: process.pid, version: VERSION, port, reason });
9
+ }
10
+
11
+ export function tunnelEvent(status, extra = {}) {
12
+ audit({ kind: 'tunnel', tool: 'tunnel', status, via: origin(), ...extra });
13
+ }
package/src/prompt.mjs CHANGED
@@ -109,6 +109,7 @@ Every call is logged with its arguments, result and duration. Screenshots taken
109
109
  the accessibility trees that were read are stored next to the log.
110
110
  - \`audit_log\` — the recent calls (filter by tool or time).
111
111
  - \`audit_artifact\` — fetch a saved artifact: a screenshot (base64 PNG) or an accessibility tree (JSON).
112
+ - \`log_note\` — write a short comment into the work log before a step (what you are about to do and why). It changes nothing else.
112
113
  Use them when you need to look back at what was on the screen or what the interface contained.
113
114
 
114
115
  ## Talking to the user (Telegram)