shellway 0.8.6 → 0.8.8

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.
Files changed (2) hide show
  1. package/package.json +2 -2
  2. package/shellway.js +140 -29
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shellway",
3
- "version": "0.8.6",
3
+ "version": "0.8.8",
4
4
  "description": "Shellway agent: lets ChatGPT, Claude and Cursor work on this computer through the Shellway relay.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -29,5 +29,5 @@
29
29
  },
30
30
  "author": "Sandeep Kumar Saini",
31
31
  "license": "UNLICENSED",
32
- "shellwayStable": "0.8.5"
32
+ "shellwayStable": "0.8.7"
33
33
  }
package/shellway.js CHANGED
@@ -10,7 +10,7 @@ import { readFile, writeFile, appendFile, readdir, stat, lstat, mkdir, rename, c
10
10
  import { createServer as netServer, connect as netConnect } from 'node:net';
11
11
  import { randomBytes, timingSafeEqual, createHash } from 'node:crypto';
12
12
 
13
- const AGENT_VERSION = '0.8.6'; // keep equal to agent/package.json
13
+ const AGENT_VERSION = '0.8.8'; // keep equal to agent/package.json
14
14
  if (Number(process.versions.node.split('.')[0]) < 22) {
15
15
  console.error(`Shellway needs Node.js 22 or newer (you have ${process.versions.node}). Get it at https://nodejs.org`);
16
16
  process.exit(1);
@@ -856,10 +856,9 @@ const desktopHandlers = {
856
856
  async focus_window({ pid, title }) {
857
857
  if (platform() !== 'win32') notSupported();
858
858
  if (!pid && !title) throw new Error('pid or title is required (see list_windows)');
859
- const target = pid ? String(Number(pid) | 0) : `[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(title)}'))`;
860
- const out = await runPs(`$ok=(New-Object -ComObject WScript.Shell).AppActivate(${target})\nif ($ok) { 'focused' } else { 'not found' }`);
861
- if (out !== 'focused') throw new Error('Window not found. Use list_windows to see open windows.');
862
- return 'Window brought to the front.';
859
+ // 0.8.8 (Ruslan 28 Nov): a minimised window is restored first, a title matches any part of the window title, and when
860
+ // nothing matches the error lists the open windows so the AI can choose the right one.
861
+ return focusResult(await runPs(focusPs(pid ? Number(pid) | 0 : 0, pid ? '' : String(title))), pid, title);
863
862
  },
864
863
  async mouse_click({ x, y, button, double }) {
865
864
  if (platform() !== 'win32') notSupported();
@@ -884,6 +883,23 @@ const desktopHandlers = {
884
883
  return `Pressed ${keys}.`;
885
884
  },
886
885
  };
886
+ // 0.8.8: Windows calls to restore a minimised window and bring it to the front (same Add-Type pattern as mouse_click).
887
+ const WIN_API = `Add-Type -Name W -Namespace SwWin -MemberDefinition '[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr h,int c); [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h);'`;
888
+ function focusPs(pid, title) {
889
+ const find = pid
890
+ ? `$p=@(Get-Process -Id ${pid} -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 })[0]`
891
+ : "$all=@(Get-Process | Where-Object { $_.MainWindowTitle })\n$p=@($all | Where-Object { $_.MainWindowTitle -eq $t })[0]\nif (-not $p) { $p=@($all | Where-Object { $_.MainWindowTitle.ToLower().Contains($t.ToLower()) })[0] }";
892
+ return `[Console]::OutputEncoding=[Text.Encoding]::UTF8\n${WIN_API}\n$t=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(title || '')}'))\n${find}\n`
893
+ + "if ($p) { $h=$p.MainWindowHandle; $m=[SwWin.W]::IsIconic($h); if ($m) { [void][SwWin.W]::ShowWindowAsync($h,9); Start-Sleep -Milliseconds 250 }; [void](New-Object -ComObject WScript.Shell).AppActivate($p.Id); [void][SwWin.W]::SetForegroundWindow($h); 'FOCUSED|' + $m + '|' + $p.Id + '|' + $p.ProcessName + '|' + $p.MainWindowTitle }\n"
894
+ + "else { 'NOTFOUND'; Get-Process | Where-Object { $_.MainWindowTitle } | Sort-Object ProcessName | Select-Object -First 25 | ForEach-Object { '{0} {1} {2}' -f $_.Id, $_.ProcessName, $_.MainWindowTitle } }";
895
+ }
896
+ function focusResult(out, pid, title) {
897
+ const lines = String(out || '').split(/\r?\n/).map((l) => l.trimEnd());
898
+ const f = lines.find((l) => l.startsWith('FOCUSED|'));
899
+ if (f) { const [, min, id, app, ...tt] = f.split('|'); return `Window brought to the front: ${tt.join('|') || '(no title)'} (${app}, pid ${id})${/true/i.test(min) ? '. It was minimised and has been restored.' : '.'}`; }
900
+ const rest = lines.filter((l) => l && l !== 'NOTFOUND');
901
+ throw new Error(`No open window ${pid ? `with pid ${pid}` : `whose title contains "${title}"`}. ${rest.length ? `Open windows (pid app title):\n${rest.join('\n')}` : 'No windows are open (the screen may be locked).'}`);
902
+ }
887
903
  const DESKTOP_METHODS = new Set(Object.keys(desktopHandlers));
888
904
  const DESKTOP_CONTROL = new Set(['open_app', 'close_app', 'focus_window', 'mouse_click', 'type_text', 'press_keys']);
889
905
  function checkDesktop(method, params) {
@@ -1003,11 +1019,13 @@ const NATIVE_NAME = 'com.getshellway.agent';
1003
1019
  const EXT_IDS = [
1004
1020
  'cepfcfgajaghchkamfmnhgcelblihndk', // the unpacked extension (fixed by the key in its manifest)
1005
1021
  'jaebfnkgmaopbkikeigclembnhbdlldc', // 0.7.4: the Edge Add-ons store version (Partner Center CRX ID, 21 Nov 2026)
1022
+ 'kleaokcionmcpjbblalbhkleljimjjmc', // 0.8.7: the Chrome Web Store version (item ID, 27 Nov 2026)
1006
1023
  ];
1007
1024
  const EXT_OFF = 'The Shellway extension is not connected. On that computer: open Edge or Chrome, click the Shellway extension icon and turn it on. (First time: npx shellway@latest policy browser extension; on Edge install Shellway from the Edge Add-ons store: https://microsoftedge.microsoft.com/addons/detail/jaebfnkgmaopbkikeigclembnhbdlldc)';
1008
1025
  // 0.8.6 (27 Nov 2026, beta): one link per browser (e.g. Edge and Chrome at the same time). The browser tools use the
1009
1026
  // current one: the browser the AI chose with browser_use, otherwise the one that connected last (as before).
1010
1027
  const STORE_EDGE = 'jaebfnkgmaopbkikeigclembnhbdlldc';
1028
+ const STORE_CHROME = 'kleaokcionmcpjbblalbhkleljimjjmc'; // 0.8.7
1011
1029
  const NO_PENDING = new Map();
1012
1030
  const ext = { seq: 0, links: new Map(), cur: null, pinned: '',
1013
1031
  get sock() { return this.cur ? this.cur.sock : null; },
@@ -1018,7 +1036,7 @@ const browserLabel = (b) => ({ edge: 'Edge', chrome: 'Chrome', brave: 'Brave', o
1018
1036
  function extUse(L) { if (ext.cur !== L) { ext.cur = L; try { activeTarget = null; } catch {} } }
1019
1037
  function extAttach(sock, rest, hello = {}) {
1020
1038
  let name = String(hello.browser || '').toLowerCase().replace(/[^a-z0-9-]/g, '').slice(0, 20);
1021
- if (!name) name = String(hello.origin || '').includes(STORE_EDGE) ? 'edge' : 'browser';
1039
+ if (!name) { const o = String(hello.origin || ''); name = o.includes(STORE_EDGE) ? 'edge' : o.includes(STORE_CHROME) ? 'chrome' : 'browser'; }
1022
1040
  const old = ext.links.get(name);
1023
1041
  if (old && old.sock !== sock) { try { old.sock.destroy(); } catch {} }
1024
1042
  const L = { sock, browser: name, version: '', pending: new Map(), since: Date.now() };
@@ -1390,15 +1408,73 @@ async function afterAction(s, ms = 900) {
1390
1408
  const r = await evalJs(s, '({ title: document.title, url: location.href })');
1391
1409
  return `Page now: ${redactTitle(r.title, r.url) || '(no title)'} — ${redactUrl(r.url)}\nCall browser_read to see the page again (item numbers may have changed).`;
1392
1410
  }
1411
+ // 0.8.8 (Ruslan 28 Nov): an autonomous AI must know whether a click or key press actually did something. Before the action
1412
+ // Shellway notes the page (address, title, a counter of page changes, the item's own state); after it, it compares.
1413
+ const PROOF_JS = (n) => `(() => { ${DEEP_JS} try { if (!window.__swObs) { window.__swMut = 0; window.__swObs = new MutationObserver((m) => { window.__swMut += m.length; });
1414
+ window.__swObs.observe(document.documentElement || document, { subtree: true, childList: true, attributes: true, characterData: true }); } } catch {}
1415
+ if (!window.__swDoc) window.__swDoc = Math.random().toString(36).slice(2);
1416
+ let item = null; const e = ${n == null ? 'null' : `__ref(${Number(n) | 0})`};
1417
+ if (e) { const a = (k) => e.getAttribute(k); const pw = (e.getAttribute('type') || '').toLowerCase() === 'password';
1418
+ item = { checked: e.checked === undefined ? null : !!e.checked, value_len: e.value === undefined ? null : String(e.value).length, value_tail: e.value === undefined || pw ? null : String(e.value).slice(-40),
1419
+ expanded: a('aria-expanded'), pressed: a('aria-pressed'), selected: a('aria-selected'), disabled: !!e.disabled || a('aria-disabled') === 'true', open: e.open === undefined ? null : !!e.open,
1420
+ text: (e.innerText || '').replace(/\\s+/g, ' ').trim().slice(0, 80) }; }
1421
+ const f = document.activeElement; return { doc: window.__swDoc, url: location.href, title: document.title, mut: window.__swMut || 0, focus: f ? f.tagName + '#' + (f.getAttribute('data-sw-ref') || f.id || '') : '', ref: ${n == null ? 'false' : 'true'}, item }; })()`;
1422
+ async function pageState(s, n) { try { return await evalJs(s, PROOF_JS(n), 8000); } catch { return null; } }
1423
+ // Two readings 0.3 s apart: pages that change by themselves (clocks, animations) are flagged so their updates prove nothing.
1424
+ async function proofBefore(s, n) { const a = await pageState(s, n); await sleep(300); const b = await pageState(s, n); return b ? { ...b, noise: a && a.doc === b.doc ? Math.max(0, b.mut - a.mut) : 0 } : null; }
1425
+ function proofText(b, a, what) {
1426
+ if (!b || !a) return `Check: Shellway could not read the page before and after the ${what} (it may still be loading). Call browser_read to confirm the result.`;
1427
+ const ch = [];
1428
+ if (a.doc !== b.doc) ch.push('a new page loaded');
1429
+ if (a.url !== b.url) ch.push(`the address changed to ${redactUrl(a.url)}`);
1430
+ if (a.title !== b.title) ch.push(`the title changed to "${redactTitle(a.title, a.url) || ''}"`);
1431
+ if (b.ref && b.item && a.doc === b.doc) {
1432
+ if (!a.item) ch.push('the item is no longer on the page');
1433
+ else {
1434
+ for (const k of ['checked', 'expanded', 'pressed', 'selected', 'open', 'disabled']) if (b.item[k] !== a.item[k]) ch.push(`the item's ${k} state changed from ${b.item[k]} to ${a.item[k]}`);
1435
+ if (b.item.value_len !== a.item.value_len || b.item.value_tail !== a.item.value_tail) ch.push(`the field's value changed (now ${a.item.value_len} characters)`);
1436
+ if (b.item.text !== a.item.text) ch.push('the item\'s text changed');
1437
+ }
1438
+ }
1439
+ // a click always focuses what it clicked, so a focus move counts only for key presses (e.g. tab)
1440
+ if (what === 'key press' && a.doc === b.doc && a.focus !== b.focus) ch.push('the keyboard focus moved to another item');
1441
+ const upd = a.doc === b.doc ? Math.max(0, a.mut - b.mut) : 0;
1442
+ const noisy = b.noise > 0;
1443
+ if (upd > 0) ch.push(`${upd} update${upd > 1 ? 's' : ''} inside the page${noisy ? ` (the page also changes by itself: ${b.noise} in 0.3 s before the ${what}, so this alone proves nothing)` : ''}`);
1444
+ const real = ch.length > (upd > 0 && noisy ? 1 : 0);
1445
+ return real ? `Check: the ${what} had an effect: ${ch.join('; ')}.`
1446
+ : `Check: NO CHANGE DETECTED after the ${what}${upd > 0 ? ` (only ${ch.join('; ')})` : ''}: same page, same address and title${b.ref ? ', the item looks the same' : ''}. It may not have worked, or it changed something this check cannot see (a download, a canvas, another tab or window). Confirm with browser_read or browser_screenshot before relying on it.`;
1447
+ }
1448
+ const MINIMISED = 'The browser window is minimised or hidden, so the page has no size and cannot be captured (Shellway tried to restore it). Restore the browser window (focus_window with its title, or click it on the taskbar) and take the screenshot again.';
1449
+ // 0.8.8 (Ruslan 28 Nov): "Cannot take screenshot with 0 width" = a minimised browser window. On Windows, restore the
1450
+ // minimised window of that browser (the one whose title starts with the tab's title, or the only minimised one).
1451
+ async function restoreBrowserWindow(tabTitle) {
1452
+ if (platform() !== 'win32') return false;
1453
+ const procs = { edge: 'msedge', chrome: 'chrome', brave: 'brave', opera: 'opera' };
1454
+ const names = extMode() && ext.cur && procs[ext.cur.browser] ? [procs[ext.cur.browser]] : ['msedge', 'chrome', 'brave'];
1455
+ try {
1456
+ const out = await runPs(`${WIN_API}\n$t=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(String(tabTitle || '').slice(0, 60))}'))\n`
1457
+ + `$w=@(Get-Process -Name ${names.map((x) => `'${x}'`).join(',')} -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 -and [SwWin.W]::IsIconic($_.MainWindowHandle) })\n`
1458
+ + "$p=@($w | Where-Object { $t -and $_.MainWindowTitle.StartsWith($t) })[0]\nif (-not $p -and $w.Count -eq 1) { $p=$w[0] }\nif ($p) { [void][SwWin.W]::ShowWindowAsync($p.MainWindowHandle,9); 'RESTORED' } else { 'NONE' }");
1459
+ return /RESTORED/.test(out);
1460
+ } catch { return false; }
1461
+ }
1462
+ // 0.8.8 (Ruslan 28 Nov): tabs keep their own id (stable while the browser runs, unlike the list number) and an optional
1463
+ // label the AI gives them (e.g. the name of its run), so a long run can find and keep using its own tabs.
1464
+ const tabLabels = new Map();
1465
+ const cleanLabel = (l) => { const v = String(l ?? '').replace(/[\r\n\t]+/g, ' ').trim(); if (v.length > 40) throw new Error('label is too long (max 40 characters)'); return v; };
1466
+ const tabLine = (t, i) => `${i + 1}. ${t.id === activeTarget ? '(active) ' : ''}[tab_id ${t.id}${tabLabels.get(t.id) ? `, label "${tabLabels.get(t.id)}"` : ''}] ${redactTitle(t.title, t.url) || '(no title)'} — ${redactUrl(t.url)}`;
1393
1467
  const browserHandlers = {
1394
- async browser_open({ url, new_tab }) {
1468
+ async browser_open({ url, new_tab, label }) {
1395
1469
  const href = browserUrl(url);
1470
+ const lb = label !== undefined ? cleanLabel(label) : '';
1396
1471
  const started = await ensureBrowser();
1397
1472
  if (new_tab) { const t = await cdpJson(`/json/new?${encodeURI(href)}`); activeTarget = t.id; }
1398
- return withPage(async (s) => {
1473
+ return withPage(async (s, t) => {
1399
1474
  if (!new_tab) { await leaveIfAsked(s, () => s.send('Page.navigate', { url: href })); await waitLoad(s); } else await waitNav(s);
1475
+ if (lb) tabLabels.set(t.id, lb);
1400
1476
  const r = await evalJs(s, SNAPSHOT_JS(6000));
1401
- return snapshotText(r, started ? 'Opened the Shellway browser window on the computer (a separate profile; the user\'s own browser is not used).\n' : '');
1477
+ return snapshotText(r, (started ? 'Opened the Shellway browser window on the computer (a separate profile; the user\'s own browser is not used).\n' : '') + `Tab id: ${t.id}${tabLabels.get(t.id) ? ` (label "${tabLabels.get(t.id)}")` : ''}\n`);
1402
1478
  });
1403
1479
  },
1404
1480
  async browser_read({ max_chars, all_items }) {
@@ -1414,15 +1490,20 @@ const browserHandlers = {
1414
1490
  let vy = pyPage - vp.sy;
1415
1491
  if (vy < 0 || vy > vp.h) { await evalJs(s, `window.scrollTo(${vp.sx}, ${Math.max(0, Math.round(pyPage - vp.h / 2))})`); await sleep(300); vy = pyPage - (await evalJs(s, 'scrollY')); }
1416
1492
  if (px < 0 || px > vp.w) throw new Error(`x=${x} is outside the page (the screenshot is ${Math.round(vp.w * lastShot.scale)} px wide).`);
1493
+ const before = await proofBefore(s, null);
1417
1494
  await mouseClick(s, px, vy, double ? 2 : 1);
1418
- return `Clicked at x=${x}, y=${y} of the screenshot.\n${await afterAction(s)}`;
1495
+ const page = await afterAction(s);
1496
+ return `Clicked at x=${x}, y=${y} of the screenshot.\n${page}\n${proofText(before, await pageState(s, null), 'click')}`;
1419
1497
  });
1420
1498
  }
1421
1499
  if ((ref === undefined || ref === null || ref === '') && !t) throw new Error('ref (the [number] from browser_read), text, or x and y (pixels in the latest browser_screenshot) is required');
1422
1500
  return withPage(async (s) => {
1423
1501
  const p = await refPoint(s, ref, t);
1502
+ const n = ref !== undefined && ref !== null && ref !== '' ? Number(ref) | 0 : null;
1503
+ const before = await proofBefore(s, n);
1424
1504
  await mouseClick(s, p.x, p.y, double ? 2 : 1);
1425
- return `Clicked ${ref !== undefined && ref !== null && ref !== '' ? `[${ref}]` : `"${t}"`}.\n${await afterAction(s)}`;
1505
+ const page = await afterAction(s);
1506
+ return `Clicked ${n !== null ? `[${ref}]` : `"${t}"`}.\n${page}\n${proofText(before, await pageState(s, n), 'click')}`;
1426
1507
  });
1427
1508
  },
1428
1509
  async browser_type({ ref, text: t, clear, submit }) {
@@ -1434,13 +1515,15 @@ const browserHandlers = {
1434
1515
  const p = await refPoint(s, ref);
1435
1516
  // 0.7.4: a drop-down list (<select>): choose the option whose text or value matches.
1436
1517
  if (p.tag === 'select') {
1518
+ const before = await proofBefore(s, n);
1437
1519
  const r = await evalJs(s, `(() => { ${DEEP_JS} const e = __ref(${n}); if (!e) return null; const want = ${JSON.stringify(t.trim().toLowerCase())};
1438
1520
  const opts = [...e.options]; const o = opts.find((o) => o.text.trim().toLowerCase() === want || o.value.toLowerCase() === want) || opts.find((o) => o.text.trim().toLowerCase().includes(want));
1439
1521
  if (!o) return { ok: false, opts: opts.slice(0, 30).map((o) => o.text.trim()) };
1440
1522
  e.focus(); e.value = o.value; o.selected = true; e.dispatchEvent(new Event('input', { bubbles: true })); e.dispatchEvent(new Event('change', { bubbles: true })); return { ok: true, chosen: o.text.trim() }; })()`);
1441
1523
  if (!r) throw new Error(`Item [${ref}] was not found: the page has changed. Call browser_read again for fresh numbers.`);
1442
1524
  if (!r.ok) throw new Error(`No option "${t}" in [${ref}]. Options: ${r.opts.join(' | ')}`);
1443
- return `Chose "${r.chosen}" in [${ref}].\n${await afterAction(s, 500)}`;
1525
+ const page = await afterAction(s, 500);
1526
+ return `Chose "${r.chosen}" in [${ref}].\n${page}\n${proofText(before, await pageState(s, n), 'choice')}`;
1444
1527
  }
1445
1528
  // 0.7.4: a file field: text is the path of a file on this computer (same folder rules as read_file).
1446
1529
  if (p.type === 'file') {
@@ -1453,6 +1536,7 @@ const browserHandlers = {
1453
1536
  await s.send('DOM.setFileInputFiles', { files: full, objectId: h.result.objectId });
1454
1537
  return `Attached ${full.length} file${full.length > 1 ? 's' : ''} to [${ref}]: ${full.map((f) => basename(f)).join(', ')}.\n${await afterAction(s, 500)}`;
1455
1538
  }
1539
+ const before = await proofBefore(s, n);
1456
1540
  await mouseClick(s, p.x, p.y);
1457
1541
  if (clear !== false) {
1458
1542
  await evalJs(s, `(() => { ${DEEP_JS} const e = __ref(${n}); if (!e) return; e.focus();
@@ -1472,13 +1556,17 @@ const browserHandlers = {
1472
1556
  }
1473
1557
  }
1474
1558
  }
1475
- if (submit) { await pressKeys(s, 'enter'); return `Typed ${t.length} characters into [${ref}] and pressed Enter.\n${await afterAction(s)}`; }
1476
- return `Typed ${t.length} characters into [${ref}]${p.type === 'password' ? ' (password field)' : ''}.`;
1559
+ if (submit) { await pressKeys(s, 'enter'); const page = await afterAction(s); return `Typed ${t.length} characters into [${ref}] and pressed Enter.\n${page}\n${proofText(before, await pageState(s, n), 'typing and Enter')}`; }
1560
+ const after = await pageState(s, n);
1561
+ // 0.8.8: say plainly whether the field now holds the text (for a password field only its length is compared)
1562
+ const holds = after && after.item ? (after.item.value_tail !== null ? (t ? after.item.value_tail.endsWith(t.slice(-Math.min(t.length, 40))) : after.item.value_len === 0) : after.item.value_len !== null ? after.item.value_len >= t.length : null) : null;
1563
+ const fieldLine = holds === true ? `Check: the field now holds the typed text (${after.item.value_len} characters).` : holds === false ? `Check: the field does NOT hold the typed text (it has ${after.item.value_len} characters). The page may have rejected or changed it: check with browser_read.` : proofText(before, after, 'typing');
1564
+ return `Typed ${t.length} characters into [${ref}]${p.type === 'password' ? ' (password field)' : ''}.\n${fieldLine}`;
1477
1565
  });
1478
1566
  },
1479
1567
  async browser_press({ keys }) {
1480
1568
  cdpKeyEvents(keys); // validate first
1481
- return withPage(async (s) => { await pressKeys(s, keys); return `Pressed ${keys}.\n${await afterAction(s, 500)}`; });
1569
+ return withPage(async (s) => { const before = await proofBefore(s, null); await pressKeys(s, keys); const page = await afterAction(s, 500); return `Pressed ${keys}.\n${page}\n${proofText(before, await pageState(s, null), 'key press')}`; });
1482
1570
  },
1483
1571
  async browser_scroll({ direction, pages: n }) {
1484
1572
  const k = Math.min(Math.max(Number(n) || 1, 1), 20) * (direction === 'up' ? -1 : 1);
@@ -1489,42 +1577,65 @@ const browserHandlers = {
1489
1577
  });
1490
1578
  },
1491
1579
  async browser_screenshot({ full_page }) {
1492
- return withPage(async (s) => {
1493
- const vp = await evalJs(s, '({ w: innerWidth, h: innerHeight, H: document.documentElement.scrollHeight })');
1580
+ return withPage(async (s, t) => {
1581
+ const VP = '({ w: innerWidth, h: innerHeight, H: document.documentElement.scrollHeight })';
1582
+ let vp = await evalJs(s, VP);
1583
+ if (!(vp.w > 0 && vp.h > 0)) {
1584
+ // 0.8.8 (Ruslan 28 Nov): a minimised or hidden window has no size: bring the tab forward and restore the window once
1585
+ try { await cdpJson(`/json/activate/${t.id}`); } catch {}
1586
+ try { await s.send('Page.bringToFront', {}, 5000); } catch {}
1587
+ const restored = await restoreBrowserWindow(t.title);
1588
+ await sleep(restored ? 800 : 400);
1589
+ vp = await evalJs(s, VP);
1590
+ if (!(vp.w > 0 && vp.h > 0)) throw new Error(MINIMISED);
1591
+ }
1494
1592
  const scale = vp.w > MAX_SHOT_W ? MAX_SHOT_W / vp.w : 1;
1495
1593
  const h = full_page ? Math.min(vp.H, 4000) : vp.h;
1496
1594
  const y = full_page ? 0 : await evalJs(s, 'scrollY');
1497
1595
  const shot = (sc, q) => s.send('Page.captureScreenshot', { format: 'jpeg', quality: q, captureBeyondViewport: !!full_page, clip: { x: 0, y, width: vp.w, height: h, scale: sc } });
1498
1596
  // Keep the image small enough for the AI apps (about 500 KB at most): lower quality first, then size.
1499
1597
  let sc = scale;
1500
- let r = await shot(sc, full_page ? 45 : 60);
1598
+ let r;
1599
+ try { r = await shot(sc, full_page ? 45 : 60); } catch (e) { if (/0 width|0 height/i.test(String(e && e.message))) throw new Error(MINIMISED); throw e; }
1501
1600
  for (let k = 0.7; r.data.length > 700_000 && k > 0.2; k -= 0.2) { sc = scale * k; r = await shot(sc, 40); }
1502
1601
  lastShot = { scale: sc, top: y }; // for browser_click with x, y
1503
1602
  const info = await evalJs(s, '({ title: document.title, url: location.href })');
1504
1603
  return { type: 'image', mimeType: 'image/jpeg', data: r.data, note: `Screenshot of the Shellway browser tab: ${redactTitle(info.title, info.url) || '(no title)'} — ${redactUrl(info.url)}${full_page && vp.H > 4000 ? ' (top 4000 px of the page)' : ''}` };
1505
1604
  });
1506
1605
  },
1507
- async browser_tabs({ action, index, url }) {
1606
+ async browser_tabs({ action, index, url, tab_id, label }) {
1508
1607
  const a = action || 'list';
1608
+ const lb = label !== undefined && label !== null ? cleanLabel(label) : '';
1509
1609
  await ensureBrowser();
1510
1610
  if (a === 'new') {
1511
1611
  const t = await cdpJson(`/json/new?${encodeURI(url ? browserUrl(url) : 'about:blank')}`); activeTarget = t.id;
1512
- if (!url) return 'Opened a new empty tab. It is now the active tab.';
1612
+ if (lb) tabLabels.set(t.id, lb);
1613
+ const idLine = `Tab id: ${t.id}${lb ? ` (label "${lb}")` : ''}`;
1614
+ if (!url) return `Opened a new empty tab. It is now the active tab. ${idLine}`;
1513
1615
  return withPage(async (s) => { await waitNav(s); const r = await evalJs(s, '({ title: document.title, url: location.href })');
1514
- return `Opened a new tab, now active: ${redactTitle(r.title, r.url) || '(no title)'} — ${redactUrl(r.url)}\nCall browser_read to see the page.`; });
1616
+ return `Opened a new tab, now active: ${redactTitle(r.title, r.url) || '(no title)'} — ${redactUrl(r.url)}\n${idLine}\nCall browser_read to see the page.`; });
1617
+ }
1618
+ if (a === 'label') {
1619
+ const t0 = (await browserPages()).find((p) => p.id === String(tab_id ?? activeTarget));
1620
+ if (!t0) throw new Error('No such tab. Use action "list" to see the tabs and their tab_id.');
1621
+ if (lb) tabLabels.set(t0.id, lb); else tabLabels.delete(t0.id);
1622
+ return lb ? `Tab ${t0.id} now has the label "${lb}".` : `Label removed from tab ${t0.id}.`;
1515
1623
  }
1516
1624
  if (a === 'back' || a === 'forward' || a === 'reload') {
1517
1625
  return withPage(async (s) => { await leaveIfAsked(s, async () => { await evalJs(s, a === 'reload' ? 'location.reload()' : `history.${a}()`); await sleep(1600); }); return `${a === 'reload' ? 'Reloaded' : `Went ${a}`}.\n${await afterAction(s)}`; });
1518
1626
  }
1519
- const list = await browserPages();
1627
+ const all = await browserPages();
1628
+ for (const id of [...tabLabels.keys()]) if (!all.some((p) => p.id === id)) tabLabels.delete(id); // closed tabs
1629
+ const list = a === 'list' && lb ? all.filter((p) => tabLabels.get(p.id) === lb) : all;
1630
+ if (a === 'list' && lb && !list.length) return `No open tab has the label "${lb}".`;
1520
1631
  if (!list.length) return extMode() ? `No Shellway AI tabs are open${ext.version ? ` (Shellway extension v${ext.version})` : ''}. (In the user's own browser the AI sees only the tabs it opened, unless the owner allows "my other tabs" in the Shellway extension.) Open one with browser_open.` : 'No tabs are open.';
1521
- if (a === 'list' && extMode()) return `(The user's own browser${ext.links.size > 1 && ext.cur ? ` — ${browserLabel(ext.cur.browser)}, one of ${ext.links.size} connected (browser_select)` : ''}, Shellway extension${ext.version ? ' v' + ext.version : ''})\n` + list.map((t, i) => `${i + 1}. ${t.id === activeTarget ? '(active) ' : ''}${redactTitle(t.title, t.url) || '(no title)'} — ${redactUrl(t.url)}`).join('\n');
1522
- if (a === 'list') return list.map((t, i) => `${i + 1}. ${t.id === activeTarget ? '(active) ' : ''}${redactTitle(t.title, t.url) || '(no title)'} — ${redactUrl(t.url)}`).join('\n');
1523
- const t = list[(Number(index) | 0) - 1];
1524
- if (!t) throw new Error(`No tab number ${index}. Use action "list" to see the tabs.`);
1525
- if (a === 'switch') { activeTarget = t.id; try { await cdpJson(`/json/activate/${t.id}`); } catch {} return `Switched to tab ${index}: ${redactTitle(t.title, t.url) || '(no title)'} — ${redactUrl(t.url)}`; }
1526
- if (a === 'close') { if (readonly) throw new Error('This computer is in read-only mode'); await cdpJson(`/json/close/${t.id}`); if (activeTarget === t.id) activeTarget = null; return `Closed tab ${index}.`; }
1527
- throw new Error('action must be list, switch, new, close, back, forward or reload');
1632
+ if (a === 'list' && extMode()) return `(The user's own browser${ext.links.size > 1 && ext.cur ? ` — ${browserLabel(ext.cur.browser)}, one of ${ext.links.size} connected (browser_select)` : ''}, Shellway extension${ext.version ? ' v' + ext.version : ''})\n` + list.map(tabLine).join('\n');
1633
+ if (a === 'list') return list.map(tabLine).join('\n');
1634
+ const t = tab_id !== undefined && tab_id !== null && tab_id !== '' ? list.find((p) => p.id === String(tab_id)) : list[(Number(index) | 0) - 1];
1635
+ if (!t) throw new Error(tab_id !== undefined && tab_id !== null && tab_id !== '' ? `No open tab with tab_id ${tab_id} (it may have been closed). Use action "list" to see the tabs.` : `No tab number ${index}. Use action "list" to see the tabs.`);
1636
+ if (a === 'switch') { activeTarget = t.id; try { await cdpJson(`/json/activate/${t.id}`); } catch {} return `Switched to tab ${tab_id ?? index}: ${redactTitle(t.title, t.url) || '(no title)'} — ${redactUrl(t.url)}`; }
1637
+ if (a === 'close') { if (readonly) throw new Error('This computer is in read-only mode'); await cdpJson(`/json/close/${t.id}`); tabLabels.delete(t.id); if (activeTarget === t.id) activeTarget = null; return `Closed tab ${tab_id ?? index}.`; }
1638
+ throw new Error('action must be list, switch, new, close, label, back, forward or reload');
1528
1639
  },
1529
1640
  // 0.8.6 (beta): which browsers have the Shellway extension connected, and which one the browser tools use
1530
1641
  async browser_browsers() {