shellway 0.7.3 → 0.7.5

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.
@@ -1,4 +1,4 @@
1
- // Shellway browser extension (0.7.3).
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 '';
@@ -178,6 +181,11 @@ async function handle(op, a) {
178
181
  if (!/^https?:\/\//i.test(String(params.url || ''))) throw new Error('Only http and https pages can be opened.');
179
182
  if (isBlocked(params.url, blocked)) throw new Error(`Blocked: ${hostOf(params.url)} is on the Shellway extension's list of blocked sites.`);
180
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
+ }
181
189
  if (method === 'Page.captureScreenshot' && !tab.active) { await chrome.tabs.update(tab.id, { active: true }); await sleep(400); }
182
190
  await ensureAttached(tab.id);
183
191
  touchIdle();
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Shellway",
4
- "version": "0.7.3",
4
+ "version": "0.7.5",
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
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shellway",
3
- "version": "0.7.3",
3
+ "version": "0.7.5",
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": {
package/shellway.js CHANGED
@@ -7,9 +7,9 @@ import { fileURLToPath } from 'node:url';
7
7
  import { execFileSync, execFile } from 'node:child_process';
8
8
  import { readFile, writeFile, appendFile, readdir, stat, lstat, mkdir, rename, cp, rm } from 'node:fs/promises';
9
9
  import { createServer as netServer, connect as netConnect } from 'node:net';
10
- import { randomBytes, timingSafeEqual } from 'node:crypto';
10
+ import { randomBytes, timingSafeEqual, createHash } from 'node:crypto';
11
11
 
12
- const AGENT_VERSION = '0.7.3'; // keep equal to agent/package.json
12
+ const AGENT_VERSION = '0.7.5'; // 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,7 +978,10 @@ 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 = ['cepfcfgajaghchkamfmnhgcelblihndk']; // the unpacked extension (fixed by the key in its manifest)
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
986
  const ext = { sock: null, seq: 0, pending: new Map(), version: '' };
984
987
  const extMode = () => { const p = loadPolicy(); return !!p && p.browser === 'extension'; };
@@ -1131,6 +1134,23 @@ function installExtensionHost() {
1131
1134
  const extConnected = () => !!ext.sock;
1132
1135
  const extVersion = () => ext.version;
1133
1136
  export { nativeHostManifest, nativeHostTargets, extJson, extCall, startExtBridge, extConnected, extVersion, installExtensionHost, SNAPSHOT_JS };
1137
+ // 0.7.5: one free trial per computer (owner 21 Nov 2026). The computer's own built-in ID (Windows MachineGuid, Mac
1138
+ // hardware UUID, Linux machine-id) does not change when the computer or the account is renamed. Only a one-way code
1139
+ // made from it is sent; the ID itself never leaves the computer.
1140
+ let machineHashCache;
1141
+ function machineId(os = platform()) {
1142
+ try {
1143
+ if (os === 'win32') { const o = execFileSync('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\Cryptography', '/v', 'MachineGuid'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true }); return (/MachineGuid\s+REG_SZ\s+(\S+)/i.exec(o) || [])[1] || ''; }
1144
+ if (os === 'darwin') { const o = execFileSync('ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice'], { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'ignore'] }); return (/"IOPlatformUUID"\s*=\s*"([^"]+)"/.exec(o) || [])[1] || ''; }
1145
+ for (const f of ['/etc/machine-id', '/var/lib/dbus/machine-id']) { try { const v = readFileSync(f, 'utf8').trim(); if (v) return v; } catch {} }
1146
+ } catch {}
1147
+ return '';
1148
+ }
1149
+ function machineHash() {
1150
+ if (machineHashCache === undefined) { const id = String(machineId() || '').trim().toLowerCase(); machineHashCache = id.length >= 8 ? createHash('sha256').update('shellway-machine-v1:' + id).digest('hex').slice(0, 32) : null; }
1151
+ return machineHashCache;
1152
+ }
1153
+ export { machineHash };
1134
1154
  const browserPages = async () => (await cdpJson('/json/list')).filter((t) => t.type === 'page' && !String(t.url).startsWith('devtools:'));
1135
1155
  async function currentPage() {
1136
1156
  await ensureBrowser();
@@ -1147,8 +1167,8 @@ async function withPage(fn) {
1147
1167
  const s = await cdpSession(t.webSocketDebuggerUrl);
1148
1168
  try { return await fn(s, t); } finally { s.close(); }
1149
1169
  }
1150
- async function evalJs(s, expression) {
1151
- const r = await s.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true });
1170
+ async function evalJs(s, expression, ms) {
1171
+ const r = await s.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, ms);
1152
1172
  if (r.exceptionDetails) throw new Error(`Page script error: ${String(r.exceptionDetails.exception?.description || r.exceptionDetails.text || '').slice(0, 200)}`);
1153
1173
  return r.result ? r.result.value : undefined;
1154
1174
  }
@@ -1161,26 +1181,44 @@ async function waitLoad(s, ms = 15_000) {
1161
1181
  }
1162
1182
  return false;
1163
1183
  }
1184
+ // 0.7.4: pages built from web components (Microsoft Partner Center, many Google/Salesforce pages) keep their buttons and
1185
+ // fields inside "shadow roots", which document.querySelectorAll does not see. __all/__ref look inside every open one.
1186
+ const DEEP_JS = `const __all = (sel) => { const out = []; const walk = (root) => { for (const e of root.querySelectorAll(sel)) out.push(e);
1187
+ for (const h of root.querySelectorAll('*')) if (h.shadowRoot) walk(h.shadowRoot); }; walk(document); return out; };
1188
+ const __ref = (n) => __all('[data-sw-ref="' + n + '"]')[0] || null;`;
1189
+ 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]';
1164
1190
  // Numbers every visible link, button and field ([n]) so browser_click / browser_type can use them. Password values are never read.
1165
1191
  const SNAPSHOT_JS = (maxText, allItems = false) => `(() => {
1192
+ ${DEEP_JS}
1166
1193
  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'; };
1167
- const sel = 'a[href],button,input:not([type=hidden]),textarea,select,summary,[role=button],[role=link],[role=tab],[role=menuitem],[role=checkbox],[role=option],[contenteditable=""],[contenteditable=true]';
1168
- document.querySelectorAll('[data-sw-ref]').forEach((e) => e.removeAttribute('data-sw-ref'));
1194
+ const sel = '${ITEM_SEL}';
1195
+ __all('[data-sw-ref]').forEach((e) => e.removeAttribute('data-sw-ref'));
1196
+ // A button inside a web component often has no text of its own (the text is the component's): use the component's.
1197
+ const hostLabel = (e) => { const h = e.getRootNode && e.getRootNode().host; return h ? (h.getAttribute('aria-label') || h.innerText || h.getAttribute('title') || '') : ''; };
1169
1198
  // 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
1170
1199
  // listed (at most ITEM_CAP) unless all items are asked for: long pages sent 300 links and slowed the AI apps down.
1171
1200
  const ITEM_CAP = ${allItems ? 300 : 80}, near = (e) => { const r = e.getBoundingClientRect(); return r.bottom > -innerHeight * 0.5 && r.top < innerHeight * 1.5; };
1172
1201
  const items = []; let n = 0, skipped = 0;
1173
- for (const e of document.querySelectorAll(sel)) {
1202
+ const seen = new Set();
1203
+ for (const e of __all(sel)) {
1174
1204
  if (n >= 300 || !vis(e)) continue;
1205
+ // a web component with role=button and the real <button> inside it: list only one of them
1206
+ const inner = e.shadowRoot && e.shadowRoot.querySelector('button,input,textarea,select,a[href]');
1207
+ if (inner && vis(inner)) continue;
1208
+ if (seen.has(e)) continue; seen.add(e);
1175
1209
  const ref = ++n; e.setAttribute('data-sw-ref', String(ref));
1176
1210
  if (${allItems ? 'false' : 'true'} && (!near(e) || items.length >= ITEM_CAP)) { skipped++; continue; }
1177
1211
  const tag = e.tagName.toLowerCase(), type = (e.getAttribute('type') || '').toLowerCase();
1178
- 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);
1179
- const kind = tag === 'a' ? 'link' : tag === 'input' ? 'input' + (type ? ':' + type : '') : tag;
1212
+ 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);
1213
+ const role = e.getAttribute('role') || '';
1214
+ const kind = tag === 'a' ? 'link' : tag === 'input' ? 'input' + (type ? ':' + type : '') : (tag.includes('-') && role ? role : tag);
1180
1215
  let val = '';
1181
1216
  if ((tag === 'input' || tag === 'textarea') && type !== 'password' && e.value) val = ' value="' + String(e.value).slice(0, 40) + '"';
1182
1217
  if (tag === 'select' && e.selectedOptions && e.selectedOptions[0]) val = ' selected="' + e.selectedOptions[0].text.slice(0, 40) + '"';
1183
1218
  if (type === 'checkbox' || type === 'radio') val = e.checked ? ' checked' : ' unchecked';
1219
+ else if (/^(checkbox|radio|switch|menuitemradio)$/.test(role)) val = e.getAttribute('aria-checked') === 'true' ? ' checked' : ' unchecked';
1220
+ 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 ? ' | …' : '') + '"';
1221
+ if (type === 'file') val = ' (to upload: browser_type with the file path on this computer)';
1184
1222
  items.push('[' + ref + '] ' + kind + ' "' + label.replace(/"/g, "'") + '"' + val);
1185
1223
  }
1186
1224
  const text = (document.body ? document.body.innerText : '').replace(/[ \\t]+\\n/g, '\\n').replace(/\\n{3,}/g, '\\n\\n').trim();
@@ -1233,12 +1271,14 @@ function snapshotText(r, label = '') {
1233
1271
  }
1234
1272
  async function refPoint(s, ref, text) {
1235
1273
  const pick = ref !== undefined && ref !== null && ref !== ''
1236
- ? `document.querySelector('[data-sw-ref="${Number(ref) | 0}"]')`
1237
- : `(() => { const want = ${JSON.stringify(String(text || '').toLowerCase())}; const sel = 'a[href],button,input,textarea,select,summary,[role=button],[role=link],[role=tab],[role=menuitem],[role=checkbox],[role=option]';
1238
- for (const e of document.querySelectorAll(sel)) { const r = e.getBoundingClientRect(); if (r.width < 1 || r.height < 1) continue;
1239
- const l = (e.getAttribute('aria-label') || e.innerText || e.value || e.getAttribute('placeholder') || e.getAttribute('title') || '').replace(/\\s+/g, ' ').trim().toLowerCase();
1240
- if (l && l.includes(want)) return e; } return null; })()`;
1241
- const r = await evalJs(s, `(() => { const e = ${pick}; if (!e) return null; e.scrollIntoView({ block: 'center', inline: 'center' }); const b = e.getBoundingClientRect();
1274
+ ? `__ref(${Number(ref) | 0})`
1275
+ : `(() => { const want = ${JSON.stringify(String(text || '').toLowerCase())}; const sel = '${ITEM_SEL}';
1276
+ const hostLabel = (e) => { const h = e.getRootNode && e.getRootNode().host; return h ? (h.getAttribute('aria-label') || h.innerText || '') : ''; };
1277
+ let partial = null;
1278
+ for (const e of __all(sel)) { const r = e.getBoundingClientRect(); if (r.width < 1 || r.height < 1) continue;
1279
+ const l = (e.getAttribute('aria-label') || e.innerText || e.value || e.getAttribute('placeholder') || e.getAttribute('title') || hostLabel(e) || '').replace(/\\s+/g, ' ').trim().toLowerCase();
1280
+ if (l === want) return e; if (!partial && l && l.includes(want)) partial = e; } return partial; })()`;
1281
+ const r = await evalJs(s, `(() => { ${DEEP_JS} const e = ${pick}; if (!e) return null; e.scrollIntoView({ block: 'center', inline: 'center' }); const b = e.getBoundingClientRect();
1242
1282
  const tag = e.tagName.toLowerCase(); return { x: b.left + b.width / 2, y: b.top + b.height / 2, tag, type: (e.getAttribute('type') || '').toLowerCase() }; })()`);
1243
1283
  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.`);
1244
1284
  return r;
@@ -1276,6 +1316,21 @@ async function pressKeys(s, keys) {
1276
1316
  await s.send('Input.dispatchKeyEvent', { type: 'keyUp', ...base });
1277
1317
  }
1278
1318
  }
1319
+ let lastShot = { scale: 1, top: 0 }; // the latest browser_screenshot: pixels -> page position
1320
+ // 0.7.4: when the AI itself moves the page away (open another address, back, forward, reload), a site's "Leave site?
1321
+ // Changes may not be saved" dialog froze the browser tab. Switch that question off just before those moves. (Clicks on
1322
+ // the page keep the dialog, so it still protects unsaved work there.)
1323
+ const NO_LEAVE_JS = "(() => { try { window.onbeforeunload = null; window.addEventListener('beforeunload', (e) => { e.stopImmediatePropagation(); }, true); } catch {} return true; })()";
1324
+ async function noLeaveDialog(s) { try { await evalJs(s, NO_LEAVE_JS, 5000); } catch {} try { await s.send('Page.enable', {}, 5000); } catch {} }
1325
+ // If the question still appears (some pages ask anyway), answer "Leave" once: the AI itself asked to move on.
1326
+ async function leaveIfAsked(s, move) {
1327
+ await noLeaveDialog(s);
1328
+ const p = Promise.resolve().then(move);
1329
+ p.catch(() => {});
1330
+ const done = await Promise.race([p.then(() => true, () => true), sleep(1500).then(() => false)]);
1331
+ if (!done) { try { await s.send('Page.handleJavaScriptDialog', { accept: true }, 5000); } catch {} }
1332
+ return p;
1333
+ }
1279
1334
  async function afterAction(s, ms = 900) {
1280
1335
  await sleep(ms);
1281
1336
  await waitLoad(s, 8000);
@@ -1288,7 +1343,7 @@ const browserHandlers = {
1288
1343
  const started = await ensureBrowser();
1289
1344
  if (new_tab) { const t = await cdpJson(`/json/new?${encodeURI(href)}`); activeTarget = t.id; }
1290
1345
  return withPage(async (s) => {
1291
- if (!new_tab) { await s.send('Page.navigate', { url: href }); await waitLoad(s); } else await waitNav(s);
1346
+ if (!new_tab) { await leaveIfAsked(s, () => s.send('Page.navigate', { url: href })); await waitLoad(s); } else await waitNav(s);
1292
1347
  const r = await evalJs(s, SNAPSHOT_JS(6000));
1293
1348
  return snapshotText(r, started ? 'Opened the Shellway browser window on the computer (a separate profile; the user\'s own browser is not used).\n' : '');
1294
1349
  });
@@ -1297,8 +1352,20 @@ const browserHandlers = {
1297
1352
  const max = Math.min(Math.max(Number(max_chars) || 20_000, 1000), 100_000);
1298
1353
  return withPage(async (s) => { await waitLoad(s, 5000); return snapshotText(await evalJs(s, SNAPSHOT_JS(max, !!all_items))); });
1299
1354
  },
1300
- async browser_click({ ref, text: t, double }) {
1301
- if ((ref === undefined || ref === null || ref === '') && !t) throw new Error('ref (the [number] from browser_read) or text is required');
1355
+ async browser_click({ ref, text: t, double, x, y }) {
1356
+ // 0.7.4: click a point of the latest browser_screenshot (for things that have no number, e.g. inside a canvas).
1357
+ if ((ref === undefined || ref === null || ref === '') && !t && Number.isFinite(Number(x)) && Number.isFinite(Number(y)) && x !== null && y !== null) {
1358
+ return withPage(async (s) => {
1359
+ const vp = await evalJs(s, '({ sy: scrollY, sx: scrollX, h: innerHeight, w: innerWidth })');
1360
+ const px = Number(x) / lastShot.scale, pyPage = Number(y) / lastShot.scale + lastShot.top;
1361
+ let vy = pyPage - vp.sy;
1362
+ 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')); }
1363
+ 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).`);
1364
+ await mouseClick(s, px, vy, double ? 2 : 1);
1365
+ return `Clicked at x=${x}, y=${y} of the screenshot.\n${await afterAction(s)}`;
1366
+ });
1367
+ }
1368
+ 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');
1302
1369
  return withPage(async (s) => {
1303
1370
  const p = await refPoint(s, ref, t);
1304
1371
  await mouseClick(s, p.x, p.y, double ? 2 : 1);
@@ -1309,14 +1376,49 @@ const browserHandlers = {
1309
1376
  if (typeof t !== 'string') throw new Error('text is required');
1310
1377
  if (t.length > 10_000) throw new Error('text is too long (max 10,000 characters)');
1311
1378
  if (ref === undefined || ref === null || ref === '') throw new Error('ref is required: the [number] of the field from browser_read');
1379
+ const n = Number(ref) | 0;
1312
1380
  return withPage(async (s) => {
1313
1381
  const p = await refPoint(s, ref);
1382
+ // 0.7.4: a drop-down list (<select>): choose the option whose text or value matches.
1383
+ if (p.tag === 'select') {
1384
+ const r = await evalJs(s, `(() => { ${DEEP_JS} const e = __ref(${n}); if (!e) return null; const want = ${JSON.stringify(t.trim().toLowerCase())};
1385
+ 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));
1386
+ if (!o) return { ok: false, opts: opts.slice(0, 30).map((o) => o.text.trim()) };
1387
+ 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() }; })()`);
1388
+ if (!r) throw new Error(`Item [${ref}] was not found: the page has changed. Call browser_read again for fresh numbers.`);
1389
+ if (!r.ok) throw new Error(`No option "${t}" in [${ref}]. Options: ${r.opts.join(' | ')}`);
1390
+ return `Chose "${r.chosen}" in [${ref}].\n${await afterAction(s, 500)}`;
1391
+ }
1392
+ // 0.7.4: a file field: text is the path of a file on this computer (same folder rules as read_file).
1393
+ if (p.type === 'file') {
1394
+ const files = t.split(/\r?\n/).map((x) => x.trim()).filter(Boolean).slice(0, 10);
1395
+ 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).');
1396
+ const full = files.map((f) => resolve(f));
1397
+ for (const f of full) { checkPolicy('read_file', { path: f }); if (!existsSync(f)) throw new Error(`File not found on this computer: ${f}`); }
1398
+ const h = await s.send('Runtime.evaluate', { expression: `(() => { ${DEEP_JS} return __ref(${n}); })()`, returnByValue: false });
1399
+ 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.`);
1400
+ await s.send('DOM.setFileInputFiles', { files: full, objectId: h.result.objectId });
1401
+ return `Attached ${full.length} file${full.length > 1 ? 's' : ''} to [${ref}]: ${full.map((f) => basename(f)).join(', ')}.\n${await afterAction(s, 500)}`;
1402
+ }
1314
1403
  await mouseClick(s, p.x, p.y);
1315
1404
  if (clear !== false) {
1316
- await evalJs(s, `(() => { const e = document.querySelector('[data-sw-ref="${Number(ref) | 0}"]'); if (!e) return; e.focus();
1405
+ await evalJs(s, `(() => { ${DEEP_JS} const e = __ref(${n}); if (!e) return; e.focus();
1317
1406
  if (typeof e.select === 'function' && (e.tagName === 'INPUT' || e.tagName === 'TEXTAREA')) e.select(); else document.execCommand('selectAll'); })()`);
1318
1407
  }
1319
- if (t) await s.send('Input.insertText', { text: t });
1408
+ if (t) {
1409
+ await s.send('Input.insertText', { text: t });
1410
+ // 0.7.4: some fields (tag/chip inputs, some web components) ignore inserted text: if the text did not arrive,
1411
+ // type it key by key instead.
1412
+ const got = await evalJs(s, `(() => { ${DEEP_JS} const e = __ref(${n}); if (!e) return null; const a = e.shadowRoot && e.shadowRoot.activeElement || document.activeElement;
1413
+ const v = (x) => x ? String(x.value !== undefined ? x.value : x.innerText || '') : ''; return v(e) + '\\n' + v(a); })()`);
1414
+ if (got !== null && t.length <= 500 && !String(got).includes(t.slice(-Math.min(t.length, 20)))) {
1415
+ for (const ch of t) {
1416
+ if (ch === '\n') { await pressKeys(s, 'enter'); continue; }
1417
+ await s.send('Input.dispatchKeyEvent', { type: 'keyDown', key: ch, text: ch, unmodifiedText: ch });
1418
+ await s.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
1419
+ }
1420
+ }
1421
+ }
1320
1422
  if (submit) { await pressKeys(s, 'enter'); return `Typed ${t.length} characters into [${ref}] and pressed Enter.\n${await afterAction(s)}`; }
1321
1423
  return `Typed ${t.length} characters into [${ref}]${p.type === 'password' ? ' (password field)' : ''}.`;
1322
1424
  });
@@ -1341,8 +1443,10 @@ const browserHandlers = {
1341
1443
  const y = full_page ? 0 : await evalJs(s, 'scrollY');
1342
1444
  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 } });
1343
1445
  // Keep the image small enough for the AI apps (about 500 KB at most): lower quality first, then size.
1344
- let r = await shot(scale, full_page ? 45 : 60);
1345
- for (let k = 0.7; r.data.length > 700_000 && k > 0.2; k -= 0.2) r = await shot(scale * k, 40);
1446
+ let sc = scale;
1447
+ let r = await shot(sc, full_page ? 45 : 60);
1448
+ for (let k = 0.7; r.data.length > 700_000 && k > 0.2; k -= 0.2) { sc = scale * k; r = await shot(sc, 40); }
1449
+ lastShot = { scale: sc, top: y }; // for browser_click with x, y
1346
1450
  const info = await evalJs(s, '({ title: document.title, url: location.href })');
1347
1451
  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)' : ''}` };
1348
1452
  });
@@ -1357,7 +1461,7 @@ const browserHandlers = {
1357
1461
  return `Opened a new tab, now active: ${redactTitle(r.title, r.url) || '(no title)'} — ${redactUrl(r.url)}\nCall browser_read to see the page.`; });
1358
1462
  }
1359
1463
  if (a === 'back' || a === 'forward' || a === 'reload') {
1360
- return withPage(async (s) => { await evalJs(s, a === 'reload' ? 'location.reload()' : `history.${a}()`); return `${a === 'reload' ? 'Reloaded' : `Went ${a}`}.\n${await afterAction(s)}`; });
1464
+ 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)}`; });
1361
1465
  }
1362
1466
  const list = await browserPages();
1363
1467
  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.';
@@ -1457,7 +1561,7 @@ function start() {
1457
1561
  const ws = new WebSocket(wsUrl, { headers: { authorization: `Bearer ${conf.device_token}`, 'x-shellway-version': AGENT_VERSION } });
1458
1562
  current = ws;
1459
1563
  ws.onopen = () => { if (my !== gen) { try { ws.close(); } catch {} return; } connectingSince = 0; delay = 1000; lastMsg = Date.now();
1460
- try { ws.send(JSON.stringify({ type: 'info', v: AGENT_VERSION, node: process.versions.node, os: platform(), reason: why, ...(prevCid ? { replaced: prevCid } : {}) })); } catch {}
1564
+ try { ws.send(JSON.stringify({ type: 'info', v: AGENT_VERSION, node: process.versions.node, os: platform(), reason: why, ...(machineHash() ? { mid: machineHash() } : {}), ...(prevCid ? { replaced: prevCid } : {}) })); } catch {}
1461
1565
  why = 'network'; prevCid = null; console.log(`Connected as "${conf.device_name}"${readonly ? ' (read-only)' : ''}. Leave this running.`); };
1462
1566
  ws.onmessage = async (ev) => {
1463
1567
  lastMsg = Date.now();
@@ -1530,7 +1634,9 @@ function service() {
1530
1634
  loadConf();
1531
1635
  mkdirSync(CONF_DIR, { recursive: true });
1532
1636
  copyFileSync(fileURLToPath(import.meta.url), dest);
1533
- if (refreshExtensionFolder()) console.log(`Shellway browser extension files updated (${EXT_DEST()}); the extension reloads itself.`);
1637
+ // 0.7.4: in extension mode also rewrite the browser's link to Shellway (new allowed extension IDs, e.g. the store version).
1638
+ if (extMode() && existsSync(EXT_DEST())) { try { installExtensionHost(); console.log(`Shellway browser extension files and browser link updated (${EXT_DEST()}); the extension reloads itself.`); } catch {} }
1639
+ else if (refreshExtensionFolder()) console.log(`Shellway browser extension files updated (${EXT_DEST()}); the extension reloads itself.`);
1534
1640
  if (os === 'linux') {
1535
1641
  mkdirSync(join(homedir(), '.config/systemd/user'), { recursive: true });
1536
1642
  writeFileSync(unitPath, renderService(os, argv));