shellway 0.8.7 → 0.8.9
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 +163 -31
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "shellway",
|
|
3
|
-
"version": "0.8.
|
|
3
|
+
"version": "0.8.9",
|
|
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.9'; // 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,92 @@ 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, focus = false) {
|
|
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 (${focus ? '$true' : '$false'} -or [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] }\n"
|
|
1459
|
+
+ "if ($p) { $h=$p.MainWindowHandle; if ([SwWin.W]::IsIconic($h)) { [void][SwWin.W]::ShowWindowAsync($h,9); Start-Sleep -Milliseconds 250 }; "
|
|
1460
|
+
+ (focus ? "[void](New-Object -ComObject WScript.Shell).AppActivate($p.Id); [void][SwWin.W]::SetForegroundWindow($h); " : '')
|
|
1461
|
+
+ "'RESTORED' } else { 'NONE' }");
|
|
1462
|
+
return /RESTORED/.test(out);
|
|
1463
|
+
} catch { return false; }
|
|
1464
|
+
}
|
|
1465
|
+
// 0.8.9 (owner's live test 29 Nov): a screenshot of a page in a minimised browser window waited until it timed out.
|
|
1466
|
+
// Before a screenshot Shellway brings the tab forward and, on Windows, restores the window and brings it to the front.
|
|
1467
|
+
// Clicks, typing and keys still work in a minimised window (tested), so for them only the tab is brought forward inside
|
|
1468
|
+
// its window (full = false): Shellway does not pull the browser in front of what the user is doing.
|
|
1469
|
+
async function ensureVisible(s, t, full = true) {
|
|
1470
|
+
const vis = async () => { try { return await evalJs(s, 'document.visibilityState', 5000); } catch { return 'unknown'; } };
|
|
1471
|
+
if ((await vis()) !== 'hidden') return 'visible';
|
|
1472
|
+
try { await cdpJson(`/json/activate/${t.id}`); } catch {}
|
|
1473
|
+
try { await s.send('Page.bringToFront', {}, 5000); } catch {}
|
|
1474
|
+
await sleep(300);
|
|
1475
|
+
if ((await vis()) !== 'hidden' || !full) return 'shown';
|
|
1476
|
+
if (await restoreBrowserWindow(t.title, true)) { await sleep(700); if ((await vis()) !== 'hidden') return 'restored'; }
|
|
1477
|
+
return 'hidden';
|
|
1478
|
+
}
|
|
1479
|
+
const visNote = (v) => (v === 'hidden' ? '\nNote: the browser window stayed hidden (minimised or covered by another window), so the page may not react. Bring it to the front with focus_window and try again.'
|
|
1480
|
+
: v === 'restored' ? '\n(The browser window was minimised or covered; Shellway brought it to the front first.)' : '');
|
|
1481
|
+
// 0.8.8 (Ruslan 28 Nov): tabs keep their own id (stable while the browser runs, unlike the list number) and an optional
|
|
1482
|
+
// label the AI gives them (e.g. the name of its run), so a long run can find and keep using its own tabs.
|
|
1483
|
+
const tabLabels = new Map();
|
|
1484
|
+
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; };
|
|
1485
|
+
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
1486
|
const browserHandlers = {
|
|
1396
|
-
async browser_open({ url, new_tab }) {
|
|
1487
|
+
async browser_open({ url, new_tab, label }) {
|
|
1397
1488
|
const href = browserUrl(url);
|
|
1489
|
+
const lb = label !== undefined ? cleanLabel(label) : '';
|
|
1398
1490
|
const started = await ensureBrowser();
|
|
1399
1491
|
if (new_tab) { const t = await cdpJson(`/json/new?${encodeURI(href)}`); activeTarget = t.id; }
|
|
1400
|
-
return withPage(async (s) => {
|
|
1492
|
+
return withPage(async (s, t) => {
|
|
1401
1493
|
if (!new_tab) { await leaveIfAsked(s, () => s.send('Page.navigate', { url: href })); await waitLoad(s); } else await waitNav(s);
|
|
1494
|
+
if (lb) tabLabels.set(t.id, lb);
|
|
1402
1495
|
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' : '');
|
|
1496
|
+
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
1497
|
});
|
|
1405
1498
|
},
|
|
1406
1499
|
async browser_read({ max_chars, all_items }) {
|
|
@@ -1410,21 +1503,28 @@ const browserHandlers = {
|
|
|
1410
1503
|
async browser_click({ ref, text: t, double, x, y }) {
|
|
1411
1504
|
// 0.7.4: click a point of the latest browser_screenshot (for things that have no number, e.g. inside a canvas).
|
|
1412
1505
|
if ((ref === undefined || ref === null || ref === '') && !t && Number.isFinite(Number(x)) && Number.isFinite(Number(y)) && x !== null && y !== null) {
|
|
1413
|
-
return withPage(async (s) => {
|
|
1506
|
+
return withPage(async (s, tab) => {
|
|
1507
|
+
const shown = await ensureVisible(s, tab, false);
|
|
1414
1508
|
const vp = await evalJs(s, '({ sy: scrollY, sx: scrollX, h: innerHeight, w: innerWidth })');
|
|
1415
1509
|
const px = Number(x) / lastShot.scale, pyPage = Number(y) / lastShot.scale + lastShot.top;
|
|
1416
1510
|
let vy = pyPage - vp.sy;
|
|
1417
1511
|
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
1512
|
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).`);
|
|
1513
|
+
const before = await proofBefore(s, null);
|
|
1419
1514
|
await mouseClick(s, px, vy, double ? 2 : 1);
|
|
1420
|
-
|
|
1515
|
+
const page = await afterAction(s);
|
|
1516
|
+
return `Clicked at x=${x}, y=${y} of the screenshot.\n${page}\n${proofText(before, await pageState(s, null), 'click')}${visNote(shown)}`;
|
|
1421
1517
|
});
|
|
1422
1518
|
}
|
|
1423
1519
|
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
|
-
return withPage(async (s) => {
|
|
1520
|
+
return withPage(async (s, tab) => {
|
|
1521
|
+
const shown = await ensureVisible(s, tab, false);
|
|
1425
1522
|
const p = await refPoint(s, ref, t);
|
|
1523
|
+
const n = ref !== undefined && ref !== null && ref !== '' ? Number(ref) | 0 : null;
|
|
1524
|
+
const before = await proofBefore(s, n);
|
|
1426
1525
|
await mouseClick(s, p.x, p.y, double ? 2 : 1);
|
|
1427
|
-
|
|
1526
|
+
const page = await afterAction(s);
|
|
1527
|
+
return `Clicked ${n !== null ? `[${ref}]` : `"${t}"`}.\n${page}\n${proofText(before, await pageState(s, n), 'click')}${visNote(shown)}`;
|
|
1428
1528
|
});
|
|
1429
1529
|
},
|
|
1430
1530
|
async browser_type({ ref, text: t, clear, submit }) {
|
|
@@ -1432,17 +1532,20 @@ const browserHandlers = {
|
|
|
1432
1532
|
if (t.length > 10_000) throw new Error('text is too long (max 10,000 characters)');
|
|
1433
1533
|
if (ref === undefined || ref === null || ref === '') throw new Error('ref is required: the [number] of the field from browser_read');
|
|
1434
1534
|
const n = Number(ref) | 0;
|
|
1435
|
-
return withPage(async (s) => {
|
|
1535
|
+
return withPage(async (s, tab) => {
|
|
1536
|
+
const shown = await ensureVisible(s, tab, false);
|
|
1436
1537
|
const p = await refPoint(s, ref);
|
|
1437
1538
|
// 0.7.4: a drop-down list (<select>): choose the option whose text or value matches.
|
|
1438
1539
|
if (p.tag === 'select') {
|
|
1540
|
+
const before = await proofBefore(s, n);
|
|
1439
1541
|
const r = await evalJs(s, `(() => { ${DEEP_JS} const e = __ref(${n}); if (!e) return null; const want = ${JSON.stringify(t.trim().toLowerCase())};
|
|
1440
1542
|
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
1543
|
if (!o) return { ok: false, opts: opts.slice(0, 30).map((o) => o.text.trim()) };
|
|
1442
1544
|
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
1545
|
if (!r) throw new Error(`Item [${ref}] was not found: the page has changed. Call browser_read again for fresh numbers.`);
|
|
1444
1546
|
if (!r.ok) throw new Error(`No option "${t}" in [${ref}]. Options: ${r.opts.join(' | ')}`);
|
|
1445
|
-
|
|
1547
|
+
const page = await afterAction(s, 500);
|
|
1548
|
+
return `Chose "${r.chosen}" in [${ref}].\n${page}\n${proofText(before, await pageState(s, n), 'choice')}`;
|
|
1446
1549
|
}
|
|
1447
1550
|
// 0.7.4: a file field: text is the path of a file on this computer (same folder rules as read_file).
|
|
1448
1551
|
if (p.type === 'file') {
|
|
@@ -1455,6 +1558,7 @@ const browserHandlers = {
|
|
|
1455
1558
|
await s.send('DOM.setFileInputFiles', { files: full, objectId: h.result.objectId });
|
|
1456
1559
|
return `Attached ${full.length} file${full.length > 1 ? 's' : ''} to [${ref}]: ${full.map((f) => basename(f)).join(', ')}.\n${await afterAction(s, 500)}`;
|
|
1457
1560
|
}
|
|
1561
|
+
const before = await proofBefore(s, n);
|
|
1458
1562
|
await mouseClick(s, p.x, p.y);
|
|
1459
1563
|
if (clear !== false) {
|
|
1460
1564
|
await evalJs(s, `(() => { ${DEEP_JS} const e = __ref(${n}); if (!e) return; e.focus();
|
|
@@ -1474,13 +1578,17 @@ const browserHandlers = {
|
|
|
1474
1578
|
}
|
|
1475
1579
|
}
|
|
1476
1580
|
}
|
|
1477
|
-
if (submit) { await pressKeys(s, 'enter'); return `Typed ${t.length} characters into [${ref}] and pressed Enter.\n${await
|
|
1478
|
-
|
|
1581
|
+
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')}${visNote(shown)}`; }
|
|
1582
|
+
const after = await pageState(s, n);
|
|
1583
|
+
// 0.8.8: say plainly whether the field now holds the text (for a password field only its length is compared)
|
|
1584
|
+
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;
|
|
1585
|
+
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');
|
|
1586
|
+
return `Typed ${t.length} characters into [${ref}]${p.type === 'password' ? ' (password field)' : ''}.\n${fieldLine}${visNote(shown)}`;
|
|
1479
1587
|
});
|
|
1480
1588
|
},
|
|
1481
1589
|
async browser_press({ keys }) {
|
|
1482
1590
|
cdpKeyEvents(keys); // validate first
|
|
1483
|
-
return withPage(async (s) => { await pressKeys(s, keys); return `Pressed ${keys}.\n${await
|
|
1591
|
+
return withPage(async (s, tab) => { const shown = await ensureVisible(s, tab, false); 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')}${visNote(shown)}`; });
|
|
1484
1592
|
},
|
|
1485
1593
|
async browser_scroll({ direction, pages: n }) {
|
|
1486
1594
|
const k = Math.min(Math.max(Number(n) || 1, 1), 20) * (direction === 'up' ? -1 : 1);
|
|
@@ -1491,42 +1599,66 @@ const browserHandlers = {
|
|
|
1491
1599
|
});
|
|
1492
1600
|
},
|
|
1493
1601
|
async browser_screenshot({ full_page }) {
|
|
1494
|
-
return withPage(async (s) => {
|
|
1495
|
-
const
|
|
1602
|
+
return withPage(async (s, t) => {
|
|
1603
|
+
const VP = '({ w: innerWidth, h: innerHeight, H: document.documentElement.scrollHeight })';
|
|
1604
|
+
if ((await ensureVisible(s, t)) === 'hidden') throw new Error(MINIMISED);
|
|
1605
|
+
let vp = await evalJs(s, VP);
|
|
1606
|
+
if (!(vp.w > 0 && vp.h > 0)) {
|
|
1607
|
+
// 0.8.8 (Ruslan 28 Nov): a minimised or hidden window has no size: bring the tab forward and restore the window once
|
|
1608
|
+
try { await cdpJson(`/json/activate/${t.id}`); } catch {}
|
|
1609
|
+
try { await s.send('Page.bringToFront', {}, 5000); } catch {}
|
|
1610
|
+
const restored = await restoreBrowserWindow(t.title);
|
|
1611
|
+
await sleep(restored ? 800 : 400);
|
|
1612
|
+
vp = await evalJs(s, VP);
|
|
1613
|
+
if (!(vp.w > 0 && vp.h > 0)) throw new Error(MINIMISED);
|
|
1614
|
+
}
|
|
1496
1615
|
const scale = vp.w > MAX_SHOT_W ? MAX_SHOT_W / vp.w : 1;
|
|
1497
1616
|
const h = full_page ? Math.min(vp.H, 4000) : vp.h;
|
|
1498
1617
|
const y = full_page ? 0 : await evalJs(s, 'scrollY');
|
|
1499
1618
|
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
1619
|
// Keep the image small enough for the AI apps (about 500 KB at most): lower quality first, then size.
|
|
1501
1620
|
let sc = scale;
|
|
1502
|
-
let r
|
|
1621
|
+
let r;
|
|
1622
|
+
try { r = await shot(sc, full_page ? 45 : 60); } catch (e) { if (/0 width|0 height|did not answer|timed? ?out/i.test(String(e && e.message))) throw new Error(MINIMISED); throw e; }
|
|
1503
1623
|
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
1624
|
lastShot = { scale: sc, top: y }; // for browser_click with x, y
|
|
1505
1625
|
const info = await evalJs(s, '({ title: document.title, url: location.href })');
|
|
1506
1626
|
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
1627
|
});
|
|
1508
1628
|
},
|
|
1509
|
-
async browser_tabs({ action, index, url }) {
|
|
1629
|
+
async browser_tabs({ action, index, url, tab_id, label }) {
|
|
1510
1630
|
const a = action || 'list';
|
|
1631
|
+
const lb = label !== undefined && label !== null ? cleanLabel(label) : '';
|
|
1511
1632
|
await ensureBrowser();
|
|
1512
1633
|
if (a === 'new') {
|
|
1513
1634
|
const t = await cdpJson(`/json/new?${encodeURI(url ? browserUrl(url) : 'about:blank')}`); activeTarget = t.id;
|
|
1514
|
-
if (
|
|
1635
|
+
if (lb) tabLabels.set(t.id, lb);
|
|
1636
|
+
const idLine = `Tab id: ${t.id}${lb ? ` (label "${lb}")` : ''}`;
|
|
1637
|
+
if (!url) return `Opened a new empty tab. It is now the active tab. ${idLine}`;
|
|
1515
1638
|
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.`; });
|
|
1639
|
+
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.`; });
|
|
1640
|
+
}
|
|
1641
|
+
if (a === 'label') {
|
|
1642
|
+
const t0 = (await browserPages()).find((p) => p.id === String(tab_id ?? activeTarget));
|
|
1643
|
+
if (!t0) throw new Error('No such tab. Use action "list" to see the tabs and their tab_id.');
|
|
1644
|
+
if (lb) tabLabels.set(t0.id, lb); else tabLabels.delete(t0.id);
|
|
1645
|
+
return lb ? `Tab ${t0.id} now has the label "${lb}".` : `Label removed from tab ${t0.id}.`;
|
|
1517
1646
|
}
|
|
1518
1647
|
if (a === 'back' || a === 'forward' || a === 'reload') {
|
|
1519
1648
|
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
1649
|
}
|
|
1521
|
-
const
|
|
1650
|
+
const all = await browserPages();
|
|
1651
|
+
for (const id of [...tabLabels.keys()]) if (!all.some((p) => p.id === id)) tabLabels.delete(id); // closed tabs
|
|
1652
|
+
const list = a === 'list' && lb ? all.filter((p) => tabLabels.get(p.id) === lb) : all;
|
|
1653
|
+
if (a === 'list' && lb && !list.length) return `No open tab has the label "${lb}".`;
|
|
1522
1654
|
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');
|
|
1655
|
+
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');
|
|
1656
|
+
if (a === 'list') return list.map(tabLine).join('\n');
|
|
1657
|
+
const t = tab_id !== undefined && tab_id !== null && tab_id !== '' ? list.find((p) => p.id === String(tab_id)) : list[(Number(index) | 0) - 1];
|
|
1658
|
+
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.`);
|
|
1659
|
+
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)}`; }
|
|
1660
|
+
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}.`; }
|
|
1661
|
+
throw new Error('action must be list, switch, new, close, label, back, forward or reload');
|
|
1530
1662
|
},
|
|
1531
1663
|
// 0.8.6 (beta): which browsers have the Shellway extension connected, and which one the browser tools use
|
|
1532
1664
|
async browser_browsers() {
|