shellway 0.6.9 → 0.7.0

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.
@@ -0,0 +1,181 @@
1
+ // Shellway browser extension (0.7.0).
2
+ // The Shellway app on this computer (the agent) talks to this extension through Chrome/Edge "native messaging":
3
+ // the browser starts a small Shellway helper that is only allowed to talk to THIS extension. The AI never talks to the
4
+ // extension directly; every request comes from the agent, which already checks the owner's safety rules.
5
+ // Safety: off until the owner turns it on; banking, trading, payment and password sites are blocked (list editable);
6
+ // while the AI works on a tab the browser shows its own "started debugging this browser" bar, and pressing Cancel on
7
+ // that bar turns Shellway off at once. Only a fixed list of DevTools commands is allowed.
8
+
9
+ const HOST = 'com.getshellway.agent';
10
+ const DEFAULT_BLOCKED = [
11
+ // banks and payments
12
+ 'onlinesbi.sbi', 'sbi.co.in', 'hdfcbank.com', 'icicibank.com', 'axisbank.com', 'kotak.com', 'pnbindia.in', 'bankofbaroda.in',
13
+ 'yesbank.in', 'idfcfirstbank.com', 'indusind.com', 'canarabank.com', 'unionbankofindia.co.in', 'paytm.com', 'phonepe.com',
14
+ 'paypal.com', 'wise.com', 'stripe.com',
15
+ // trading and investing
16
+ 'zerodha.com', 'upstox.com', 'groww.in', 'angelone.in', 'fyers.in', 'dhan.co', '5paisa.com', 'icicidirect.com', 'mstock.com',
17
+ 'binance.com', 'coinbase.com', 'wazirx.com',
18
+ // passwords and account security
19
+ 'passwords.google.com', 'myaccount.google.com', 'accounts.google.com', 'account.microsoft.com', 'login.live.com',
20
+ '1password.com', 'bitwarden.com', 'lastpass.com', 'dashlane.com',
21
+ ];
22
+ const ALLOWED_CDP = new Set([
23
+ 'Runtime.evaluate', 'Input.dispatchMouseEvent', 'Input.dispatchKeyEvent', 'Input.insertText',
24
+ 'Page.navigate', 'Page.reload', 'Page.captureScreenshot', 'Page.getLayoutMetrics', 'Page.bringToFront',
25
+ ]);
26
+ const IDLE_DETACH_MS = 60_000;
27
+
28
+ let port = null;
29
+ let connected = false;
30
+ let agentVersion = '';
31
+ let lastError = '';
32
+ const attached = new Set();
33
+ const groupByWindow = new Map();
34
+ let idleTimer = null;
35
+
36
+ const getSettings = () => chrome.storage.local.get({ enabled: false, blocked: DEFAULT_BLOCKED });
37
+ const hostOf = (url) => { try { return new URL(url).hostname.toLowerCase(); } catch { return ''; } };
38
+ function isBlocked(url, blocked) {
39
+ const h = hostOf(url);
40
+ if (!h) return false;
41
+ return blocked.some((b) => { const d = String(b).trim().toLowerCase().replace(/^\*\./, ''); return d && (h === d || h.endsWith('.' + d)); });
42
+ }
43
+ const webUrl = (u) => /^https?:\/\//i.test(String(u || '')) || String(u || '') === 'about:blank';
44
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
45
+
46
+ function badge() {
47
+ const text = connected ? 'ON' : port ? '…' : '';
48
+ chrome.action.setBadgeText({ text }).catch(() => {});
49
+ chrome.action.setBadgeBackgroundColor({ color: connected ? '#0a7d4f' : '#b26a00' }).catch(() => {});
50
+ }
51
+
52
+ async function connect() {
53
+ const s = await getSettings();
54
+ if (!s.enabled || port) return;
55
+ try { port = chrome.runtime.connectNative(HOST); } catch (e) { lastError = String(e && e.message || e); port = null; badge(); return; }
56
+ port.onMessage.addListener(onMessage);
57
+ port.onDisconnect.addListener(() => {
58
+ const err = chrome.runtime.lastError && chrome.runtime.lastError.message;
59
+ if (err) lastError = /not found/i.test(err) ? 'The Shellway app is not set up for the extension on this computer. Run: npx shellway@beta policy browser extension' : err;
60
+ port = null; connected = false; badge(); detachAll();
61
+ });
62
+ badge();
63
+ }
64
+ function disconnect() {
65
+ if (port) { try { port.disconnect(); } catch {} }
66
+ port = null; connected = false; badge(); detachAll();
67
+ }
68
+
69
+ async function onMessage(m) {
70
+ if (!m || typeof m !== 'object') return;
71
+ if (m.type === 'hello') { connected = true; agentVersion = m.version || ''; lastError = ''; badge(); return; }
72
+ if (m.type === 'error') { lastError = m.message || 'error'; return; }
73
+ if (m.id === undefined) return;
74
+ try {
75
+ const result = await handle(m.op, m.args || {});
76
+ if (port) port.postMessage({ id: m.id, ok: true, result });
77
+ } catch (e) {
78
+ if (port) port.postMessage({ id: m.id, ok: false, error: String(e && e.message || e) });
79
+ }
80
+ }
81
+
82
+ async function addToGroup(tab) {
83
+ try {
84
+ let gid = groupByWindow.get(tab.windowId);
85
+ if (gid !== undefined) { try { await chrome.tabGroups.get(gid); } catch { gid = undefined; } }
86
+ gid = await chrome.tabs.group(gid === undefined ? { tabIds: [tab.id], createProperties: { windowId: tab.windowId } } : { tabIds: [tab.id], groupId: gid });
87
+ groupByWindow.set(tab.windowId, gid);
88
+ await chrome.tabGroups.update(gid, { title: 'Shellway AI', color: 'cyan' });
89
+ } catch { /* tab groups are a convenience only */ }
90
+ }
91
+
92
+ async function tabFor(id, blocked) {
93
+ let tab;
94
+ try { tab = await chrome.tabs.get(Number(id)); } catch { throw new Error('That tab is closed. List the tabs again.'); }
95
+ if (isBlocked(tab.url || tab.pendingUrl, blocked)) throw new Error(`Blocked: ${hostOf(tab.url || tab.pendingUrl)} is on the Shellway extension's list of blocked sites (banking, trading, payments, passwords). The owner can change the list in the Shellway extension.`);
96
+ return tab;
97
+ }
98
+ async function ensureAttached(tabId) {
99
+ if (attached.has(tabId)) return;
100
+ try { await chrome.debugger.attach({ tabId }, '1.3'); }
101
+ catch (e) { if (!/already attached/i.test(String(e && e.message))) throw new Error(`Could not use this tab: ${e && e.message || e}`); }
102
+ attached.add(tabId);
103
+ }
104
+ function touchIdle() {
105
+ clearTimeout(idleTimer);
106
+ idleTimer = setTimeout(detachAll, IDLE_DETACH_MS); // the "debugging" bar goes away when the AI is idle
107
+ }
108
+ function detachAll() {
109
+ clearTimeout(idleTimer);
110
+ for (const tabId of [...attached]) { chrome.debugger.detach({ tabId }).catch(() => {}); attached.delete(tabId); }
111
+ }
112
+
113
+ async function handle(op, a) {
114
+ const { enabled, blocked } = await getSettings();
115
+ if (!enabled) throw new Error('The Shellway extension is turned off in this browser.');
116
+ if (op === 'list') {
117
+ const tabs = await chrome.tabs.query({});
118
+ return tabs.filter((t) => webUrl(t.url || t.pendingUrl) && !isBlocked(t.url || t.pendingUrl, blocked))
119
+ .map((t) => ({ id: String(t.id), type: 'page', title: t.title || '', url: t.url || t.pendingUrl || '', active: !!t.active }));
120
+ }
121
+ if (op === 'new') {
122
+ const url = a.url || 'about:blank';
123
+ if (!webUrl(url)) throw new Error('Only http and https pages can be opened.');
124
+ if (isBlocked(url, blocked)) throw new Error(`Blocked: ${hostOf(url)} is on the Shellway extension's list of blocked sites.`);
125
+ const tab = await chrome.tabs.create({ url, active: true });
126
+ await addToGroup(tab);
127
+ return { id: String(tab.id) };
128
+ }
129
+ if (op === 'close') { await chrome.tabs.remove(Number(a.id)); attached.delete(Number(a.id)); return 'closed'; }
130
+ if (op === 'activate') {
131
+ const tab = await tabFor(a.id, blocked);
132
+ await chrome.tabs.update(tab.id, { active: true });
133
+ return 'ok';
134
+ }
135
+ if (op === 'cdp') {
136
+ const method = String(a.method || '');
137
+ if (!ALLOWED_CDP.has(method)) throw new Error(`Not allowed in the Shellway extension: ${method}`);
138
+ const tab = await tabFor(a.id, blocked);
139
+ const params = a.params || {};
140
+ if (method === 'Page.navigate') {
141
+ if (!/^https?:\/\//i.test(String(params.url || ''))) throw new Error('Only http and https pages can be opened.');
142
+ if (isBlocked(params.url, blocked)) throw new Error(`Blocked: ${hostOf(params.url)} is on the Shellway extension's list of blocked sites.`);
143
+ }
144
+ if (method === 'Page.captureScreenshot' && !tab.active) { await chrome.tabs.update(tab.id, { active: true }); await sleep(400); }
145
+ await ensureAttached(tab.id);
146
+ touchIdle();
147
+ return await chrome.debugger.sendCommand({ tabId: tab.id }, method, params);
148
+ }
149
+ if (op === 'ping') return 'pong';
150
+ throw new Error(`Unknown request: ${op}`);
151
+ }
152
+
153
+ // Cancel on the browser's "debugging" bar = the owner wants it to stop: turn Shellway off.
154
+ chrome.debugger.onDetach.addListener(async (src, reason) => {
155
+ attached.delete(src.tabId);
156
+ if (reason === 'canceled_by_user') {
157
+ await chrome.storage.local.set({ enabled: false });
158
+ lastError = 'Turned off: Cancel was pressed on the browser bar.';
159
+ disconnect();
160
+ }
161
+ });
162
+ chrome.tabs.onRemoved.addListener((tabId) => attached.delete(tabId));
163
+
164
+ // Popup
165
+ chrome.runtime.onMessage.addListener((msg, _sender, reply) => {
166
+ (async () => {
167
+ if (msg.cmd === 'set') { await chrome.storage.local.set({ enabled: !!msg.enabled }); if (msg.enabled) { lastError = ''; await connect(); } else disconnect(); }
168
+ if (msg.cmd === 'blocked') await chrome.storage.local.set({ blocked: String(msg.list || '').split(/[\s,]+/).map((x) => x.trim()).filter(Boolean) });
169
+ if (msg.cmd === 'reset-blocked') await chrome.storage.local.set({ blocked: DEFAULT_BLOCKED });
170
+ const s = await getSettings();
171
+ reply({ enabled: s.enabled, blocked: s.blocked, connected, connecting: !!port && !connected, agentVersion, lastError, working: attached.size });
172
+ })();
173
+ return true;
174
+ });
175
+
176
+ // Stay connected: reconnect on start, and every 30 seconds if the link dropped (for example after the computer slept).
177
+ chrome.alarms.create('shellway-keep', { periodInMinutes: 0.5 });
178
+ chrome.alarms.onAlarm.addListener((a) => { if (a.name === 'shellway-keep') connect(); });
179
+ chrome.runtime.onStartup.addListener(connect);
180
+ chrome.runtime.onInstalled.addListener(connect);
181
+ connect();
Binary file
Binary file
Binary file
Binary file
@@ -0,0 +1,12 @@
1
+ {
2
+ "manifest_version": 3,
3
+ "name": "Shellway",
4
+ "version": "0.7.0",
5
+ "description": "Lets your AI (ChatGPT, Claude) use this browser through the Shellway app on your computer. Off until you turn it on.",
6
+ "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnZWALJr6dwkQu7eX3reFbtgMAErsCyODHKnwz97XMKpR9bAz4+irBlJ2KEXD6ERZFjuKYqNZ2HLe0eQp5y9fWscyWeTUXNTstsFaymsb5C0aRcpW/dXRl2Dy9vQ7y7+ATH4SCxcckncfmEXt4GFQ6TtyPsctuQfYez6o9MHmwGaKwpCPaWmqfYqomy0yjzMCbCg2b0aP2+hDmOhc0KARhGVnzlZBIBSybtkpAmzXfUxMJHDD5ly3g6ScCcR+3Zf7SKyCfLMGSkwYwiJvvS4sNCtBzwKdDdbEh865T7H5NCS8GOhSt0hxkPPxpbTlXrWXINDiSkF00/b7ZToBRTmK4QIDAQAB",
7
+ "minimum_chrome_version": "116",
8
+ "permissions": ["debugger", "tabs", "tabGroups", "nativeMessaging", "storage", "alarms"],
9
+ "background": { "service_worker": "background.js" },
10
+ "action": { "default_popup": "popup.html", "default_title": "Shellway", "default_icon": { "16": "icons/icon16.png", "32": "icons/icon32.png" } },
11
+ "icons": { "16": "icons/icon16.png", "32": "icons/icon32.png", "48": "icons/icon48.png", "128": "icons/icon128.png" }
12
+ }
@@ -0,0 +1,39 @@
1
+ <!doctype html>
2
+ <html>
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <style>
6
+ body { font: 13px/1.45 system-ui, -apple-system, "Segoe UI", sans-serif; width: 300px; margin: 0; padding: 14px; color: #1d1d1f; background: #fff; }
7
+ h1 { font-size: 15px; margin: 0 0 10px; display: flex; align-items: center; gap: 8px; }
8
+ h1 img { width: 20px; height: 20px; }
9
+ .row { display: flex; align-items: center; justify-content: space-between; padding: 10px 12px; border: 1px solid #e3e3e6; border-radius: 10px; }
10
+ .status { margin: 10px 0; padding: 8px 10px; border-radius: 8px; background: #f4f4f6; }
11
+ .ok { background: #e7f6ee; color: #0a5c3b; }
12
+ .warn { background: #fff4e0; color: #7a4a00; }
13
+ .note { color: #666; font-size: 12px; margin: 8px 0; }
14
+ textarea { width: 100%; box-sizing: border-box; height: 90px; font: 12px ui-monospace, Consolas, monospace; border: 1px solid #d6d6db; border-radius: 8px; padding: 6px; }
15
+ button { font: inherit; padding: 5px 10px; border-radius: 7px; border: 1px solid #c9c9cf; background: #fafafa; cursor: pointer; }
16
+ .switch { position: relative; width: 42px; height: 24px; }
17
+ .switch input { opacity: 0; width: 0; height: 0; }
18
+ .slider { position: absolute; inset: 0; background: #c9c9cf; border-radius: 24px; transition: .15s; cursor: pointer; }
19
+ .slider:before { content: ""; position: absolute; width: 18px; height: 18px; left: 3px; top: 3px; background: #fff; border-radius: 50%; transition: .15s; }
20
+ input:checked + .slider { background: #0a7d4f; }
21
+ input:checked + .slider:before { transform: translateX(18px); }
22
+ details { margin-top: 10px; }
23
+ summary { cursor: pointer; font-weight: 600; }
24
+ </style>
25
+ </head>
26
+ <body>
27
+ <h1><img src="icons/icon32.png" alt="">Shellway</h1>
28
+ <div class="row"><span>Let my AI use this browser</span><label class="switch"><input id="on" type="checkbox"><span class="slider"></span></label></div>
29
+ <div id="status" class="status">…</div>
30
+ <p class="note">Your AI (ChatGPT, Claude) can open tabs, read pages, click, type and take screenshots here, with the sites you are already signed in to. It never types passwords or card numbers. While it works, the browser shows a "debugging this browser" bar: press <b>Cancel</b> on it to stop and turn Shellway off.</p>
31
+ <details>
32
+ <summary>Blocked sites</summary>
33
+ <p class="note">The AI cannot open or use these sites (and anything under them). One per line.</p>
34
+ <textarea id="blocked"></textarea>
35
+ <div style="display:flex;gap:6px;margin-top:6px"><button id="save">Save</button><button id="reset">Restore defaults</button></div>
36
+ </details>
37
+ <script src="popup.js"></script>
38
+ </body>
39
+ </html>
@@ -0,0 +1,18 @@
1
+ const $ = (id) => document.getElementById(id);
2
+ const send = (msg) => chrome.runtime.sendMessage(msg);
3
+ let blockedShown = false;
4
+ function render(s) {
5
+ $('on').checked = s.enabled;
6
+ const st = $('status');
7
+ st.className = 'status';
8
+ if (!s.enabled) st.textContent = 'Off. Turn it on to let your AI use this browser.';
9
+ else if (s.connected) { st.className = 'status ok'; st.textContent = `Connected to the Shellway app${s.agentVersion ? ` (${s.agentVersion})` : ''}.${s.working ? ' The AI is working in a tab now.' : ''}`; }
10
+ else { st.className = 'status warn'; st.textContent = s.lastError || (s.connecting ? 'Connecting to the Shellway app…' : 'Not connected. Is the Shellway app running on this computer?'); }
11
+ if (!blockedShown) { $('blocked').value = s.blocked.join('\n'); blockedShown = true; }
12
+ }
13
+ const refresh = async () => render(await send({ cmd: 'status' }));
14
+ $('on').addEventListener('change', async (e) => render(await send({ cmd: 'set', enabled: e.target.checked })));
15
+ $('save').addEventListener('click', async () => { blockedShown = false; render(await send({ cmd: 'blocked', list: $('blocked').value })); });
16
+ $('reset').addEventListener('click', async () => { blockedShown = false; render(await send({ cmd: 'reset-blocked' })); });
17
+ refresh();
18
+ setInterval(refresh, 1500);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shellway",
3
- "version": "0.6.9",
3
+ "version": "0.7.0",
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": {
@@ -8,7 +8,8 @@
8
8
  },
9
9
  "files": [
10
10
  "shellway.js",
11
- "README.md"
11
+ "README.md",
12
+ "extension/"
12
13
  ],
13
14
  "engines": {
14
15
  "node": ">=22"
package/shellway.js CHANGED
@@ -2,12 +2,14 @@
2
2
  import { spawn } from 'node:child_process';
3
3
  import { homedir, hostname, platform, release } from 'node:os';
4
4
  import { join, resolve, dirname, basename, sep } from 'node:path';
5
- import { mkdirSync, readFileSync, writeFileSync, chmodSync, existsSync, copyFileSync, rmSync, statSync, realpathSync } from 'node:fs';
5
+ import { mkdirSync, readFileSync, writeFileSync, chmodSync, existsSync, copyFileSync, rmSync, statSync, realpathSync, cpSync } from 'node:fs';
6
6
  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
+ import { createServer as netServer, connect as netConnect } from 'node:net';
10
+ import { randomBytes, timingSafeEqual } from 'node:crypto';
9
11
 
10
- const AGENT_VERSION = '0.6.9'; // keep equal to agent/package.json
12
+ const AGENT_VERSION = '0.7.0'; // keep equal to agent/package.json
11
13
  if (Number(process.versions.node.split('.')[0]) < 22) {
12
14
  console.error(`Shellway needs Node.js 22 or newer (you have ${process.versions.node}). Get it at https://nodejs.org`);
13
15
  process.exit(1);
@@ -642,7 +644,7 @@ function policyCli() {
642
644
  console.log(`Backups before a file is changed: ${q.backups ? `on (${join(CONF_DIR, 'backups')})` : 'off'}`);
643
645
  console.log(`Keep awake while Shellway runs: ${q.keep_awake ? 'on' : 'off'}`);
644
646
  console.log(`Screen, apps, mouse and keyboard: ${q.desktop ? (platform() === 'win32' ? 'ON (the AI can open, switch and close apps, click and type; no screenshots on Windows yet)' : 'ON (the AI can see the screen; apps, mouse and keyboard on Windows)') : 'off'}`);
645
- console.log(`Browser control: ${q.browser ? 'ON (the AI can use its own Shellway browser window: open pages, read, click and type)' : 'off'}`);
647
+ console.log(`Browser control: ${q.browser === 'extension' ? 'ON in your own Edge/Chrome (Shellway extension)' : q.browser ? 'ON (the AI can use its own Shellway browser window: open pages, read, click and type)' : 'off'}`);
646
648
  if (q.allowed_folders.length && q.commands) console.log('Note: commands start inside an allowed folder, but a command can still reach other folders. For a strict lock, also run: shellway policy commands off');
647
649
  console.log('Rules apply right away; no restart needed.');
648
650
  };
@@ -657,6 +659,18 @@ function policyCli() {
657
659
  else if (sub === 'backups' && (val === 'on' || val === 'off')) p.backups = val === 'on';
658
660
  else if (sub === 'keep-awake' && (val === 'on' || val === 'off')) p.keep_awake = val === 'on';
659
661
  else if (sub === 'desktop' && (val === 'on' || val === 'off')) p.desktop = val === 'on';
662
+ else if (sub === 'browser' && val === 'extension') {
663
+ p.browser = 'extension';
664
+ const r = installExtensionHost();
665
+ console.log(`Browser control ON, in YOUR OWN Edge/Chrome through the Shellway extension (your sign-ins are used; banking, trading,
666
+ payment and password sites are blocked in the extension).${r.agentFile.includes('_npx') ? '\nNote: run "npx shellway@beta service install" first so the extension can always reach Shellway.' : ''}
667
+ One-time setup in the browser:
668
+ 1. Open edge://extensions (Edge) or chrome://extensions (Chrome)
669
+ 2. Turn on "Developer mode"
670
+ 3. Click "Load unpacked" and choose the folder: ${r.extDest || '(extension folder missing in this package)'}
671
+ 4. Click the Shellway icon in the toolbar (puzzle piece -> pin it) and turn it on.
672
+ To stop at any time: turn it off in the Shellway icon, press Cancel on the "debugging this browser" bar, or: shellway policy browser off`);
673
+ }
660
674
  else if (sub === 'browser' && (val === 'on' || val === 'off')) {
661
675
  p.browser = val === 'on';
662
676
  if (p.browser) console.log('Browser control ON: when asked, the AI opens its own browser window on this computer (a separate Chrome/Edge profile in ~/.shellway/browser;\nyour normal browser, passwords and cookies are not used). You can watch it and close it at any time. Sites you sign in to there stay signed in.');
@@ -674,6 +688,7 @@ shellway policy backups on|off keep a copy of a file before the AI changes
674
688
  shellway policy keep-awake on|off stop the computer from sleeping while Shellway runs
675
689
  shellway policy desktop on|off let the AI see the screen, open/close apps, click and type (off by default)
676
690
  shellway policy browser on|off let the AI use its own browser window: open pages, read, click, type (off by default)
691
+ shellway policy browser extension let the AI use YOUR Edge/Chrome (your sign-ins) through the Shellway extension
677
692
  shellway policy reset remove all rules`);
678
693
  return;
679
694
  }
@@ -901,6 +916,7 @@ function browserUrl(u) {
901
916
  }
902
917
  let browserPort = null, activeTarget = null;
903
918
  async function cdpJson(path) {
919
+ if (extMode()) return extJson(path);
904
920
  const r = await fetch(`http://127.0.0.1:${browserPort}${path}`, { method: path.startsWith('/json/new') ? 'PUT' : 'GET', signal: AbortSignal.timeout(5000) });
905
921
  if (!r.ok) throw new Error(`The browser answered ${r.status}`);
906
922
  const t = await r.text();
@@ -909,6 +925,7 @@ async function cdpJson(path) {
909
925
  async function browserAlive() { if (!browserPort) return false; try { await cdpJson('/json/version'); return true; } catch { return false; } }
910
926
  function portFile() { try { return Number(readFileSync(join(BROWSER_DIR, 'DevToolsActivePort'), 'utf8').split('\n')[0]) || null; } catch { return null; } }
911
927
  async function ensureBrowser() {
928
+ if (extMode()) { if (!ext.sock) throw new Error(EXT_OFF); return false; }
912
929
  if (await browserAlive()) return false;
913
930
  browserPort = portFile(); // a Shellway browser window left open by an earlier run of the agent
914
931
  if (await browserAlive()) return false;
@@ -936,6 +953,7 @@ async function ensureBrowser() {
936
953
  throw new Error('The browser did not start. Close any open Shellway browser window on the computer and try again.');
937
954
  }
938
955
  async function cdpSession(wsUrl) {
956
+ if (String(wsUrl).startsWith('ext:')) return extSession(String(wsUrl).slice(4));
939
957
  const ws = new WebSocket(wsUrl);
940
958
  await new Promise((ok, no) => { ws.onopen = ok; ws.onerror = () => no(new Error('Could not connect to the browser tab')); });
941
959
  let seq = 0; const pending = new Map();
@@ -952,12 +970,164 @@ async function cdpSession(wsUrl) {
952
970
  });
953
971
  return { send, close: () => { try { ws.close(); } catch {} } };
954
972
  }
973
+ // ---- B2 (20 Nov 2026, 0.7.0): the user's OWN Chrome/Edge through the Shellway browser extension (policy browser extension) ----
974
+ // The extension cannot talk to the network itself: the browser starts "shellway native-host" (native messaging, allowed only
975
+ // for the Shellway extension id) and that helper connects to this agent on 127.0.0.1 with a secret from ~/.shellway that only
976
+ // this user can read. The same DevTools commands as the own-window mode then run through chrome.debugger in the extension.
977
+ // The extension adds its own guards: off until the owner turns it on, blocked sites (banks, trading, payments, passwords),
978
+ // a fixed list of allowed DevTools commands, the browser's "debugging" bar while it works (Cancel = turn off).
979
+ const EXT_BRIDGE = join(CONF_DIR, 'extension-bridge.json');
980
+ const NATIVE_NAME = 'com.getshellway.agent';
981
+ const EXT_IDS = ['cepfcfgajaghchkamfmnhgcelblihndk']; // the unpacked extension (fixed by the key in its manifest)
982
+ 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() };
984
+ const extMode = () => { const p = loadPolicy(); return !!p && p.browser === 'extension'; };
985
+ function extAttach(sock, rest) {
986
+ if (ext.sock && ext.sock !== sock) { try { ext.sock.destroy(); } catch {} }
987
+ ext.sock = sock;
988
+ let buf = rest || '';
989
+ const take = () => {
990
+ let i;
991
+ while ((i = buf.indexOf('\n')) >= 0) {
992
+ const line = buf.slice(0, i); buf = buf.slice(i + 1);
993
+ let m; try { m = JSON.parse(line); } catch { continue; }
994
+ const p = m && m.id !== undefined && ext.pending.get(m.id);
995
+ if (!p) continue;
996
+ ext.pending.delete(m.id); clearTimeout(p.timer);
997
+ m.ok ? p.ok(m.result) : p.no(new Error(m.error || 'The browser extension reported an error'));
998
+ }
999
+ };
1000
+ sock.on('data', (d) => { buf += d.toString('utf8'); take(); });
1001
+ const gone = () => {
1002
+ if (ext.sock !== sock) return;
1003
+ ext.sock = null;
1004
+ 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
+ ext.pending.clear();
1006
+ };
1007
+ sock.on('close', gone); sock.on('error', gone);
1008
+ take();
1009
+ }
1010
+ function extCall(op, args = {}, ms = 30_000) {
1011
+ if (!ext.sock) return Promise.reject(new Error(EXT_OFF));
1012
+ return new Promise((ok, no) => {
1013
+ const id = ++ext.seq;
1014
+ const timer = setTimeout(() => { if (ext.pending.delete(id)) no(new Error(`The browser did not answer (${op}${args.method ? ' ' + args.method : ''})`)); }, ms);
1015
+ ext.pending.set(id, { ok, no, timer });
1016
+ ext.sock.write(JSON.stringify({ id, op, args }) + '\n');
1017
+ });
1018
+ }
1019
+ async function extJson(path) {
1020
+ if (path === '/json/version') return { ok: true };
1021
+ if (path === '/json/list') return (await extCall('list')).map((t) => ({ ...t, webSocketDebuggerUrl: 'ext:' + t.id }));
1022
+ if (path.startsWith('/json/new')) { const q = path.indexOf('?'); return extCall('new', { url: q >= 0 ? decodeURI(path.slice(q + 1)) : 'about:blank' }); }
1023
+ const m = path.match(/^\/json\/(close|activate)\/(.+)$/);
1024
+ if (m) return extCall(m[1], { id: m[2] });
1025
+ throw new Error(`unsupported browser request ${path}`);
1026
+ }
1027
+ const extSession = (id) => ({ send: (method, params = {}, ms = 20_000) => extCall('cdp', { id, method, params }, ms), close: () => {} });
1028
+ // Local endpoint for the native-messaging helper: 127.0.0.1 only, random port, a new random secret every start.
1029
+ function startExtBridge() {
1030
+ const token = randomBytes(24).toString('hex');
1031
+ const srv = netServer((sock) => {
1032
+ let head = '';
1033
+ sock.setNoDelay(true);
1034
+ const t = setTimeout(() => sock.destroy(), 5000);
1035
+ const onHead = (d) => {
1036
+ head += d.toString('utf8');
1037
+ const i = head.indexOf('\n');
1038
+ if (i < 0) { if (head.length > 4096) sock.destroy(); return; }
1039
+ sock.off('data', onHead); clearTimeout(t);
1040
+ let given = '';
1041
+ try { given = String(JSON.parse(head.slice(0, i)).token || ''); } catch {}
1042
+ const a = Buffer.from(given), b = Buffer.from(token);
1043
+ if (a.length !== b.length || !timingSafeEqual(a, b)) { sock.destroy(); return; }
1044
+ extAttach(sock, head.slice(i + 1));
1045
+ };
1046
+ sock.on('data', onHead);
1047
+ sock.on('error', () => {});
1048
+ });
1049
+ srv.on('error', (e) => console.log(`Browser extension link not available: ${e.message}`));
1050
+ srv.listen(0, '127.0.0.1', () => {
1051
+ try {
1052
+ mkdirSync(CONF_DIR, { recursive: true });
1053
+ writeFileSync(EXT_BRIDGE, JSON.stringify({ port: srv.address().port, token, pid: process.pid }), { mode: 0o600 });
1054
+ if (platform() !== 'win32') chmodSync(EXT_BRIDGE, 0o600);
1055
+ } catch (e) { console.log(`Browser extension link not available: ${e.message}`); }
1056
+ });
1057
+ srv.unref();
1058
+ return srv;
1059
+ }
1060
+ // "shellway native-host": started by Chrome/Edge for the extension. Browser side: 4-byte little-endian length + JSON.
1061
+ // Agent side: one JSON per line. The helper only passes messages along.
1062
+ function nativeHost() {
1063
+ const frame = (obj) => { const b = Buffer.from(typeof obj === 'string' ? obj : JSON.stringify(obj), 'utf8'); const h = Buffer.alloc(4); h.writeUInt32LE(b.length, 0); process.stdout.write(Buffer.concat([h, b])); };
1064
+ let info;
1065
+ try { info = JSON.parse(readFileSync(EXT_BRIDGE, 'utf8')); } catch { info = null; }
1066
+ if (!info || !info.port) { frame({ type: 'error', message: 'The Shellway app is not running on this computer.' }); setTimeout(() => process.exit(0), 200); return; }
1067
+ const sock = netConnect(info.port, '127.0.0.1');
1068
+ let up = false;
1069
+ sock.on('connect', () => { up = true; sock.write(JSON.stringify({ token: info.token }) + '\n'); frame({ type: 'hello', version: AGENT_VERSION }); });
1070
+ const bye = (msg) => { if (msg) try { frame({ type: 'error', message: msg }); } catch {} setTimeout(() => process.exit(0), 200); };
1071
+ sock.on('error', () => bye(up ? '' : 'The Shellway app is not running on this computer.'));
1072
+ sock.on('close', () => bye(''));
1073
+ let lb = '';
1074
+ sock.on('data', (d) => { lb += d.toString('utf8'); let i; while ((i = lb.indexOf('\n')) >= 0) { const line = lb.slice(0, i); lb = lb.slice(i + 1); if (line) frame(line); } });
1075
+ let ib = Buffer.alloc(0);
1076
+ process.stdin.on('data', (d) => {
1077
+ ib = Buffer.concat([ib, d]);
1078
+ while (ib.length >= 4) {
1079
+ const n = ib.readUInt32LE(0);
1080
+ if (ib.length < 4 + n) break;
1081
+ const msg = ib.subarray(4, 4 + n).toString('utf8'); ib = ib.subarray(4 + n);
1082
+ sock.write(msg.replace(/\n/g, ' ') + '\n');
1083
+ }
1084
+ });
1085
+ process.stdin.on('end', () => { try { sock.destroy(); } catch {} process.exit(0); });
1086
+ }
1087
+ // Sets up the browser side once: copies the extension to a visible folder and registers the native-messaging helper.
1088
+ function nativeHostTargets(os = platform(), home = homedir()) {
1089
+ if (os === 'win32') return { reg: ['Microsoft\\Edge', 'Google\\Chrome', 'BraveSoftware\\Brave-Browser', 'Chromium'].map((b) => `HKCU\\Software\\${b}\\NativeMessagingHosts\\${NATIVE_NAME}`) };
1090
+ const base = os === 'darwin' ? join(home, 'Library', 'Application Support') : join(home, '.config');
1091
+ const dirs = os === 'darwin' ? ['Google/Chrome', 'Microsoft Edge', 'BraveSoftware/Brave-Browser', 'Chromium'] : ['google-chrome', 'microsoft-edge', 'BraveSoftware/Brave-Browser', 'chromium'];
1092
+ return { dirs: dirs.map((d) => join(base, d, 'NativeMessagingHosts')) };
1093
+ }
1094
+ function nativeHostManifest(launcher) {
1095
+ return { name: NATIVE_NAME, description: 'Shellway: lets the Shellway extension reach the Shellway app on this computer', path: launcher, type: 'stdio', allowed_origins: EXT_IDS.map((id) => `chrome-extension://${id}/`) };
1096
+ }
1097
+ function installExtensionHost() {
1098
+ const os = platform();
1099
+ const here = dirname(fileURLToPath(import.meta.url));
1100
+ const agentFile = existsSync(join(CONF_DIR, 'agent.mjs')) ? join(CONF_DIR, 'agent.mjs') : fileURLToPath(import.meta.url);
1101
+ const extSrc = join(here, 'extension');
1102
+ const extDest = join(homedir(), 'Shellway Extension');
1103
+ if (existsSync(extSrc)) { rmSync(extDest, { recursive: true, force: true }); cpSync(extSrc, extDest, { recursive: true }); }
1104
+ mkdirSync(CONF_DIR, { recursive: true });
1105
+ const launcher = join(CONF_DIR, os === 'win32' ? 'native-host.bat' : 'native-host.sh');
1106
+ writeFileSync(launcher, os === 'win32'
1107
+ ? `@echo off\r\n"${process.execPath}" "${agentFile}" native-host %*\r\n`
1108
+ : `#!/bin/sh\nexec "${process.execPath}" "${agentFile}" native-host "$@"\n`);
1109
+ if (os !== 'win32') chmodSync(launcher, 0o755);
1110
+ const manifest = JSON.stringify(nativeHostManifest(launcher), null, 2);
1111
+ const t = nativeHostTargets(os);
1112
+ if (t.reg) {
1113
+ const mf = join(CONF_DIR, `${NATIVE_NAME}.json`);
1114
+ writeFileSync(mf, manifest);
1115
+ for (const key of t.reg) { try { execFileSync('reg', ['add', key, '/ve', '/t', 'REG_SZ', '/d', mf, '/f'], { stdio: 'ignore' }); } catch {} }
1116
+ } else {
1117
+ for (const d of t.dirs) { try { mkdirSync(d, { recursive: true }); writeFileSync(join(d, `${NATIVE_NAME}.json`), manifest); } catch {} }
1118
+ }
1119
+ return { extDest: existsSync(extDest) ? extDest : null, agentFile };
1120
+ }
1121
+ const extConnected = () => !!ext.sock;
1122
+ export { nativeHostManifest, nativeHostTargets, extJson, extCall, startExtBridge, extConnected, installExtensionHost };
955
1123
  const browserPages = async () => (await cdpJson('/json/list')).filter((t) => t.type === 'page' && !String(t.url).startsWith('devtools:'));
956
1124
  async function currentPage() {
957
1125
  await ensureBrowser();
958
1126
  let list = await browserPages();
959
- if (!list.length) { await cdpJson('/json/new?about:blank'); list = await browserPages(); }
960
- const t = list.find((p) => p.id === activeTarget) || list[0];
1127
+ // In the user's own browser the AI never takes over a tab it did not open or switch to: it starts in a new tab.
1128
+ let t = list.find((p) => p.id === activeTarget) || (extMode() ? null : list[0]);
1129
+ if (!t) { const n = await cdpJson('/json/new?about:blank'); list = await browserPages(); t = list.find((p) => p.id === n.id) || list[0]; }
1130
+ if (!t) throw new Error('No browser tab is open.');
961
1131
  activeTarget = t.id;
962
1132
  return t;
963
1133
  }
@@ -1198,6 +1368,7 @@ async function tokenValid(conf) {
1198
1368
 
1199
1369
  function start() {
1200
1370
  const conf = loadConf();
1371
+ startExtBridge();
1201
1372
  keepAwakeTick();
1202
1373
  setInterval(keepAwakeTick, 60_000);
1203
1374
  const wsUrl = conf.server.replace(/^http/, 'ws') + '/agent';
@@ -1373,4 +1544,5 @@ else if (cmd === 'pair') await pair();
1373
1544
  else if (cmd === 'start') start();
1374
1545
  else if (cmd === 'service') service();
1375
1546
  else if (cmd === 'policy') policyCli();
1547
+ else if (cmd === 'native-host' || String(cmd || '').startsWith('chrome-extension://')) nativeHost();
1376
1548
  else console.log('shellway pair <CODE> [--server URL] [--name NAME]\nshellway start [--readonly]\nshellway service install|uninstall|status [--readonly]\nshellway policy safety rules: allowed folders, blocked commands, backups (shellway policy help)');