shellway 0.8.7 → 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.
- package/package.json +2 -2
- package/shellway.js +137 -28
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "shellway",
|
|
3
|
-
"version": "0.8.
|
|
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.
|
|
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.
|
|
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
|
-
|
|
860
|
-
|
|
861
|
-
|
|
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) {
|
|
@@ -1392,15 +1408,73 @@ async function afterAction(s, ms = 900) {
|
|
|
1392
1408
|
const r = await evalJs(s, '({ title: document.title, url: location.href })');
|
|
1393
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).`;
|
|
1394
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)}`;
|
|
1395
1467
|
const browserHandlers = {
|
|
1396
|
-
async browser_open({ url, new_tab }) {
|
|
1468
|
+
async browser_open({ url, new_tab, label }) {
|
|
1397
1469
|
const href = browserUrl(url);
|
|
1470
|
+
const lb = label !== undefined ? cleanLabel(label) : '';
|
|
1398
1471
|
const started = await ensureBrowser();
|
|
1399
1472
|
if (new_tab) { const t = await cdpJson(`/json/new?${encodeURI(href)}`); activeTarget = t.id; }
|
|
1400
|
-
return withPage(async (s) => {
|
|
1473
|
+
return withPage(async (s, t) => {
|
|
1401
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);
|
|
1402
1476
|
const r = await evalJs(s, SNAPSHOT_JS(6000));
|
|
1403
|
-
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`);
|
|
1404
1478
|
});
|
|
1405
1479
|
},
|
|
1406
1480
|
async browser_read({ max_chars, all_items }) {
|
|
@@ -1416,15 +1490,20 @@ const browserHandlers = {
|
|
|
1416
1490
|
let vy = pyPage - vp.sy;
|
|
1417
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')); }
|
|
1418
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);
|
|
1419
1494
|
await mouseClick(s, px, vy, double ? 2 : 1);
|
|
1420
|
-
|
|
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')}`;
|
|
1421
1497
|
});
|
|
1422
1498
|
}
|
|
1423
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');
|
|
1424
1500
|
return withPage(async (s) => {
|
|
1425
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);
|
|
1426
1504
|
await mouseClick(s, p.x, p.y, double ? 2 : 1);
|
|
1427
|
-
|
|
1505
|
+
const page = await afterAction(s);
|
|
1506
|
+
return `Clicked ${n !== null ? `[${ref}]` : `"${t}"`}.\n${page}\n${proofText(before, await pageState(s, n), 'click')}`;
|
|
1428
1507
|
});
|
|
1429
1508
|
},
|
|
1430
1509
|
async browser_type({ ref, text: t, clear, submit }) {
|
|
@@ -1436,13 +1515,15 @@ const browserHandlers = {
|
|
|
1436
1515
|
const p = await refPoint(s, ref);
|
|
1437
1516
|
// 0.7.4: a drop-down list (<select>): choose the option whose text or value matches.
|
|
1438
1517
|
if (p.tag === 'select') {
|
|
1518
|
+
const before = await proofBefore(s, n);
|
|
1439
1519
|
const r = await evalJs(s, `(() => { ${DEEP_JS} const e = __ref(${n}); if (!e) return null; const want = ${JSON.stringify(t.trim().toLowerCase())};
|
|
1440
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));
|
|
1441
1521
|
if (!o) return { ok: false, opts: opts.slice(0, 30).map((o) => o.text.trim()) };
|
|
1442
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() }; })()`);
|
|
1443
1523
|
if (!r) throw new Error(`Item [${ref}] was not found: the page has changed. Call browser_read again for fresh numbers.`);
|
|
1444
1524
|
if (!r.ok) throw new Error(`No option "${t}" in [${ref}]. Options: ${r.opts.join(' | ')}`);
|
|
1445
|
-
|
|
1525
|
+
const page = await afterAction(s, 500);
|
|
1526
|
+
return `Chose "${r.chosen}" in [${ref}].\n${page}\n${proofText(before, await pageState(s, n), 'choice')}`;
|
|
1446
1527
|
}
|
|
1447
1528
|
// 0.7.4: a file field: text is the path of a file on this computer (same folder rules as read_file).
|
|
1448
1529
|
if (p.type === 'file') {
|
|
@@ -1455,6 +1536,7 @@ const browserHandlers = {
|
|
|
1455
1536
|
await s.send('DOM.setFileInputFiles', { files: full, objectId: h.result.objectId });
|
|
1456
1537
|
return `Attached ${full.length} file${full.length > 1 ? 's' : ''} to [${ref}]: ${full.map((f) => basename(f)).join(', ')}.\n${await afterAction(s, 500)}`;
|
|
1457
1538
|
}
|
|
1539
|
+
const before = await proofBefore(s, n);
|
|
1458
1540
|
await mouseClick(s, p.x, p.y);
|
|
1459
1541
|
if (clear !== false) {
|
|
1460
1542
|
await evalJs(s, `(() => { ${DEEP_JS} const e = __ref(${n}); if (!e) return; e.focus();
|
|
@@ -1474,13 +1556,17 @@ const browserHandlers = {
|
|
|
1474
1556
|
}
|
|
1475
1557
|
}
|
|
1476
1558
|
}
|
|
1477
|
-
if (submit) { await pressKeys(s, 'enter'); return `Typed ${t.length} characters into [${ref}] and pressed Enter.\n${await
|
|
1478
|
-
|
|
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}`;
|
|
1479
1565
|
});
|
|
1480
1566
|
},
|
|
1481
1567
|
async browser_press({ keys }) {
|
|
1482
1568
|
cdpKeyEvents(keys); // validate first
|
|
1483
|
-
return withPage(async (s) => { await pressKeys(s, keys); return `Pressed ${keys}.\n${await
|
|
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')}`; });
|
|
1484
1570
|
},
|
|
1485
1571
|
async browser_scroll({ direction, pages: n }) {
|
|
1486
1572
|
const k = Math.min(Math.max(Number(n) || 1, 1), 20) * (direction === 'up' ? -1 : 1);
|
|
@@ -1491,42 +1577,65 @@ const browserHandlers = {
|
|
|
1491
1577
|
});
|
|
1492
1578
|
},
|
|
1493
1579
|
async browser_screenshot({ full_page }) {
|
|
1494
|
-
return withPage(async (s) => {
|
|
1495
|
-
const
|
|
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
|
+
}
|
|
1496
1592
|
const scale = vp.w > MAX_SHOT_W ? MAX_SHOT_W / vp.w : 1;
|
|
1497
1593
|
const h = full_page ? Math.min(vp.H, 4000) : vp.h;
|
|
1498
1594
|
const y = full_page ? 0 : await evalJs(s, 'scrollY');
|
|
1499
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 } });
|
|
1500
1596
|
// Keep the image small enough for the AI apps (about 500 KB at most): lower quality first, then size.
|
|
1501
1597
|
let sc = scale;
|
|
1502
|
-
let r
|
|
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; }
|
|
1503
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); }
|
|
1504
1601
|
lastShot = { scale: sc, top: y }; // for browser_click with x, y
|
|
1505
1602
|
const info = await evalJs(s, '({ title: document.title, url: location.href })');
|
|
1506
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)' : ''}` };
|
|
1507
1604
|
});
|
|
1508
1605
|
},
|
|
1509
|
-
async browser_tabs({ action, index, url }) {
|
|
1606
|
+
async browser_tabs({ action, index, url, tab_id, label }) {
|
|
1510
1607
|
const a = action || 'list';
|
|
1608
|
+
const lb = label !== undefined && label !== null ? cleanLabel(label) : '';
|
|
1511
1609
|
await ensureBrowser();
|
|
1512
1610
|
if (a === 'new') {
|
|
1513
1611
|
const t = await cdpJson(`/json/new?${encodeURI(url ? browserUrl(url) : 'about:blank')}`); activeTarget = t.id;
|
|
1514
|
-
if (
|
|
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}`;
|
|
1515
1615
|
return withPage(async (s) => { await waitNav(s); const r = await evalJs(s, '({ title: document.title, url: location.href })');
|
|
1516
|
-
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}.`;
|
|
1517
1623
|
}
|
|
1518
1624
|
if (a === 'back' || a === 'forward' || a === 'reload') {
|
|
1519
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)}`; });
|
|
1520
1626
|
}
|
|
1521
|
-
const
|
|
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}".`;
|
|
1522
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.';
|
|
1523
|
-
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(
|
|
1524
|
-
if (a === 'list') return list.map(
|
|
1525
|
-
const t = list[(Number(index) | 0) - 1];
|
|
1526
|
-
if (!t) throw new Error(`No tab number ${index}. Use action "list" to see the tabs.`);
|
|
1527
|
-
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)}`; }
|
|
1528
|
-
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}.`; }
|
|
1529
|
-
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');
|
|
1530
1639
|
},
|
|
1531
1640
|
// 0.8.6 (beta): which browsers have the Shellway extension connected, and which one the browser tools use
|
|
1532
1641
|
async browser_browsers() {
|