shellway 0.7.2 → 0.7.4
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/extension/background.js +10 -1
- package/extension/manifest.json +1 -1
- package/package.json +1 -1
- package/shellway.js +120 -28
package/extension/background.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Shellway browser extension (0.7.
|
|
1
|
+
// Shellway browser extension (0.7.4).
|
|
2
2
|
// The Shellway app on this computer (the agent) talks to this extension through Chrome/Edge "native messaging":
|
|
3
3
|
// the browser starts a small Shellway helper that is only allowed to talk to THIS extension. The AI never talks to the
|
|
4
4
|
// extension directly; every request comes from the agent, which already checks the owner's safety rules.
|
|
@@ -24,6 +24,8 @@ const DEFAULT_BLOCKED = [
|
|
|
24
24
|
const ALLOWED_CDP = new Set([
|
|
25
25
|
'Runtime.evaluate', 'Input.dispatchMouseEvent', 'Input.dispatchKeyEvent', 'Input.insertText',
|
|
26
26
|
'Page.navigate', 'Page.reload', 'Page.captureScreenshot', 'Page.getLayoutMetrics', 'Page.bringToFront',
|
|
27
|
+
'Page.enable', 'Page.handleJavaScriptDialog', // 0.7.4: answer a "Leave site?" question after the AI itself moved the page
|
|
28
|
+
'DOM.setFileInputFiles', // 0.7.4: attach a file the AI was asked to upload (the Shellway app checks the computer's folder rules first)
|
|
27
29
|
]);
|
|
28
30
|
const IDLE_DETACH_MS = 60_000;
|
|
29
31
|
|
|
@@ -53,6 +55,7 @@ function describe(method, params) {
|
|
|
53
55
|
if (method === 'Page.navigate') return 'Opened a page';
|
|
54
56
|
if (method === 'Page.reload') return 'Reloaded';
|
|
55
57
|
if (method === 'Page.captureScreenshot') return 'Took a screenshot';
|
|
58
|
+
if (method === 'DOM.setFileInputFiles') return 'Attached a file';
|
|
56
59
|
if (method === 'Input.dispatchMouseEvent' && params.type === 'mousePressed') return 'Clicked';
|
|
57
60
|
if (method === 'Input.insertText' || (method === 'Input.dispatchKeyEvent' && params.type !== 'keyUp')) return 'Typed / pressed keys';
|
|
58
61
|
return '';
|
|
@@ -95,6 +98,7 @@ async function onMessage(m) {
|
|
|
95
98
|
connected = true; agentVersion = m.version || ''; lastError = ''; badge();
|
|
96
99
|
// 0.7.2: the Shellway app refreshed this extension's folder (a newer version): reload once to use the new files.
|
|
97
100
|
const mine = chrome.runtime.getManifest().version;
|
|
101
|
+
if (port) port.postMessage({ type: 'ext', version: mine }); // 0.7.3: tell the Shellway app which version runs here
|
|
98
102
|
if (m.extVersion && m.extVersion !== mine) {
|
|
99
103
|
const { reloadedFor } = await chrome.storage.local.get({ reloadedFor: '' });
|
|
100
104
|
if (reloadedFor !== m.extVersion) { await chrome.storage.local.set({ reloadedFor: m.extVersion }); chrome.runtime.reload(); }
|
|
@@ -177,6 +181,11 @@ async function handle(op, a) {
|
|
|
177
181
|
if (!/^https?:\/\//i.test(String(params.url || ''))) throw new Error('Only http and https pages can be opened.');
|
|
178
182
|
if (isBlocked(params.url, blocked)) throw new Error(`Blocked: ${hostOf(params.url)} is on the Shellway extension's list of blocked sites.`);
|
|
179
183
|
}
|
|
184
|
+
if (method === 'DOM.setFileInputFiles') {
|
|
185
|
+
const f = params.files;
|
|
186
|
+
if (!Array.isArray(f) || !f.length || f.length > 10 || f.some((x) => typeof x !== 'string' || !x)) throw new Error('files must be 1 to 10 file paths');
|
|
187
|
+
if (!params.objectId) throw new Error('No file field was given.');
|
|
188
|
+
}
|
|
180
189
|
if (method === 'Page.captureScreenshot' && !tab.active) { await chrome.tabs.update(tab.id, { active: true }); await sleep(400); }
|
|
181
190
|
await ensureAttached(tab.id);
|
|
182
191
|
touchIdle();
|
package/extension/manifest.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"manifest_version": 3,
|
|
3
3
|
"name": "Shellway",
|
|
4
|
-
"version": "0.7.
|
|
4
|
+
"version": "0.7.4",
|
|
5
5
|
"description": "Lets your AI (ChatGPT, Claude) use this browser through the Shellway app on your computer. Off until you turn it on.",
|
|
6
6
|
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnZWALJr6dwkQu7eX3reFbtgMAErsCyODHKnwz97XMKpR9bAz4+irBlJ2KEXD6ERZFjuKYqNZ2HLe0eQp5y9fWscyWeTUXNTstsFaymsb5C0aRcpW/dXRl2Dy9vQ7y7+ATH4SCxcckncfmEXt4GFQ6TtyPsctuQfYez6o9MHmwGaKwpCPaWmqfYqomy0yjzMCbCg2b0aP2+hDmOhc0KARhGVnzlZBIBSybtkpAmzXfUxMJHDD5ly3g6ScCcR+3Zf7SKyCfLMGSkwYwiJvvS4sNCtBzwKdDdbEh865T7H5NCS8GOhSt0hxkPPxpbTlXrWXINDiSkF00/b7ZToBRTmK4QIDAQAB",
|
|
7
7
|
"minimum_chrome_version": "116",
|
package/package.json
CHANGED
package/shellway.js
CHANGED
|
@@ -9,7 +9,7 @@ import { readFile, writeFile, appendFile, readdir, stat, lstat, mkdir, rename, c
|
|
|
9
9
|
import { createServer as netServer, connect as netConnect } from 'node:net';
|
|
10
10
|
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
|
11
11
|
|
|
12
|
-
const AGENT_VERSION = '0.7.
|
|
12
|
+
const AGENT_VERSION = '0.7.4'; // keep equal to agent/package.json
|
|
13
13
|
if (Number(process.versions.node.split('.')[0]) < 22) {
|
|
14
14
|
console.error(`Shellway needs Node.js 22 or newer (you have ${process.versions.node}). Get it at https://nodejs.org`);
|
|
15
15
|
process.exit(1);
|
|
@@ -978,9 +978,12 @@ async function cdpSession(wsUrl) {
|
|
|
978
978
|
// a fixed list of allowed DevTools commands, the browser's "debugging" bar while it works (Cancel = turn off).
|
|
979
979
|
const EXT_BRIDGE = join(CONF_DIR, 'extension-bridge.json');
|
|
980
980
|
const NATIVE_NAME = 'com.getshellway.agent';
|
|
981
|
-
const EXT_IDS = [
|
|
981
|
+
const EXT_IDS = [
|
|
982
|
+
'cepfcfgajaghchkamfmnhgcelblihndk', // the unpacked extension (fixed by the key in its manifest)
|
|
983
|
+
'jaebfnkgmaopbkikeigclembnhbdlldc', // 0.7.4: the Edge Add-ons store version (Partner Center CRX ID, 21 Nov 2026)
|
|
984
|
+
];
|
|
982
985
|
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@beta policy browser extension, then load the extension as shown.)';
|
|
983
|
-
const ext = { sock: null, seq: 0, pending: new Map() };
|
|
986
|
+
const ext = { sock: null, seq: 0, pending: new Map(), version: '' };
|
|
984
987
|
const extMode = () => { const p = loadPolicy(); return !!p && p.browser === 'extension'; };
|
|
985
988
|
function extAttach(sock, rest) {
|
|
986
989
|
if (ext.sock && ext.sock !== sock) { try { ext.sock.destroy(); } catch {} }
|
|
@@ -991,6 +994,7 @@ function extAttach(sock, rest) {
|
|
|
991
994
|
while ((i = buf.indexOf('\n')) >= 0) {
|
|
992
995
|
const line = buf.slice(0, i); buf = buf.slice(i + 1);
|
|
993
996
|
let m; try { m = JSON.parse(line); } catch { continue; }
|
|
997
|
+
if (m && m.type === 'ext') { ext.version = String(m.version || '').slice(0, 20); continue; } // 0.7.3: version running in the browser
|
|
994
998
|
const p = m && m.id !== undefined && ext.pending.get(m.id);
|
|
995
999
|
if (!p) continue;
|
|
996
1000
|
ext.pending.delete(m.id); clearTimeout(p.timer);
|
|
@@ -1000,7 +1004,7 @@ function extAttach(sock, rest) {
|
|
|
1000
1004
|
sock.on('data', (d) => { buf += d.toString('utf8'); take(); });
|
|
1001
1005
|
const gone = () => {
|
|
1002
1006
|
if (ext.sock !== sock) return;
|
|
1003
|
-
ext.sock = null;
|
|
1007
|
+
ext.sock = null; ext.version = '';
|
|
1004
1008
|
for (const p of ext.pending.values()) { clearTimeout(p.timer); p.no(new Error('The browser extension disconnected (the browser was closed or Shellway was turned off there).')); }
|
|
1005
1009
|
ext.pending.clear();
|
|
1006
1010
|
};
|
|
@@ -1128,7 +1132,8 @@ function installExtensionHost() {
|
|
|
1128
1132
|
return { extDest: existsSync(extDest) ? extDest : null, agentFile };
|
|
1129
1133
|
}
|
|
1130
1134
|
const extConnected = () => !!ext.sock;
|
|
1131
|
-
|
|
1135
|
+
const extVersion = () => ext.version;
|
|
1136
|
+
export { nativeHostManifest, nativeHostTargets, extJson, extCall, startExtBridge, extConnected, extVersion, installExtensionHost, SNAPSHOT_JS };
|
|
1132
1137
|
const browserPages = async () => (await cdpJson('/json/list')).filter((t) => t.type === 'page' && !String(t.url).startsWith('devtools:'));
|
|
1133
1138
|
async function currentPage() {
|
|
1134
1139
|
await ensureBrowser();
|
|
@@ -1145,8 +1150,8 @@ async function withPage(fn) {
|
|
|
1145
1150
|
const s = await cdpSession(t.webSocketDebuggerUrl);
|
|
1146
1151
|
try { return await fn(s, t); } finally { s.close(); }
|
|
1147
1152
|
}
|
|
1148
|
-
async function evalJs(s, expression) {
|
|
1149
|
-
const r = await s.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
|
|
1153
|
+
async function evalJs(s, expression, ms) {
|
|
1154
|
+
const r = await s.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, ms);
|
|
1150
1155
|
if (r.exceptionDetails) throw new Error(`Page script error: ${String(r.exceptionDetails.exception?.description || r.exceptionDetails.text || '').slice(0, 200)}`);
|
|
1151
1156
|
return r.result ? r.result.value : undefined;
|
|
1152
1157
|
}
|
|
@@ -1159,26 +1164,44 @@ async function waitLoad(s, ms = 15_000) {
|
|
|
1159
1164
|
}
|
|
1160
1165
|
return false;
|
|
1161
1166
|
}
|
|
1167
|
+
// 0.7.4: pages built from web components (Microsoft Partner Center, many Google/Salesforce pages) keep their buttons and
|
|
1168
|
+
// fields inside "shadow roots", which document.querySelectorAll does not see. __all/__ref look inside every open one.
|
|
1169
|
+
const DEEP_JS = `const __all = (sel) => { const out = []; const walk = (root) => { for (const e of root.querySelectorAll(sel)) out.push(e);
|
|
1170
|
+
for (const h of root.querySelectorAll('*')) if (h.shadowRoot) walk(h.shadowRoot); }; walk(document); return out; };
|
|
1171
|
+
const __ref = (n) => __all('[data-sw-ref="' + n + '"]')[0] || null;`;
|
|
1172
|
+
const ITEM_SEL = 'a[href],button,input:not([type=hidden]),textarea,select,summary,[role=button],[role=link],[role=tab],[role=menuitem],[role=menuitemradio],[role=checkbox],[role=radio],[role=switch],[role=option],[role=combobox],[role=textbox],[contenteditable=""],[contenteditable=true]';
|
|
1162
1173
|
// Numbers every visible link, button and field ([n]) so browser_click / browser_type can use them. Password values are never read.
|
|
1163
1174
|
const SNAPSHOT_JS = (maxText, allItems = false) => `(() => {
|
|
1175
|
+
${DEEP_JS}
|
|
1164
1176
|
const vis = (e) => { const r = e.getBoundingClientRect(); if (r.width < 1 || r.height < 1) return false; const st = getComputedStyle(e); return st.visibility !== 'hidden' && st.display !== 'none'; };
|
|
1165
|
-
const sel = '
|
|
1166
|
-
|
|
1177
|
+
const sel = '${ITEM_SEL}';
|
|
1178
|
+
__all('[data-sw-ref]').forEach((e) => e.removeAttribute('data-sw-ref'));
|
|
1179
|
+
// A button inside a web component often has no text of its own (the text is the component's): use the component's.
|
|
1180
|
+
const hostLabel = (e) => { const h = e.getRootNode && e.getRootNode().host; return h ? (h.getAttribute('aria-label') || h.innerText || h.getAttribute('title') || '') : ''; };
|
|
1167
1181
|
// 0.7.2: every visible item gets a number (so any [n] can be clicked), but only the ones on or near the screen are
|
|
1168
1182
|
// listed (at most ITEM_CAP) unless all items are asked for: long pages sent 300 links and slowed the AI apps down.
|
|
1169
1183
|
const ITEM_CAP = ${allItems ? 300 : 80}, near = (e) => { const r = e.getBoundingClientRect(); return r.bottom > -innerHeight * 0.5 && r.top < innerHeight * 1.5; };
|
|
1170
1184
|
const items = []; let n = 0, skipped = 0;
|
|
1171
|
-
|
|
1185
|
+
const seen = new Set();
|
|
1186
|
+
for (const e of __all(sel)) {
|
|
1172
1187
|
if (n >= 300 || !vis(e)) continue;
|
|
1188
|
+
// a web component with role=button and the real <button> inside it: list only one of them
|
|
1189
|
+
const inner = e.shadowRoot && e.shadowRoot.querySelector('button,input,textarea,select,a[href]');
|
|
1190
|
+
if (inner && vis(inner)) continue;
|
|
1191
|
+
if (seen.has(e)) continue; seen.add(e);
|
|
1173
1192
|
const ref = ++n; e.setAttribute('data-sw-ref', String(ref));
|
|
1174
1193
|
if (${allItems ? 'false' : 'true'} && (!near(e) || items.length >= ITEM_CAP)) { skipped++; continue; }
|
|
1175
1194
|
const tag = e.tagName.toLowerCase(), type = (e.getAttribute('type') || '').toLowerCase();
|
|
1176
|
-
const label = (e.getAttribute('aria-label') || (tag === 'input' || tag === 'textarea' || tag === 'select' ? '' : e.innerText) || e.getAttribute('placeholder') || e.getAttribute('title') || e.getAttribute('name') || (tag === 'a' ? e.getAttribute('href') : '') || '').replace(/\\s+/g, ' ').trim().slice(0, 80);
|
|
1177
|
-
const
|
|
1195
|
+
const label = (e.getAttribute('aria-label') || (tag === 'input' || tag === 'textarea' || tag === 'select' ? '' : e.innerText) || e.getAttribute('placeholder') || e.getAttribute('title') || hostLabel(e) || e.getAttribute('name') || (tag === 'a' ? e.getAttribute('href') : '') || '').replace(/\\s+/g, ' ').trim().slice(0, 80);
|
|
1196
|
+
const role = e.getAttribute('role') || '';
|
|
1197
|
+
const kind = tag === 'a' ? 'link' : tag === 'input' ? 'input' + (type ? ':' + type : '') : (tag.includes('-') && role ? role : tag);
|
|
1178
1198
|
let val = '';
|
|
1179
1199
|
if ((tag === 'input' || tag === 'textarea') && type !== 'password' && e.value) val = ' value="' + String(e.value).slice(0, 40) + '"';
|
|
1180
1200
|
if (tag === 'select' && e.selectedOptions && e.selectedOptions[0]) val = ' selected="' + e.selectedOptions[0].text.slice(0, 40) + '"';
|
|
1181
1201
|
if (type === 'checkbox' || type === 'radio') val = e.checked ? ' checked' : ' unchecked';
|
|
1202
|
+
else if (/^(checkbox|radio|switch|menuitemradio)$/.test(role)) val = e.getAttribute('aria-checked') === 'true' ? ' checked' : ' unchecked';
|
|
1203
|
+
if (tag === 'select') val += ' options="' + [...e.options].slice(0, 12).map((o) => o.text.trim().slice(0, 30)).join(' | ').replace(/"/g, "'") + (e.options.length > 12 ? ' | …' : '') + '"';
|
|
1204
|
+
if (type === 'file') val = ' (to upload: browser_type with the file path on this computer)';
|
|
1182
1205
|
items.push('[' + ref + '] ' + kind + ' "' + label.replace(/"/g, "'") + '"' + val);
|
|
1183
1206
|
}
|
|
1184
1207
|
const text = (document.body ? document.body.innerText : '').replace(/[ \\t]+\\n/g, '\\n').replace(/\\n{3,}/g, '\\n\\n').trim();
|
|
@@ -1231,12 +1254,14 @@ function snapshotText(r, label = '') {
|
|
|
1231
1254
|
}
|
|
1232
1255
|
async function refPoint(s, ref, text) {
|
|
1233
1256
|
const pick = ref !== undefined && ref !== null && ref !== ''
|
|
1234
|
-
? `
|
|
1235
|
-
: `(() => { const want = ${JSON.stringify(String(text || '').toLowerCase())}; const sel = '
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1257
|
+
? `__ref(${Number(ref) | 0})`
|
|
1258
|
+
: `(() => { const want = ${JSON.stringify(String(text || '').toLowerCase())}; const sel = '${ITEM_SEL}';
|
|
1259
|
+
const hostLabel = (e) => { const h = e.getRootNode && e.getRootNode().host; return h ? (h.getAttribute('aria-label') || h.innerText || '') : ''; };
|
|
1260
|
+
let partial = null;
|
|
1261
|
+
for (const e of __all(sel)) { const r = e.getBoundingClientRect(); if (r.width < 1 || r.height < 1) continue;
|
|
1262
|
+
const l = (e.getAttribute('aria-label') || e.innerText || e.value || e.getAttribute('placeholder') || e.getAttribute('title') || hostLabel(e) || '').replace(/\\s+/g, ' ').trim().toLowerCase();
|
|
1263
|
+
if (l === want) return e; if (!partial && l && l.includes(want)) partial = e; } return partial; })()`;
|
|
1264
|
+
const r = await evalJs(s, `(() => { ${DEEP_JS} const e = ${pick}; if (!e) return null; e.scrollIntoView({ block: 'center', inline: 'center' }); const b = e.getBoundingClientRect();
|
|
1240
1265
|
const tag = e.tagName.toLowerCase(); return { x: b.left + b.width / 2, y: b.top + b.height / 2, tag, type: (e.getAttribute('type') || '').toLowerCase() }; })()`);
|
|
1241
1266
|
if (!r) throw new Error(ref !== undefined && ref !== null && ref !== '' ? `Item [${ref}] was not found: the page has changed. Call browser_read again for fresh numbers.` : `No clickable item with the text "${text}" was found. Call browser_read to see what is on the page.`);
|
|
1242
1267
|
return r;
|
|
@@ -1274,6 +1299,21 @@ async function pressKeys(s, keys) {
|
|
|
1274
1299
|
await s.send('Input.dispatchKeyEvent', { type: 'keyUp', ...base });
|
|
1275
1300
|
}
|
|
1276
1301
|
}
|
|
1302
|
+
let lastShot = { scale: 1, top: 0 }; // the latest browser_screenshot: pixels -> page position
|
|
1303
|
+
// 0.7.4: when the AI itself moves the page away (open another address, back, forward, reload), a site's "Leave site?
|
|
1304
|
+
// Changes may not be saved" dialog froze the browser tab. Switch that question off just before those moves. (Clicks on
|
|
1305
|
+
// the page keep the dialog, so it still protects unsaved work there.)
|
|
1306
|
+
const NO_LEAVE_JS = "(() => { try { window.onbeforeunload = null; window.addEventListener('beforeunload', (e) => { e.stopImmediatePropagation(); }, true); } catch {} return true; })()";
|
|
1307
|
+
async function noLeaveDialog(s) { try { await evalJs(s, NO_LEAVE_JS, 5000); } catch {} try { await s.send('Page.enable', {}, 5000); } catch {} }
|
|
1308
|
+
// If the question still appears (some pages ask anyway), answer "Leave" once: the AI itself asked to move on.
|
|
1309
|
+
async function leaveIfAsked(s, move) {
|
|
1310
|
+
await noLeaveDialog(s);
|
|
1311
|
+
const p = Promise.resolve().then(move);
|
|
1312
|
+
p.catch(() => {});
|
|
1313
|
+
const done = await Promise.race([p.then(() => true, () => true), sleep(1500).then(() => false)]);
|
|
1314
|
+
if (!done) { try { await s.send('Page.handleJavaScriptDialog', { accept: true }, 5000); } catch {} }
|
|
1315
|
+
return p;
|
|
1316
|
+
}
|
|
1277
1317
|
async function afterAction(s, ms = 900) {
|
|
1278
1318
|
await sleep(ms);
|
|
1279
1319
|
await waitLoad(s, 8000);
|
|
@@ -1286,7 +1326,7 @@ const browserHandlers = {
|
|
|
1286
1326
|
const started = await ensureBrowser();
|
|
1287
1327
|
if (new_tab) { const t = await cdpJson(`/json/new?${encodeURI(href)}`); activeTarget = t.id; }
|
|
1288
1328
|
return withPage(async (s) => {
|
|
1289
|
-
if (!new_tab) { await s.send('Page.navigate', { url: href }); await waitLoad(s); } else await waitNav(s);
|
|
1329
|
+
if (!new_tab) { await leaveIfAsked(s, () => s.send('Page.navigate', { url: href })); await waitLoad(s); } else await waitNav(s);
|
|
1290
1330
|
const r = await evalJs(s, SNAPSHOT_JS(6000));
|
|
1291
1331
|
return snapshotText(r, started ? 'Opened the Shellway browser window on the computer (a separate profile; the user\'s own browser is not used).\n' : '');
|
|
1292
1332
|
});
|
|
@@ -1295,8 +1335,20 @@ const browserHandlers = {
|
|
|
1295
1335
|
const max = Math.min(Math.max(Number(max_chars) || 20_000, 1000), 100_000);
|
|
1296
1336
|
return withPage(async (s) => { await waitLoad(s, 5000); return snapshotText(await evalJs(s, SNAPSHOT_JS(max, !!all_items))); });
|
|
1297
1337
|
},
|
|
1298
|
-
async browser_click({ ref, text: t, double }) {
|
|
1299
|
-
|
|
1338
|
+
async browser_click({ ref, text: t, double, x, y }) {
|
|
1339
|
+
// 0.7.4: click a point of the latest browser_screenshot (for things that have no number, e.g. inside a canvas).
|
|
1340
|
+
if ((ref === undefined || ref === null || ref === '') && !t && Number.isFinite(Number(x)) && Number.isFinite(Number(y)) && x !== null && y !== null) {
|
|
1341
|
+
return withPage(async (s) => {
|
|
1342
|
+
const vp = await evalJs(s, '({ sy: scrollY, sx: scrollX, h: innerHeight, w: innerWidth })');
|
|
1343
|
+
const px = Number(x) / lastShot.scale, pyPage = Number(y) / lastShot.scale + lastShot.top;
|
|
1344
|
+
let vy = pyPage - vp.sy;
|
|
1345
|
+
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')); }
|
|
1346
|
+
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).`);
|
|
1347
|
+
await mouseClick(s, px, vy, double ? 2 : 1);
|
|
1348
|
+
return `Clicked at x=${x}, y=${y} of the screenshot.\n${await afterAction(s)}`;
|
|
1349
|
+
});
|
|
1350
|
+
}
|
|
1351
|
+
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');
|
|
1300
1352
|
return withPage(async (s) => {
|
|
1301
1353
|
const p = await refPoint(s, ref, t);
|
|
1302
1354
|
await mouseClick(s, p.x, p.y, double ? 2 : 1);
|
|
@@ -1307,14 +1359,49 @@ const browserHandlers = {
|
|
|
1307
1359
|
if (typeof t !== 'string') throw new Error('text is required');
|
|
1308
1360
|
if (t.length > 10_000) throw new Error('text is too long (max 10,000 characters)');
|
|
1309
1361
|
if (ref === undefined || ref === null || ref === '') throw new Error('ref is required: the [number] of the field from browser_read');
|
|
1362
|
+
const n = Number(ref) | 0;
|
|
1310
1363
|
return withPage(async (s) => {
|
|
1311
1364
|
const p = await refPoint(s, ref);
|
|
1365
|
+
// 0.7.4: a drop-down list (<select>): choose the option whose text or value matches.
|
|
1366
|
+
if (p.tag === 'select') {
|
|
1367
|
+
const r = await evalJs(s, `(() => { ${DEEP_JS} const e = __ref(${n}); if (!e) return null; const want = ${JSON.stringify(t.trim().toLowerCase())};
|
|
1368
|
+
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));
|
|
1369
|
+
if (!o) return { ok: false, opts: opts.slice(0, 30).map((o) => o.text.trim()) };
|
|
1370
|
+
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() }; })()`);
|
|
1371
|
+
if (!r) throw new Error(`Item [${ref}] was not found: the page has changed. Call browser_read again for fresh numbers.`);
|
|
1372
|
+
if (!r.ok) throw new Error(`No option "${t}" in [${ref}]. Options: ${r.opts.join(' | ')}`);
|
|
1373
|
+
return `Chose "${r.chosen}" in [${ref}].\n${await afterAction(s, 500)}`;
|
|
1374
|
+
}
|
|
1375
|
+
// 0.7.4: a file field: text is the path of a file on this computer (same folder rules as read_file).
|
|
1376
|
+
if (p.type === 'file') {
|
|
1377
|
+
const files = t.split(/\r?\n/).map((x) => x.trim()).filter(Boolean).slice(0, 10);
|
|
1378
|
+
if (!files.length) throw new Error('For a file field, text is the full path of the file on this computer (one per line for several).');
|
|
1379
|
+
const full = files.map((f) => resolve(f));
|
|
1380
|
+
for (const f of full) { checkPolicy('read_file', { path: f }); if (!existsSync(f)) throw new Error(`File not found on this computer: ${f}`); }
|
|
1381
|
+
const h = await s.send('Runtime.evaluate', { expression: `(() => { ${DEEP_JS} return __ref(${n}); })()`, returnByValue: false });
|
|
1382
|
+
if (!h || !h.result || !h.result.objectId) throw new Error(`Item [${ref}] was not found: the page has changed. Call browser_read again for fresh numbers.`);
|
|
1383
|
+
await s.send('DOM.setFileInputFiles', { files: full, objectId: h.result.objectId });
|
|
1384
|
+
return `Attached ${full.length} file${full.length > 1 ? 's' : ''} to [${ref}]: ${full.map((f) => basename(f)).join(', ')}.\n${await afterAction(s, 500)}`;
|
|
1385
|
+
}
|
|
1312
1386
|
await mouseClick(s, p.x, p.y);
|
|
1313
1387
|
if (clear !== false) {
|
|
1314
|
-
await evalJs(s, `(() => { const e =
|
|
1388
|
+
await evalJs(s, `(() => { ${DEEP_JS} const e = __ref(${n}); if (!e) return; e.focus();
|
|
1315
1389
|
if (typeof e.select === 'function' && (e.tagName === 'INPUT' || e.tagName === 'TEXTAREA')) e.select(); else document.execCommand('selectAll'); })()`);
|
|
1316
1390
|
}
|
|
1317
|
-
if (t)
|
|
1391
|
+
if (t) {
|
|
1392
|
+
await s.send('Input.insertText', { text: t });
|
|
1393
|
+
// 0.7.4: some fields (tag/chip inputs, some web components) ignore inserted text: if the text did not arrive,
|
|
1394
|
+
// type it key by key instead.
|
|
1395
|
+
const got = await evalJs(s, `(() => { ${DEEP_JS} const e = __ref(${n}); if (!e) return null; const a = e.shadowRoot && e.shadowRoot.activeElement || document.activeElement;
|
|
1396
|
+
const v = (x) => x ? String(x.value !== undefined ? x.value : x.innerText || '') : ''; return v(e) + '\\n' + v(a); })()`);
|
|
1397
|
+
if (got !== null && t.length <= 500 && !String(got).includes(t.slice(-Math.min(t.length, 20)))) {
|
|
1398
|
+
for (const ch of t) {
|
|
1399
|
+
if (ch === '\n') { await pressKeys(s, 'enter'); continue; }
|
|
1400
|
+
await s.send('Input.dispatchKeyEvent', { type: 'keyDown', key: ch, text: ch, unmodifiedText: ch });
|
|
1401
|
+
await s.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
|
|
1402
|
+
}
|
|
1403
|
+
}
|
|
1404
|
+
}
|
|
1318
1405
|
if (submit) { await pressKeys(s, 'enter'); return `Typed ${t.length} characters into [${ref}] and pressed Enter.\n${await afterAction(s)}`; }
|
|
1319
1406
|
return `Typed ${t.length} characters into [${ref}]${p.type === 'password' ? ' (password field)' : ''}.`;
|
|
1320
1407
|
});
|
|
@@ -1339,8 +1426,10 @@ const browserHandlers = {
|
|
|
1339
1426
|
const y = full_page ? 0 : await evalJs(s, 'scrollY');
|
|
1340
1427
|
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 } });
|
|
1341
1428
|
// Keep the image small enough for the AI apps (about 500 KB at most): lower quality first, then size.
|
|
1342
|
-
let
|
|
1343
|
-
|
|
1429
|
+
let sc = scale;
|
|
1430
|
+
let r = await shot(sc, full_page ? 45 : 60);
|
|
1431
|
+
for (let k = 0.7; r.data.length > 700_000 && k > 0.2; k -= 0.2) { sc = scale * k; r = await shot(sc, 40); }
|
|
1432
|
+
lastShot = { scale: sc, top: y }; // for browser_click with x, y
|
|
1344
1433
|
const info = await evalJs(s, '({ title: document.title, url: location.href })');
|
|
1345
1434
|
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)' : ''}` };
|
|
1346
1435
|
});
|
|
@@ -1355,10 +1444,11 @@ const browserHandlers = {
|
|
|
1355
1444
|
return `Opened a new tab, now active: ${redactTitle(r.title, r.url) || '(no title)'} — ${redactUrl(r.url)}\nCall browser_read to see the page.`; });
|
|
1356
1445
|
}
|
|
1357
1446
|
if (a === 'back' || a === 'forward' || a === 'reload') {
|
|
1358
|
-
return withPage(async (s) => { await evalJs(s, a === 'reload' ? 'location.reload()' : `history.${a}()`); return `${a === 'reload' ? 'Reloaded' : `Went ${a}`}.\n${await afterAction(s)}`; });
|
|
1447
|
+
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)}`; });
|
|
1359
1448
|
}
|
|
1360
1449
|
const list = await browserPages();
|
|
1361
|
-
if (!list.length) return extMode() ?
|
|
1450
|
+
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.';
|
|
1451
|
+
if (a === 'list' && extMode()) return `(The user's own browser, 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');
|
|
1362
1452
|
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');
|
|
1363
1453
|
const t = list[(Number(index) | 0) - 1];
|
|
1364
1454
|
if (!t) throw new Error(`No tab number ${index}. Use action "list" to see the tabs.`);
|
|
@@ -1527,7 +1617,9 @@ function service() {
|
|
|
1527
1617
|
loadConf();
|
|
1528
1618
|
mkdirSync(CONF_DIR, { recursive: true });
|
|
1529
1619
|
copyFileSync(fileURLToPath(import.meta.url), dest);
|
|
1530
|
-
|
|
1620
|
+
// 0.7.4: in extension mode also rewrite the browser's link to Shellway (new allowed extension IDs, e.g. the store version).
|
|
1621
|
+
if (extMode() && existsSync(EXT_DEST())) { try { installExtensionHost(); console.log(`Shellway browser extension files and browser link updated (${EXT_DEST()}); the extension reloads itself.`); } catch {} }
|
|
1622
|
+
else if (refreshExtensionFolder()) console.log(`Shellway browser extension files updated (${EXT_DEST()}); the extension reloads itself.`);
|
|
1531
1623
|
if (os === 'linux') {
|
|
1532
1624
|
mkdirSync(join(homedir(), '.config/systemd/user'), { recursive: true });
|
|
1533
1625
|
writeFileSync(unitPath, renderService(os, argv));
|