arena-bridge 0.8.0 → 0.8.11

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 CHANGED
@@ -4,6 +4,100 @@ 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.8.11
8
+
9
+ ### Fixed
10
+ - Wave 0 closure: `GET /audit?limit=abc` now returns `400 invalid limit` in both Node and Python (was `500` in Python, silent `30` in Node); `PUT/DELETE /files` gate and audit already via `authorize()`+audit, `allowedChat` before inbox, `compare_digest`/`timingSafeEqual` verified.
11
+ - `S8-T` pipeline: trust path and normal path both audit after execution with `duration_ms`/`exit_code` via single pipeline in `Engine.call()` — no `ok` before execute.
12
+ - `B1` shell `killpg` + streaming cap with tail semantics: `clip()` now keeps last `cap` bytes (most recent output) instead of head; `start_process` session uses ring buffer — oldest chunks dropped when over `cap`, single oversized chunk truncated to tail.
13
+
14
+ ### Added
15
+ - `R5` async `202` — `GET /approvals/:id` now polls single approval (idempotent, no body) in Node (`direct.mjs`) and Python (`server.py`), alongside existing `GET /approvals` list; `POST /call`/`/exec`/`PUT/DELETE /files` return `202` with `approval_id` for pending.
16
+ - `B4/B8` atomic writes: `requestApproval`/`decide`/`timeout` now use `tmp+rename` (0600) in `src/approvals.mjs` and `arena_bridge/approvals.py` — no truncated JSON on parallel approve/poll/prune; `pruneApprovals`/`pruneArtifacts`/`pruneInbox` integrated in `cleanup`.
17
+
18
+ ## 0.8.10
19
+
20
+ ### Added
21
+ - macOS app now streams live events via `GET /v1/events` SSE — `AppModel.startEventStream()` keeps a long-lived `URLSession.bytes` connection with `Bearer` token, reconnects on drop, and triggers `refresh()` on `approvals`/`audit`/`heartbeat` events; falls back to 4s polling if SSE unavailable. Fixes AppModel double-timer freeze: `Bridge.run()` is async and polling is rate-limited.
22
+
23
+ ## 0.8.9
24
+
25
+ ### Added
26
+ - `doctor` now checks `audit.log` and `bridge.log` sizes — warns when over 10 MB / 5 MB with hint `arena-bridge cleanup`; `status` now includes `audit entries` and `bridge.log` size alongside `pending approvals`/`trust`/`publicUrl`.
27
+
28
+ ## 0.8.8
29
+
30
+ ### Changed
31
+ - Version is now single-source from `package.json`: `src/version.mjs` fallback synced to `0.8.8`, `pyproject.toml` and `arena_bridge/__init__.py` auto-synced, `Info.plist` `CFBundleShortVersionString` is set from `package.json` at `build.sh` time (was hardcoded `0.8.1`). CI `version-check` now passes for npm/py/macos.
32
+
33
+ ### Added
34
+ - Contract fixtures `test/fixtures/policy.json` for path policy (PROTECTED) — same inputs for Node and Python, covers `roots`, `protected`, dangling symlink to outside, and `audit_artifact` traversal (`basename`+`isInside`).
35
+
36
+ ## 0.8.7
37
+
38
+ ### Added
39
+ - `GET /v1/events` — Server-Sent Events stream for live approvals/audit/health deltas (Node + Python, bearer auth, heartbeat every 3s). `arena-bridge events [--json]` CLI consumes it.
40
+ - MCP protocol negotiation now supports both `2025-06-18` and `2026-07-28` — `initialize` returns the client's requested version when known, otherwise `2025-06-18`.
41
+
42
+ ## 0.8.6
43
+
44
+ ### Fixed
45
+ - Audit log now auto-rotates at 10 MB (keeps last 50% of entries) instead of growing unbounded; both Node and Python call `rotateAuditIfNeeded()` inside `audit()` with a cheap `stat` check.
46
+
47
+ ## 0.8.5
48
+
49
+ ### Added
50
+ - Engine suggests closest tool on `UNKNOWN_TOOL` (Levenshtein ≤3 `did you mean 'X'?`, else `available: ...`); fixed `Invalid array length`/`KeyError` on object tool names.
51
+ - `telegram pruneInbox(days)` / `prune_inbox(days)` — drops expired `inbox.jsonl` entries by `date` (Unix seconds) plus legacy `.json` files; `cleanup --days` now also purges telegram files.
52
+
53
+ ## 0.8.4
54
+
55
+ ### Added
56
+ - `doctor` now integrates `config validate` (missing roots/token/port) and `service health` checks; `--json` includes `publicUrl`/`node`/`checks` with stable `code`s.
57
+ - `GET /health` now returns `audit_count` and `log_size` (in addition to `pending_approvals`/`trust_active`/`has_public_url`/`device` optional via `exposeDeviceInHealth`).
58
+ - `trust` auto-prunes expired entries on `trustState()` via `pruneExpiredTrust()`.
59
+
60
+ ### Fixed
61
+ - `restart` now uses `launchctl kickstart -k gui/<uid>/ai.arena.bridge` instead of `bootout`/`bootstrap` for reliable restart.
62
+
63
+ ## 0.8.3
64
+
65
+ ### Added
66
+ - `--json` everywhere: `approvals`, `trust --history`, `audit`, `browser list`, `config validate/diff`, `doctor`, `status`, `logs`.
67
+ - `approvals prune --days 14` and `browser clean --days 30` — prune old approvals/profiles by `mtime`; `browser list --json` for automation.
68
+ - `audit --json` / `--from DATE` / `--to DATE` — date range filtering (ISO); `trust --history --json` (Node + Python).
69
+ - `feature-tree.md` and `AGENTS.md` docs updated.
70
+
71
+ ### Fixed
72
+ - ESM `require is not defined` in `cmdTrust --history` and `cmdRestart`/`service logs`/`browser clean`/`config edit` — replaced with `import fs/path/CONFIG_DIR/spawnSync`.
73
+
74
+ ## 0.8.2
75
+
76
+ ### Added
77
+ - `arena-bridge doctor --fix` — repairs `~/.arena-bridge` perms/dirs; `arena-bridge status [--json]` — runtime snapshot (config, url, trust, approvals, service).
78
+ - `arena-bridge logs [-n N] [--json]` — tail `bridge.log`; `arena-bridge cleanup [--days N]` — prune artifacts/approvals; `arena-bridge open` — open `publicUrl`.
79
+ - `GET /health` now includes `pending_approvals`, `trust_active`, `has_public_url`.
80
+
81
+ ### Fixed
82
+ - `audit --tool`, `--since`, `--from/--to`, `trust --extend`, `config validate|diff`, `service logs` — new filters and validators for DX/ops.
83
+
84
+
85
+ ## 0.8.1
86
+
87
+ ### Fixed
88
+ - Browser sessions no longer die after a short idle period: the WebSocket handshake timeout
89
+ is cleared once the DevTools connection is up (it used to destroy the socket after 10 s
90
+ without traffic), TCP keepalive and WebSocket pings keep the connection alive, and the
91
+ Python read loop treats an idle-socket timeout as "keep waiting" instead of closing.
92
+ - If Chrome still drops a DevTools socket, the browser session now survives: the manager
93
+ reconnects in the background (Node) or lazily on the next call (Python), re-attaches all
94
+ tabs and keeps the same `session_id`, tab ids and observations.
95
+
96
+ ### Added
97
+ - `chrome_activate`: make a tab active inside its Chrome window without moving the user's
98
+ cursor or stealing OS focus (background tabs may pause rendering, so activating the tab
99
+ you are about to work with makes interactions more reliable).
100
+
7
101
  ## 0.8.0
8
102
 
9
103
  ### Added
package/README.md CHANGED
@@ -487,8 +487,13 @@ arena-bridge audit -n 50 # что происходило
487
487
  | `trust` | окно доверия (`--for`, `--tools`, `--paths`, `--off`, `--status`) |
488
488
  | `approvals` / `approve <id>` | ожидающие подтверждения и ответ на них (`--deny`) |
489
489
  | `audit [-n N]` | журнал действий |
490
- | `doctor` | проверка установки, токенов, путей, Peekaboo, Chrome |
491
- | `url` | текущий публичный URL |
490
+ | `logs [-n N] [--json]` | `bridge.log` (структурные логи, 5MB rotation) |
491
+ | `config get/set/edit/list` | управление `config.json` (`get <key>`, `set <key> <val>`, `--json`) |
492
+ | `cleanup [--days N]` | удалить старые артефакты + approvals (по умолчанию 14д) |
493
+ | `doctor [--fix] [--json]` | проверка установки, токенов, путей, Peekaboo, Chrome (`--fix` чинит dirs/perms) |
494
+ | `status [--json]` | рантайм-снапшот: config, url, trust, pending, port, service |
495
+ | `url` / `open` | текущий публичный URL (open — открыть в браузере) |
496
+ | `completion bash|zsh|fish` | shell completion для bash/zsh/fish |
492
497
  | `version` | установленная и последняя версии |
493
498
  | `update` | обновить пакет с npm (`--check` — только проверить) |
494
499
  | `service` | macOS-фоновый сервис: `install` / `uninstall` / `status` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "arena-bridge",
3
- "version": "0.8.0",
3
+ "version": "0.8.11",
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": {
@@ -19,9 +19,9 @@
19
19
  "node": ">=18"
20
20
  },
21
21
  "scripts": {
22
- "test": "node --test test/approvals.test.mjs && node test/smoke.mjs && node test/browser.test.mjs && node test/mac.test.mjs && node test/service.test.mjs",
23
- "test:node": "node --test test/approvals.test.mjs && node test/smoke.mjs && node test/browser.test.mjs && node test/mac.test.mjs && node test/service.test.mjs",
24
- "test:python": "python3 test/test_approvals.py && python3 test/test_bridge.py && python3 test/test_browser.py && python3 test/test_mac.py && python3 test/test_service.py",
22
+ "test": "node --test test/approvals.test.mjs && node --test test/telegram.test.mjs && node test/smoke.mjs && node test/browser.test.mjs && node test/mac.test.mjs && node test/service.test.mjs",
23
+ "test:node": "node --test test/approvals.test.mjs && node --test test/telegram.test.mjs && node test/smoke.mjs && node test/browser.test.mjs && node test/mac.test.mjs && node test/service.test.mjs",
24
+ "test:python": "python3 test/test_approvals.py && python3 test/test_bridge.py && python3 test/test_browser.py && python3 test/test_mac.py && python3 test/test_service.py && python3 test/test_telegram.py",
25
25
  "pack:check": "npm pack --dry-run"
26
26
  },
27
27
  "repository": {
package/src/approvals.mjs CHANGED
@@ -76,10 +76,19 @@ export function settle(id, decision, by = 'cli', { trustSec = 0 } = {}) {
76
76
  }
77
77
 
78
78
  function redact(args) {
79
- const clone = { ...args };
80
- for (const k of Object.keys(clone)) {
81
- if (/token|secret|password|key/i.test(k)) clone[k] = '***';
79
+ function scrub(v) {
80
+ if (Array.isArray(v)) return v.map(scrub);
81
+ if (v && typeof v === 'object') {
82
+ const out = {};
83
+ for (const [k, val] of Object.entries(v)) {
84
+ if (/token|secret|password|authorization/i.test(k)) out[k] = '***';
85
+ else out[k] = scrub(val);
86
+ }
87
+ return out;
88
+ }
89
+ return v;
82
90
  }
91
+ const clone = scrub({ ...args });
83
92
  if (typeof clone.command === 'string' && clone.command.length > 4000) {
84
93
  clone.command = clone.command.slice(0, 4000) + '…';
85
94
  }
@@ -91,6 +100,25 @@ function redact(args) {
91
100
  * The request lives in a file so that the `arena-bridge approve` CLI (a separate
92
101
  * process) can pick it up.
93
102
  */
103
+ export function pruneApprovals(days = 14) {
104
+ if (!fs.existsSync(APPROVALS_DIR)) return { removed: 0 };
105
+ const cutoff = Date.now() - days * 86400000;
106
+ let removed = 0;
107
+ for (const f of fs.readdirSync(APPROVALS_DIR)) {
108
+ if (!f.endsWith('.json')) continue;
109
+ const file = path.join(APPROVALS_DIR, f);
110
+ try {
111
+ const rec = JSON.parse(fs.readFileSync(file, 'utf8'));
112
+ const ts = rec.decidedAt || rec.createdAt || 0;
113
+ if (rec.status !== 'pending' && ts && ts < cutoff) {
114
+ fs.unlinkSync(file);
115
+ removed++;
116
+ }
117
+ } catch {}
118
+ }
119
+ return { removed };
120
+ }
121
+
94
122
  export async function requestApproval(tool, args, cfg) {
95
123
  ensureDirs();
96
124
  const id = crypto.randomUUID();
@@ -105,7 +133,12 @@ export async function requestApproval(tool, args, cfg) {
105
133
  decidedAt: null,
106
134
  decidedBy: null,
107
135
  };
108
- fs.writeFileSync(fileOf(id), JSON.stringify(rec, null, 2), { mode: 0o600 });
136
+ // B8 atomic
137
+ {
138
+ const fp = fileOf(id); const tmp = fp + '.tmp';
139
+ fs.writeFileSync(tmp, JSON.stringify(rec, null, 2), { mode: 0o600 });
140
+ fs.renameSync(tmp, fp);
141
+ }
109
142
 
110
143
  // tell the user about it right away, so a pending request is not a dead end
111
144
  if (cfg.telegram?.enabled && cfg.telegram?.botToken) {
@@ -140,7 +173,7 @@ export async function requestApproval(tool, args, cfg) {
140
173
  timedOut.status = 'timeout';
141
174
  timedOut.decidedAt = Date.now();
142
175
  timedOut.decidedBy = 'system';
143
- fs.writeFileSync(fileOf(id), JSON.stringify(timedOut, null, 2), { mode: 0o600 });
176
+ { const fp=fileOf(id); const tmp=fp+'.tmp'; fs.writeFileSync(tmp, JSON.stringify(timedOut, null, 2), {mode:0o600}); fs.renameSync(tmp, fp); }
144
177
  }
145
178
  return { approved: timedOut.status === 'approved', rec: timedOut };
146
179
  }
package/src/audit.mjs CHANGED
@@ -39,7 +39,30 @@ export function audit(entry) {
39
39
  try {
40
40
  const dir = configDir();
41
41
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
42
- const rec = { ts: new Date().toISOString(), ...scrub(entry) };
42
+ // auto-rotate if over 10 MB (cheap stat, keeps log bounded)
43
+ try { const st = fs.statSync(auditPath()); if (st.size > 10*1024*1024) rotateAuditIfNeeded(); } catch {}
44
+ // R2 fix: don't store huge bodies in audit log — store size instead
45
+ function trunc(v, depth=0) {
46
+ if (depth > 6) return '[max depth]';
47
+ if (typeof v === 'string' && v.length > 4000) {
48
+ return `[${v.length} chars truncated]`;
49
+ }
50
+ if (v && typeof v === 'object') {
51
+ if (Array.isArray(v)) return v.map(x => trunc(x, depth+1));
52
+ const out = {};
53
+ for (const [k, val] of Object.entries(v)) {
54
+ if ((k === 'content' || k === 'data_base64' || k === 'data' || k === 'text') && typeof val === 'string' && val.length > 1000) {
55
+ out[k] = `[${val.length} chars truncated]`;
56
+ out[k + '_bytes'] = Buffer.byteLength(val);
57
+ } else {
58
+ out[k] = trunc(val, depth+1);
59
+ }
60
+ }
61
+ return out;
62
+ }
63
+ return v;
64
+ }
65
+ const rec = { ts: new Date().toISOString(), ...trunc(scrub(entry)) };
43
66
  fs.appendFileSync(auditPath(), JSON.stringify(rec) + '\n', { mode: 0o600 });
44
67
  } catch {
45
68
  /* auditing must never break the request */
@@ -49,16 +72,56 @@ export function audit(entry) {
49
72
  export function tailAudit(n = 50) {
50
73
  const file = auditPath();
51
74
  if (!fs.existsSync(file)) return [];
52
- const lines = fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean);
53
- return lines
54
- .slice(-n)
55
- .map((l) => {
56
- try {
57
- return JSON.parse(l);
58
- } catch {
59
- return { raw: l };
60
- }
61
- });
75
+ // R6 fix: read from end, not whole file, to handle large audit.log
76
+ try {
77
+ const stat = fs.statSync(file);
78
+ // if file small (<1MB), use simple path
79
+ if (stat.size < 1024*1024) {
80
+ const lines = fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean);
81
+ return lines.slice(-n).map((l) => { try { return JSON.parse(l); } catch { return { raw: l }; } });
82
+ }
83
+ // For large files, read last 512KB and get needed lines (reverse-read approximation)
84
+ const fd = fs.openSync(file, 'r');
85
+ const chunkSize = 512*1024;
86
+ const start = Math.max(0, stat.size - chunkSize);
87
+ const buf = Buffer.alloc(stat.size - start);
88
+ fs.readSync(fd, buf, 0, buf.length, start);
89
+ fs.closeSync(fd);
90
+ const lines = buf.toString('utf8').trim().split('\n').filter(Boolean);
91
+ // If we didn't get enough due to truncation, fallback to reading more
92
+ if (lines.length < n && start > 0) {
93
+ const moreStart = Math.max(0, stat.size - chunkSize*4);
94
+ const buf2 = Buffer.alloc(stat.size - moreStart);
95
+ const fd2 = fs.openSync(file, 'r');
96
+ fs.readSync(fd2, buf2, 0, buf2.length, moreStart);
97
+ fs.closeSync(fd2);
98
+ const lines2 = buf2.toString('utf8').trim().split('\n').filter(Boolean);
99
+ return lines2.slice(-n).map((l) => { try { return JSON.parse(l); } catch { return { raw: l }; } });
100
+ }
101
+ return lines.slice(-n).map((l) => { try { return JSON.parse(l); } catch { return { raw: l }; } });
102
+ } catch {
103
+ // fallback to old method
104
+ try {
105
+ const lines = fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean);
106
+ return lines.slice(-n).map((l) => { try { return JSON.parse(l); } catch { return { raw: l }; } });
107
+ } catch { return []; }
108
+ }
109
+ }
110
+
111
+ export function rotateAuditIfNeeded(maxBytes = 10*1024*1024) {
112
+ const file = auditPath();
113
+ if (!fs.existsSync(file)) return;
114
+ try {
115
+ const stat = fs.statSync(file);
116
+ if (stat.size > maxBytes) {
117
+ const lines = fs.readFileSync(file, 'utf8').trim().split('\n').filter(Boolean);
118
+ // keep last 50% of lines
119
+ const keep = lines.slice(Math.floor(lines.length/2));
120
+ const tmp = file + '.tmp';
121
+ fs.writeFileSync(tmp, keep.join('\n') + '\n', { mode: 0o600 });
122
+ fs.renameSync(tmp, file);
123
+ }
124
+ } catch {}
62
125
  }
63
126
 
64
127
  /* ------------------------------------------------------------------ *
@@ -84,9 +147,14 @@ export function saveArtifact(entryId, kind, name, data, meta = {}) {
84
147
 
85
148
  export function readArtifact(entryId, name) {
86
149
  try {
87
- const file = path.join(auditDir(), String(entryId), path.basename(String(name)));
88
- if (!fs.existsSync(file)) return null;
89
- return { file, data: fs.readFileSync(file) };
150
+ const base = path.resolve(auditDir());
151
+ // entryId and name are treated as single path components (no slashes, no traversal)
152
+ const target = path.resolve(path.join(base, path.basename(String(entryId)), path.basename(String(name))));
153
+ // ensure target stays inside audit dir
154
+ const rel = path.relative(base, target);
155
+ if (rel.startsWith('..') || path.isAbsolute(rel)) return null;
156
+ if (!fs.existsSync(target)) return null;
157
+ return { file: target, data: fs.readFileSync(target) };
90
158
  } catch {
91
159
  return null;
92
160
  }
package/src/browser.mjs CHANGED
@@ -175,6 +175,7 @@ export class BrowserManager {
175
175
  headless: s.headless,
176
176
  port: s.port,
177
177
  profile: s.profile,
178
+ disconnected: !!s.disconnected,
178
179
  tabs: [...s.tabs.values()].map((t) => ({ tab_id: t.targetId, title: t.title, url: t.url })),
179
180
  created_at: s.createdAt,
180
181
  }));
@@ -215,14 +216,90 @@ export class BrowserManager {
215
216
  tabs: new Map(),
216
217
  observe: new Map(),
217
218
  createdAt: Date.now(),
219
+ disconnected: false,
220
+ terminated: false,
221
+ reconnecting: false,
222
+ reconnects: 0,
218
223
  };
224
+ // H1/R6: limit Chrome sessions to 10, clean oldest and TTL 24h
225
+ if (this.sessions.size >= 10) {
226
+ let oldest = null;
227
+ for (const s of this.sessions.values()) {
228
+ if (!oldest || (s.startedAt || 0) < (oldest.startedAt || 0)) oldest = s;
229
+ }
230
+ if (oldest) {
231
+ try { oldest.proc?.kill(); } catch {}
232
+ this.sessions.delete(oldest.id || oldest.session_id);
233
+ }
234
+ }
235
+ // cleanup expired (>24h)
236
+ const now = Date.now();
237
+ for (const [k, s] of this.sessions) {
238
+ if (now - (s.startedAt || now) > 24*3600*1000) {
239
+ try { s.proc?.kill(); } catch {}
240
+ this.sessions.delete(k);
241
+ }
242
+ }
219
243
  this.sessions.set(id, session);
220
- cdp.on('close', () => {
221
- this.sessions.delete(id);
222
- });
244
+ this._wireCdp(session);
223
245
  return session;
224
246
  }
225
247
 
248
+ _wireCdp(session) {
249
+ session.cdp.on('close', () => {
250
+ if (session.terminated) {
251
+ this.sessions.delete(session.id);
252
+ return;
253
+ }
254
+ // Chrome may drop an idle DevTools socket while the browser itself is
255
+ // fine. Keep the session (tabs, observations) and reconnect in the
256
+ // background instead of failing every later call with a dead session.
257
+ session.disconnected = true;
258
+ void this._reconnect(session);
259
+ });
260
+ }
261
+
262
+ async _reconnect(session) {
263
+ if (session.reconnecting || session.terminated || !session.port) return;
264
+ session.reconnecting = true;
265
+ try {
266
+ for (let attempt = 0; attempt < 60 && !session.terminated; attempt++) {
267
+ await sleep(1000);
268
+ try {
269
+ const wsUrl = await browserWsUrl(session.port);
270
+ const cdp = new CDPClient(wsUrl);
271
+ await cdp.connect();
272
+ if (session.terminated) {
273
+ cdp.close();
274
+ return;
275
+ }
276
+ session.cdp = cdp;
277
+ this._wireCdp(session);
278
+ const { targetInfos } = await cdp.send('Target.getTargets');
279
+ const alive = new Set();
280
+ for (const t of targetInfos) {
281
+ if (t.type !== 'page') continue;
282
+ alive.add(t.targetId);
283
+ const tab = await this._attachTarget(session, t.targetId);
284
+ tab.title = t.title;
285
+ tab.url = t.url;
286
+ }
287
+ for (const targetId of [...session.tabs.keys()]) {
288
+ if (!alive.has(targetId)) session.tabs.delete(targetId);
289
+ }
290
+ session.disconnected = false;
291
+ session.reconnects++;
292
+ return;
293
+ } catch {
294
+ /* Chrome not reachable yet — keep retrying */
295
+ }
296
+ }
297
+ this.sessions.delete(session.id);
298
+ } finally {
299
+ session.reconnecting = false;
300
+ }
301
+ }
302
+
226
303
  async _collectTabs(session) {
227
304
  const { targetInfos } = await session.cdp.send('Target.getTargets');
228
305
  for (const t of targetInfos) {
@@ -376,6 +453,7 @@ export class BrowserManager {
376
453
  if (!s.managed) {
377
454
  return { ok: false, error: 'refusing to stop an attached (user) browser', session_id: s.id };
378
455
  }
456
+ s.terminated = true;
379
457
  try {
380
458
  s.cdp.close();
381
459
  } catch {
@@ -644,6 +722,24 @@ export class BrowserManager {
644
722
  };
645
723
  },
646
724
  },
725
+ {
726
+ name: 'chrome_activate',
727
+ description:
728
+ 'Make a tab the active one inside its Chrome window (Target.activateTarget). This does NOT move the ' +
729
+ "user's mouse cursor and does not steal OS focus — the window is not raised; only the selected tab " +
730
+ 'changes. Some pages pause timers/rendering in background tabs, so activating the tab you are about ' +
731
+ 'to work with makes interactions more reliable.',
732
+ approval: true,
733
+ approvalFor: requiresApproval,
734
+ schema: S({ session_id: { type: 'string' }, tab_id: { type: 'string' } }, []),
735
+ required: [],
736
+ handler: async (args, ctx) => {
737
+ const session = needSession(args, ctx);
738
+ const tab = await this._tab(session, args.tab_id);
739
+ await session.cdp.send('Target.activateTarget', { targetId: tab.targetId });
740
+ return { ok: true, session_id: session.id, tab_id: tab.targetId };
741
+ },
742
+ },
647
743
  {
648
744
  name: 'chrome_open',
649
745
  description: 'Open a URL in the browser (new tab by default).',