shellway 0.8.1 → 0.8.3

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,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Shellway",
4
- "version": "0.8.1",
4
+ "version": "0.8.3",
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.8.1",
3
+ "version": "0.8.3",
4
4
  "description": "Shellway agent: lets ChatGPT, Claude and Cursor work on this computer through the Shellway relay.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -29,5 +29,5 @@
29
29
  },
30
30
  "author": "Sandeep Kumar Saini",
31
31
  "license": "UNLICENSED",
32
- "shellwayStable": "0.7.7"
32
+ "shellwayStable": "0.8.2"
33
33
  }
package/shellway.js CHANGED
@@ -2,14 +2,15 @@
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, cpSync } from 'node:fs';
5
+ import { mkdirSync, readFileSync, writeFileSync, chmodSync, existsSync, copyFileSync, rmSync, statSync, realpathSync, cpSync, renameSync } from 'node:fs';
6
+ import { gunzipSync } from 'node:zlib';
6
7
  import { fileURLToPath } from 'node:url';
7
- import { execFileSync, execFile } from 'node:child_process';
8
+ import { execFileSync, execFile, spawnSync } from 'node:child_process';
8
9
  import { readFile, writeFile, appendFile, readdir, stat, lstat, mkdir, rename, cp, rm, open as fsOpen } from 'node:fs/promises';
9
10
  import { createServer as netServer, connect as netConnect } from 'node:net';
10
11
  import { randomBytes, timingSafeEqual, createHash } from 'node:crypto';
11
12
 
12
- const AGENT_VERSION = '0.8.1'; // keep equal to agent/package.json
13
+ const AGENT_VERSION = '0.8.3'; // keep equal to agent/package.json
13
14
  if (Number(process.versions.node.split('.')[0]) < 22) {
14
15
  console.error(`Shellway needs Node.js 22 or newer (you have ${process.versions.node}). Get it at https://nodejs.org`);
15
16
  process.exit(1);
@@ -1512,9 +1513,110 @@ Object.assign(handlers, browserHandlers);
1512
1513
  // token. Only the relay asks for it (it is not one of the AI app's tools).
1513
1514
  // 0.7.8: remembers the HTTPS fallback across restarts (see runAgent). Never holds a token.
1514
1515
  const LINK_STATE = join(CONF_DIR, 'link-state.json');
1516
+ // 0.8.2 (customer 10396, 23 Nov: "service status" said "not running" on Windows while the agent ran and worked; the
1517
+ // process-list check misses some setups): the running agent writes a small heartbeat (pid, version, link, time) every
1518
+ // tick, and "shellway service status" reads it on every system. No token, no paths, no commands in it.
1519
+ const ALIVE_FILE = join(CONF_DIR, 'agent-alive.json');
1520
+ export function writeAlive(extra = {}) { try { mkdirSync(CONF_DIR, { recursive: true }); writeFileSync(ALIVE_FILE, JSON.stringify({ pid: process.pid, v: AGENT_VERSION, t: Date.now(), ...extra })); } catch {} }
1521
+ export function readAlive(maxAgeMs = 90_000, t = Date.now()) {
1522
+ let a; try { a = JSON.parse(readFileSync(ALIVE_FILE, 'utf8')); } catch { return null; }
1523
+ if (!a || !a.pid || !(t - a.t <= maxAgeMs)) return null;
1524
+ try { process.kill(a.pid, 0); } catch (e) { if (e.code !== 'EPERM') return null; }
1525
+ return a;
1526
+ }
1515
1527
  function readLinkState() { try { return JSON.parse(readFileSync(LINK_STATE, 'utf8')) || {}; } catch { return {}; } }
1516
1528
  function writeLinkState(st) { try { mkdirSync(CONF_DIR, { recursive: true }); writeFileSync(LINK_STATE, JSON.stringify(st)); } catch {} }
1517
1529
  const linkState = { transport: 'ws', connectedAt: 0, links: 0, lastClose: null, journal: 0, startedAt: Date.now() };
1530
+ // ---- 0.8.3: automatic updates (owner 24 Nov 2026) ----
1531
+ // Only the background copy (~/.shellway/agent.mjs, made by "shellway service install") updates itself. Every 6 hours it
1532
+ // asks the npm registry which version is "latest" (the stable channel Shellway sets). If it is newer, it downloads the
1533
+ // package, checks npm's sha512 integrity, takes shellway.js out of it, checks that it parses, keeps the current file as
1534
+ // agent.prev.mjs and restarts (the service starts the new file). It never updates while a command or a background
1535
+ // process is running. After the restart the new version must connect within 3 minutes, or the old file comes back and
1536
+ // that version is skipped. Turn it off: "shellway auto-update off" (or SHELLWAY_NO_AUTO_UPDATE=1).
1537
+ const AU_PENDING = () => join(CONF_DIR, 'update-pending.json'), AU_SKIP = () => join(CONF_DIR, 'update-skip.json'), AU_OFF = () => join(CONF_DIR, 'auto-update-off');
1538
+ export function newerVersion(a, b) { // true when version a is newer than b
1539
+ const p = (v) => String(v || '').split('.').map((n) => parseInt(n, 10) || 0);
1540
+ const x = p(a), y = p(b);
1541
+ for (let i = 0; i < 3; i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) > (y[i] || 0);
1542
+ return false;
1543
+ }
1544
+ export function tarExtract(buf, want) { // one file out of an (uncompressed) tar archive
1545
+ const str = (b) => b.toString('utf8').replace(/\0[\s\S]*$/, '');
1546
+ for (let o = 0; o + 512 <= buf.length;) {
1547
+ const h = buf.subarray(o, o + 512);
1548
+ if (h.every((b) => b === 0)) break;
1549
+ const name = str(h.subarray(0, 100)), pre = str(h.subarray(345, 500)), full = pre ? `${pre}/${name}` : name;
1550
+ const size = parseInt(str(h.subarray(124, 136)).trim() || '0', 8) || 0;
1551
+ if (full === want) return buf.subarray(o + 512, o + 512 + size);
1552
+ o += 512 + Math.ceil(size / 512) * 512;
1553
+ }
1554
+ return null;
1555
+ }
1556
+ export const autoUpdateOff = () => !!process.env.SHELLWAY_NO_AUTO_UPDATE || existsSync(AU_OFF());
1557
+ const runningAsService = () => { try { return fileURLToPath(import.meta.url) === join(CONF_DIR, 'agent.mjs'); } catch { return false; } };
1558
+ export async function fetchUpdate(current, { registry = 'https://registry.npmjs.org/shellway/latest', fetchImpl = fetch } = {}) {
1559
+ const meta = await (await fetchImpl(registry, { signal: AbortSignal.timeout(20_000) })).json();
1560
+ const v = String((meta && meta.version) || '');
1561
+ if (!/^\d+\.\d+\.\d+$/.test(v) || !newerVersion(v, current)) return null;
1562
+ let skip = {}; try { skip = JSON.parse(readFileSync(AU_SKIP(), 'utf8')); } catch {}
1563
+ if (skip.version === v) return null;
1564
+ const tb = meta.dist && meta.dist.tarball, integ = meta.dist && meta.dist.integrity;
1565
+ if (!tb || !String(tb).startsWith('https://registry.npmjs.org/shellway/-/') || !/^sha512-/.test(String(integ || ''))) throw new Error('registry data looks wrong');
1566
+ const tgz = Buffer.from(await (await fetchImpl(tb, { signal: AbortSignal.timeout(120_000) })).arrayBuffer());
1567
+ if ('sha512-' + createHash('sha512').update(tgz).digest('base64') !== integ) throw new Error('integrity check failed');
1568
+ const file = tarExtract(gunzipSync(tgz), 'package/shellway.js');
1569
+ if (!file) throw new Error('shellway.js missing in the package');
1570
+ if (!file.toString('utf8').includes(`const AGENT_VERSION = '${v}'`)) throw new Error('version inside the package does not match');
1571
+ return { version: v, file };
1572
+ }
1573
+ export function applyUpdate(u, from, dir = CONF_DIR) {
1574
+ const dest = join(dir, 'agent.mjs'), tmp = join(dir, 'agent.new.mjs'), prev = join(dir, 'agent.prev.mjs');
1575
+ writeFileSync(tmp, u.file);
1576
+ if (spawnSync(process.execPath, ['--check', tmp], { stdio: 'ignore' }).status !== 0) { rmSync(tmp, { force: true }); throw new Error('the new file does not parse'); }
1577
+ copyFileSync(dest, prev);
1578
+ renameSync(tmp, dest);
1579
+ writeFileSync(join(dir, 'update-pending.json'), JSON.stringify({ from, to: u.version, t: Date.now() }));
1580
+ }
1581
+ function autoUpdateLoop(isBusy) {
1582
+ if (!runningAsService()) return;
1583
+ // after an update: the new version must connect within 3 minutes, otherwise put the old file back
1584
+ let pend = null; try { pend = JSON.parse(readFileSync(AU_PENDING(), 'utf8')); } catch {}
1585
+ if (pend) {
1586
+ if (pend.to !== AGENT_VERSION) { try { rmSync(AU_PENDING(), { force: true }); } catch {} }
1587
+ else setTimeout(() => {
1588
+ if (linkState.connectedAt) { try { rmSync(AU_PENDING(), { force: true }); } catch {} console.log(`Updated automatically from ${pend.from} to ${AGENT_VERSION}.`); return; }
1589
+ try {
1590
+ copyFileSync(join(CONF_DIR, 'agent.prev.mjs'), join(CONF_DIR, 'agent.mjs'));
1591
+ writeFileSync(AU_SKIP(), JSON.stringify({ version: AGENT_VERSION, t: Date.now() }));
1592
+ rmSync(AU_PENDING(), { force: true });
1593
+ console.error(`Version ${AGENT_VERSION} could not connect within 3 minutes; going back to ${pend.from}.`);
1594
+ process.exit(0);
1595
+ } catch (e) { console.error(`Could not go back to the previous version: ${e.message}`); }
1596
+ }, 180_000).unref();
1597
+ }
1598
+ const check = async () => {
1599
+ if (autoUpdateOff()) return;
1600
+ if (isBusy()) { setTimeout(check, 10 * 60_000).unref(); return; } // try again in 10 minutes
1601
+ try {
1602
+ const u = await fetchUpdate(AGENT_VERSION);
1603
+ if (!u || isBusy()) return;
1604
+ applyUpdate(u, AGENT_VERSION);
1605
+ console.log(`Shellway ${u.version} is available; updating from ${AGENT_VERSION} and restarting.`);
1606
+ setTimeout(() => process.exit(0), 500);
1607
+ } catch (e) { console.error(`Automatic update check failed: ${e.message}`); }
1608
+ };
1609
+ setTimeout(check, (15 + Math.floor(Math.random() * 30)) * 60_000).unref(); // first check 15-45 min after start
1610
+ setInterval(check, 6 * 3600_000).unref();
1611
+ }
1612
+ function autoUpdateCli() {
1613
+ const sub = process.argv[3];
1614
+ mkdirSync(CONF_DIR, { recursive: true });
1615
+ if (sub === 'off') { writeFileSync(AU_OFF(), 'off\n'); console.log('Automatic updates are off. Update by hand with: npx shellway@latest service install'); }
1616
+ else if (sub === 'on') { rmSync(AU_OFF(), { force: true }); console.log('Automatic updates are on (only for the background service).'); }
1617
+ else console.log(`Automatic updates: ${autoUpdateOff() ? 'off' : 'on'} (version ${AGENT_VERSION}).\nshellway auto-update on|off`);
1618
+ }
1619
+
1518
1620
  const STATUS_LINE = /Connected as|Disconnected|reconnecting…|Switching to the HTTPS fallback|Trying the WebSocket link again|Connection error|answers are not reaching|Connecting took too long|token is invalid/;
1519
1621
  handlers.shellway_diagnostics = async () => {
1520
1622
  const out = [`Shellway app ${AGENT_VERSION} · Node.js ${process.versions.node} · ${platform()} ${release()}`,
@@ -1719,6 +1821,7 @@ function start() {
1719
1821
  // request gets its stored answer, a running one answers when it finishes, and nothing ever runs twice.
1720
1822
  const BOOT = randomBytes(6).toString('hex');
1721
1823
  const journal = new Map(); // id -> { done, reply, at }
1824
+ autoUpdateLoop(() => [...sessions.values()].some((x) => !x.exited) || [...journal.values()].some((r) => !r.done));
1722
1825
  const remember = (id) => {
1723
1826
  const rec = { done: false, reply: null, at: Date.now() };
1724
1827
  journal.set(id, rec);
@@ -1738,8 +1841,10 @@ function start() {
1738
1841
  why = reason; prevCid = cid; cid = null;
1739
1842
  delay = 1000; setTimeout(connect, 500);
1740
1843
  };
1844
+ writeAlive({ link: 'starting' });
1741
1845
  setInterval(() => {
1742
1846
  const t = Date.now(), slept = t - lastTick > Math.max(45_000, TICK * 3); lastTick = t;
1847
+ writeAlive({ link: linkState.transport === 'poll' ? 'https' : 'websocket', up: !!(current && current.readyState === 1) });
1743
1848
  if (connectingSince && t - connectingSince > 30_000) {
1744
1849
  const w = current; current = null; connectingSince = 0;
1745
1850
  if (w) { w.onopen = null; w.onclose = null; w.onmessage = null; try { w.close(); } catch {} }
@@ -1905,11 +2010,14 @@ function service() {
1905
2010
  else if (os === 'darwin') run('launchctl', ['list', 'com.getshellway.agent']);
1906
2011
  else {
1907
2012
  if (!existsSync(winStartup())) throw new Error('not installed');
1908
- let n = 0;
1909
- try { n = Number(run('powershell', ['-NoProfile', '-Command', `(Get-CimInstance Win32_Process | Where-Object { $_.Name -eq 'node.exe' -and $_.CommandLine -like '*${CONF_DIR.replace(/'/g, "''")}*agent.mjs*' }).Count`], { quiet: true }).trim()) || 0; } catch {}
2013
+ let n = readAlive() ? 1 : 0;
2014
+ if (!n) try { n = Number(run('powershell', ['-NoProfile', '-Command', `(Get-CimInstance Win32_Process | Where-Object { $_.Name -eq 'node.exe' -and $_.CommandLine -like '*${CONF_DIR.replace(/'/g, "''")}*agent.mjs*' }).Count`], { quiet: true }).trim()) || 0; } catch {}
1910
2015
  console.log(`Auto-start installed (${winStartup()}). Background agent: ${n > 0 ? 'running' : 'not running - log out and in, or run the install again'}. Log: ${join(CONF_DIR, 'agent.log')}`);
1911
2016
  }
1912
2017
  } catch { console.log('Auto-start is not installed (or not running).'); }
2018
+ const a = readAlive();
2019
+ console.log(a ? `Running agent: version ${a.v}, process ${a.pid}, link ${a.link || '?'}${a.up === false ? ' (reconnecting)' : ''}, last heartbeat ${Math.round((Date.now() - a.t) / 1000)} s ago`
2020
+ : 'Running agent: no heartbeat in the last 90 s (the agent is not running, or it is older than 0.8.2)');
1913
2021
  }
1914
2022
  }
1915
2023
 
@@ -2028,5 +2136,6 @@ else if (cmd === 'start') start();
2028
2136
  else if (cmd === 'service') service();
2029
2137
  else if (cmd === 'policy') policyCli();
2030
2138
  else if (cmd === 'doctor') await doctorCli();
2139
+ else if (cmd === 'auto-update') autoUpdateCli();
2031
2140
  else if (cmd === 'native-host' || String(cmd || '').startsWith('chrome-extension://')) nativeHost();
2032
2141
  else console.log('shellway pair <CODE> [--server URL] [--name NAME]\nshellway start [--readonly]\nshellway doctor check the connection to Shellway and print a report\nshellway service install|uninstall|status [--readonly]\nshellway policy safety rules: allowed folders, blocked commands, backups (shellway policy help)');