shellway 0.7.6 → 0.7.8
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/manifest.json +1 -1
- package/package.json +1 -1
- package/shellway.js +298 -15
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.8",
|
|
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
|
@@ -5,11 +5,11 @@ import { join, resolve, dirname, basename, sep } from 'node:path';
|
|
|
5
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
|
-
import { readFile, writeFile, appendFile, readdir, stat, lstat, mkdir, rename, cp, rm } from 'node:fs/promises';
|
|
8
|
+
import { readFile, writeFile, appendFile, readdir, stat, lstat, mkdir, rename, cp, rm, open as fsOpen } from 'node:fs/promises';
|
|
9
9
|
import { createServer as netServer, connect as netConnect } from 'node:net';
|
|
10
10
|
import { randomBytes, timingSafeEqual, createHash } from 'node:crypto';
|
|
11
11
|
|
|
12
|
-
const AGENT_VERSION = '0.7.
|
|
12
|
+
const AGENT_VERSION = '0.7.8'; // 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);
|
|
@@ -27,6 +27,26 @@ const flag = (n) => { const i = args.indexOf(`--${n}`); return i >= 0 ? args[i +
|
|
|
27
27
|
const has = (n) => args.includes(`--${n}`);
|
|
28
28
|
const cmd = args[0];
|
|
29
29
|
|
|
30
|
+
// 0.7.6 (customer report 21 Nov: a write_file that failed on a dropped link was sometimes written, sometimes not): files are
|
|
31
|
+
// written to a temporary file next to the target, flushed to disk, then renamed over it — the target is always either
|
|
32
|
+
// the old file or the complete new one. Symbolic links are written through (the link stays a link). If Windows refuses
|
|
33
|
+
// the rename (file locked or read-only), the file is written directly as before.
|
|
34
|
+
async function atomicWrite(p, data) {
|
|
35
|
+
const buf = Buffer.isBuffer(data) ? data : Buffer.from(String(data));
|
|
36
|
+
const sha = createHash('sha256').update(buf).digest('hex').slice(0, 16);
|
|
37
|
+
let st = null; try { st = await lstat(p); } catch {}
|
|
38
|
+
if (st && st.isSymbolicLink()) { await writeFile(p, buf); return { bytes: buf.length, sha }; }
|
|
39
|
+
const tmp = join(dirname(p), `.${basename(p)}.shellway-${randomBytes(4).toString('hex')}.tmp`);
|
|
40
|
+
const fh = await fsOpen(tmp, 'w', st ? st.mode & 0o7777 : 0o666);
|
|
41
|
+
try { await fh.writeFile(buf); await fh.sync(); } finally { await fh.close(); }
|
|
42
|
+
try { await rename(tmp, p); }
|
|
43
|
+
catch (e) {
|
|
44
|
+
try { await rm(tmp, { force: true }); } catch {}
|
|
45
|
+
if (['EPERM', 'EACCES', 'EBUSY', 'EXDEV'].includes(e.code)) await writeFile(p, buf); else throw e;
|
|
46
|
+
}
|
|
47
|
+
return { bytes: buf.length, sha };
|
|
48
|
+
}
|
|
49
|
+
|
|
30
50
|
function loadConf() {
|
|
31
51
|
if (!existsSync(CONF)) { console.error('Not paired yet. Run: shellway pair <CODE> --server <URL>'); process.exit(78); }
|
|
32
52
|
return JSON.parse(readFileSync(CONF, 'utf8'));
|
|
@@ -227,8 +247,9 @@ const handlers = {
|
|
|
227
247
|
},
|
|
228
248
|
async write_file({ path, content, append }) {
|
|
229
249
|
const p = resolve(path);
|
|
230
|
-
|
|
231
|
-
|
|
250
|
+
if (append) { await appendFile(p, content); return `Wrote ${Buffer.byteLength(content)} bytes to ${p}`; }
|
|
251
|
+
const r = await atomicWrite(p, content);
|
|
252
|
+
return `Wrote ${r.bytes} bytes to ${p} (sha256 ${r.sha}; saved in one step: the file is either the old one or this complete new one, never half written)`;
|
|
232
253
|
},
|
|
233
254
|
async edit_block({ path, old_string, new_string, expected_replacements }) {
|
|
234
255
|
const p = resolve(path);
|
|
@@ -260,8 +281,8 @@ const handlers = {
|
|
|
260
281
|
: 'No line contains the start of it. The file may have changed: read it again and copy the text exactly.'}`);
|
|
261
282
|
}
|
|
262
283
|
if (found !== exp) throw new Error(`old_string appears ${found} time(s) but expected_replacements is ${exp}. Nothing changed. Add more surrounding text to make it unique, or set expected_replacements to ${found}.`);
|
|
263
|
-
await
|
|
264
|
-
return `Replaced ${found} occurrence${found === 1 ? '' : 's'} in ${p}`;
|
|
284
|
+
const r = await atomicWrite(p, parts.join(newS));
|
|
285
|
+
return `Replaced ${found} occurrence${found === 1 ? '' : 's'} in ${p} (sha256 ${r.sha}, ${r.bytes} bytes; saved in one step)`;
|
|
265
286
|
},
|
|
266
287
|
async search_files({ path, pattern, mode, max_results, ignore_case }) {
|
|
267
288
|
if (typeof pattern !== 'string' || pattern === '') throw new Error('pattern is required');
|
|
@@ -1486,6 +1507,32 @@ function checkBrowser(method, params) {
|
|
|
1486
1507
|
export { browserUrl, cdpKeyEvents, browserCandidates, redactUrl, redactTitle };
|
|
1487
1508
|
Object.assign(handlers, browserHandlers);
|
|
1488
1509
|
|
|
1510
|
+
// 0.7.6 R9 ("Report a problem" on the dashboard): a short, safe status of this app for the support message — version,
|
|
1511
|
+
// Node.js, system, link state and the app's own connection lines from its log. Never command text, output, files or the
|
|
1512
|
+
// token. Only the relay asks for it (it is not one of the AI app's tools).
|
|
1513
|
+
// 0.7.8: remembers the HTTPS fallback across restarts (see runAgent). Never holds a token.
|
|
1514
|
+
const LINK_STATE = join(CONF_DIR, 'link-state.json');
|
|
1515
|
+
function readLinkState() { try { return JSON.parse(readFileSync(LINK_STATE, 'utf8')) || {}; } catch { return {}; } }
|
|
1516
|
+
function writeLinkState(st) { try { mkdirSync(CONF_DIR, { recursive: true }); writeFileSync(LINK_STATE, JSON.stringify(st)); } catch {} }
|
|
1517
|
+
const linkState = { transport: 'ws', connectedAt: 0, links: 0, lastClose: null, journal: 0, startedAt: Date.now() };
|
|
1518
|
+
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
|
+
handlers.shellway_diagnostics = async () => {
|
|
1520
|
+
const out = [`Shellway app ${AGENT_VERSION} · Node.js ${process.versions.node} · ${platform()} ${release()}`,
|
|
1521
|
+
`Link: ${linkState.transport === 'poll' ? 'HTTPS fallback' : 'WebSocket'}, up ${linkState.connectedAt ? Math.round((Date.now() - linkState.connectedAt) / 1000) + 's' : '?'}; ${linkState.links} links since the app started ${Math.round((Date.now() - linkState.startedAt) / 60000)} min ago; ${linkState.journal} recent requests remembered`];
|
|
1522
|
+
if (linkState.lastClose) out.push('Previous link: ' + JSON.stringify(linkState.lastClose).slice(0, 300));
|
|
1523
|
+
try {
|
|
1524
|
+
const log = join(CONF_DIR, 'agent.log');
|
|
1525
|
+
if (existsSync(log)) {
|
|
1526
|
+
const st = statSync(log), len = Math.min(st.size, 300_000), buf = Buffer.alloc(len), fd = await fsOpen(log, 'r');
|
|
1527
|
+
try { await fd.read(buf, 0, len, st.size - len); } finally { await fd.close(); }
|
|
1528
|
+
const rows = buf.toString('utf8').split(/\r?\n/).filter((l) => STATUS_LINE.test(l));
|
|
1529
|
+
out.push(`Log: ${rows.length} connection lines in the last ${Math.round(len / 1024)} KB; latest:`);
|
|
1530
|
+
for (const l of rows.slice(-25)) out.push(' ' + l.replace(/Bearer\s+\S+/g, 'Bearer ***').slice(0, 220));
|
|
1531
|
+
} else out.push('Log: none (auto-start not installed)');
|
|
1532
|
+
} catch (e) { out.push('Log: ' + e.message); }
|
|
1533
|
+
return out.join('\n').split(homedir()).join('~');
|
|
1534
|
+
};
|
|
1535
|
+
|
|
1489
1536
|
// One entry point for every request from the relay, so it can be tested without a network.
|
|
1490
1537
|
async function dispatch(method, params) {
|
|
1491
1538
|
if (readonly && writeMethods.has(method)) throw new Error('This computer is in read-only mode');
|
|
@@ -1508,6 +1555,87 @@ async function tokenValid(conf) {
|
|
|
1508
1555
|
} catch { return true; } // network down: keep retrying
|
|
1509
1556
|
}
|
|
1510
1557
|
|
|
1558
|
+
// 0.7.6 R5 (customer report 21 Nov: on some Windows PCs an antivirus / VPN / proxy holds or cuts WebSocket links):
|
|
1559
|
+
// the same conversation with Shellway over plain HTTPS requests (long-poll). It looks like a WebSocket to start(), so
|
|
1560
|
+
// keepalives, receipts and reconnects work the same. Messages from Shellway carry a number and are acknowledged on the
|
|
1561
|
+
// next poll, so an answer lost on the way is sent again and a repeat is ignored.
|
|
1562
|
+
export class PollLink {
|
|
1563
|
+
constructor(base, token, version) {
|
|
1564
|
+
this.base = base; this.h = { authorization: `Bearer ${token}`, 'x-shellway-version': version };
|
|
1565
|
+
this.readyState = 0; this.sid = null; this.ack = 0; this.outq = []; this.sending = false; this.ctl = new AbortController();
|
|
1566
|
+
this.onopen = null; this.onmessage = null; this.onclose = null; this.onerror = null;
|
|
1567
|
+
this._open();
|
|
1568
|
+
}
|
|
1569
|
+
get bufferedAmount() { return this.outq.length; }
|
|
1570
|
+
async _req(path, opts, ms) {
|
|
1571
|
+
const c = new AbortController(), t = setTimeout(() => c.abort(), ms), off = () => c.abort();
|
|
1572
|
+
this.ctl.signal.addEventListener('abort', off);
|
|
1573
|
+
try { return await fetch(this.base + path, { ...opts, headers: { ...this.h, ...(opts.headers || {}) }, signal: c.signal }); }
|
|
1574
|
+
finally { clearTimeout(t); this.ctl.signal.removeEventListener('abort', off); }
|
|
1575
|
+
}
|
|
1576
|
+
_fail(e) { try { this.onerror && this.onerror({ message: (e && (e.cause && e.cause.code || e.code || e.message)) || 'error' }); } catch {} }
|
|
1577
|
+
async _open() {
|
|
1578
|
+
try {
|
|
1579
|
+
const r = await this._req('/agent/poll/open', { method: 'POST' }, 15_000);
|
|
1580
|
+
if (!r.ok) return this._end(r.status === 401 ? 4001 : r.status === 429 ? 4003 : 1006, `HTTP ${r.status}`);
|
|
1581
|
+
const j = await r.json(); this.sid = j.sid; this.wait = Number(j.wait) || 25_000;
|
|
1582
|
+
} catch (e) { if (this.readyState === 0) { this._fail(e); this._end(1006, ''); } return; }
|
|
1583
|
+
if (this.readyState !== 0) return;
|
|
1584
|
+
this.readyState = 1;
|
|
1585
|
+
try { this.onopen && this.onopen(); } catch {}
|
|
1586
|
+
this._loop();
|
|
1587
|
+
}
|
|
1588
|
+
async _loop() {
|
|
1589
|
+
let fails = 0;
|
|
1590
|
+
while (this.readyState === 1) {
|
|
1591
|
+
try {
|
|
1592
|
+
const r = await this._req(`/agent/poll?sid=${this.sid}&ack=${this.ack}`, { method: 'GET' }, this.wait + 15_000);
|
|
1593
|
+
if (r.status === 410) return this._end(1006, 'closed by Shellway');
|
|
1594
|
+
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
1595
|
+
const j = await r.json(); fails = 0;
|
|
1596
|
+
for (const x of j.msgs || []) { if (x.s <= this.ack) continue; this.ack = x.s; try { Promise.resolve(this.onmessage && this.onmessage({ data: x.m })).catch(() => {}); } catch {} }
|
|
1597
|
+
if (j.closed) return this._end(1000, 'closed by Shellway');
|
|
1598
|
+
} catch (e) {
|
|
1599
|
+
if (this.readyState !== 1) return;
|
|
1600
|
+
if (++fails >= 3) { this._fail(e); return this._end(1006, ''); }
|
|
1601
|
+
await new Promise((ok) => setTimeout(ok, 1000));
|
|
1602
|
+
}
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
send(text) { if (this.readyState !== 1) throw new Error('not connected'); this.outq.push(String(text)); this._flush(); }
|
|
1606
|
+
async _flush() {
|
|
1607
|
+
if (this.sending) return; this.sending = true;
|
|
1608
|
+
let fails = 0;
|
|
1609
|
+
try {
|
|
1610
|
+
while (this.outq.length && this.readyState === 1) {
|
|
1611
|
+
const batch = this.outq.splice(0, 50);
|
|
1612
|
+
try {
|
|
1613
|
+
const r = await this._req(`/agent/poll/send?sid=${this.sid}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(batch) }, 30_000);
|
|
1614
|
+
if (r.status === 410) { this._end(1006, 'closed by Shellway'); break; }
|
|
1615
|
+
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
1616
|
+
fails = 0;
|
|
1617
|
+
} catch (e) {
|
|
1618
|
+
if (this.readyState !== 1) break;
|
|
1619
|
+
this.outq.unshift(...batch);
|
|
1620
|
+
if (++fails >= 3) { this._fail(e); this._end(1006, ''); break; }
|
|
1621
|
+
await new Promise((ok) => setTimeout(ok, 1000));
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
} finally { this.sending = false; }
|
|
1625
|
+
}
|
|
1626
|
+
close() {
|
|
1627
|
+
if (this.readyState >= 2) return;
|
|
1628
|
+
const sid = this.sid; this.readyState = 3; this.ctl.abort();
|
|
1629
|
+
if (sid) fetch(`${this.base}/agent/poll/close?sid=${sid}`, { method: 'POST', headers: this.h, signal: AbortSignal.timeout(5000) }).catch(() => {});
|
|
1630
|
+
const cb = this.onclose; if (cb) setImmediate(() => { try { cb({ code: 1000, reason: '', wasClean: true }); } catch {} });
|
|
1631
|
+
}
|
|
1632
|
+
_end(code, reason) {
|
|
1633
|
+
if (this.readyState === 3) return;
|
|
1634
|
+
this.readyState = 3; this.ctl.abort();
|
|
1635
|
+
const cb = this.onclose; if (cb) setImmediate(() => { try { cb({ code, reason, wasClean: false }); } catch {} });
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1511
1639
|
function start() {
|
|
1512
1640
|
const conf = loadConf();
|
|
1513
1641
|
startExtBridge();
|
|
@@ -1539,12 +1667,53 @@ function start() {
|
|
|
1539
1667
|
let current = null, lastTick = Date.now(), gen = 0, connectingSince = 0;
|
|
1540
1668
|
let lastMsg = Date.now(), kaSeen = false, cid = null, prevCid = null, why = 'start';
|
|
1541
1669
|
let conn = null, lastClose = null, blockedRuns = 0;
|
|
1670
|
+
// 0.7.6 R5: WebSocket first; if its links keep dropping (4 links in a row under 3 minutes) or Shellway's answers are
|
|
1671
|
+
// blocked twice, use the HTTPS fallback for 30 minutes, then try the WebSocket again. SHELLWAY_TRANSPORT=poll forces it.
|
|
1672
|
+
// 0.7.8 (customer 10396, 22 Nov: a network that freezes every long-lived link ~30 times an hour): if the WebSocket
|
|
1673
|
+
// drops again within a day after the last fallback ended, stay on HTTPS for 24 hours. The choice is kept in
|
|
1674
|
+
// link-state.json, so a restart or reboot does not start the drops again; a WebSocket link that stays up 3+ minutes
|
|
1675
|
+
// clears it.
|
|
1676
|
+
const forced = process.env.SHELLWAY_TRANSPORT === 'poll';
|
|
1677
|
+
const SHORT_POLL_MS = Number(process.env.SHELLWAY_POLL_FOR_MS) || 30 * 60_000;
|
|
1678
|
+
const LONG_POLL_MS = Number(process.env.SHELLWAY_POLL_LONG_MS) || 24 * 3600_000;
|
|
1679
|
+
const saved = forced ? {} : readLinkState();
|
|
1680
|
+
let transport = forced ? 'poll' : 'ws', pollUntil = 0, shortRuns = 0, lastFallbackEnd = Number(saved.lastFallbackEnd) || 0;
|
|
1681
|
+
if (!forced && Number(saved.pollUntil) > Date.now()) {
|
|
1682
|
+
transport = 'poll'; pollUntil = Number(saved.pollUntil);
|
|
1683
|
+
console.log(`Using the HTTPS fallback until ${new Date(pollUntil).toISOString().slice(0, 16).replace('T', ' ')} UTC (the WebSocket link kept dropping on this network).`);
|
|
1684
|
+
}
|
|
1685
|
+
const useFallback = (reason) => {
|
|
1686
|
+
if (transport === 'poll') return;
|
|
1687
|
+
const again = lastFallbackEnd > 0 && Date.now() - lastFallbackEnd < 24 * 3600_000;
|
|
1688
|
+
transport = 'poll'; pollUntil = Date.now() + (again ? LONG_POLL_MS : SHORT_POLL_MS); shortRuns = 0;
|
|
1689
|
+
delay = 1000; // connect over HTTPS right away, not after the grown WebSocket retry delay
|
|
1690
|
+
writeLinkState({ pollUntil, lastFallbackEnd, reason, at: Date.now() });
|
|
1691
|
+
console.log(`Switching to the HTTPS fallback for ${again ? '24 hours' : '30 minutes'} (${reason}${again ? '; it dropped again after the last retry' : ''}). Shellway keeps working; this is slower but gets through antivirus/VPN filters.`);
|
|
1692
|
+
};
|
|
1693
|
+
const linkEnded = (opened, secs) => {
|
|
1694
|
+
if (transport !== 'ws') return;
|
|
1695
|
+
if (!opened || secs < 180) { if (++shortRuns >= 4) useFallback('the WebSocket link keeps dropping'); }
|
|
1696
|
+
else { shortRuns = 0; if (lastFallbackEnd) { lastFallbackEnd = 0; writeLinkState({}); } }
|
|
1697
|
+
};
|
|
1698
|
+
// 0.7.6 receipts (customer report 21 Nov): every request from Shellway has an id. This agent remembers the recent ones
|
|
1699
|
+
// (BOOT identifies this process). If a link drops and Shellway sends the same id again on the new link, a finished
|
|
1700
|
+
// request gets its stored answer, a running one answers when it finishes, and nothing ever runs twice.
|
|
1701
|
+
const BOOT = randomBytes(6).toString('hex');
|
|
1702
|
+
const journal = new Map(); // id -> { done, reply, at }
|
|
1703
|
+
const remember = (id) => {
|
|
1704
|
+
const rec = { done: false, reply: null, at: Date.now() };
|
|
1705
|
+
journal.set(id, rec);
|
|
1706
|
+
if (journal.size > 300) for (const [k, v] of journal) { if (journal.size <= 200) break; if (v.done) journal.delete(k); }
|
|
1707
|
+
return rec;
|
|
1708
|
+
};
|
|
1709
|
+
const sendNow = (text, fallback) => { const w = current && current.readyState === 1 ? current : fallback; try { w.send(text); if (conn && w === current) conn.tx++; } catch {} };
|
|
1542
1710
|
const clean = (x) => String(x || '').replace(/Bearer\s+\S+/gi, 'Bearer ***').replace(/[\r\n]+/g, ' ').slice(0, 120);
|
|
1543
1711
|
const summary = (c, extra = {}) => c ? { secs: Math.round((Date.now() - c.openedAt) / 1000), rx: c.rx, ka: c.ka, tx: c.tx, quiet: Math.round((Date.now() - (c.lastRx || c.openedAt)) / 1000), ...extra } : extra;
|
|
1544
1712
|
const reconnectNow = (reason) => {
|
|
1545
1713
|
const w = current; if (!w) return;
|
|
1546
1714
|
current = null; w.onclose = null; w.onmessage = null;
|
|
1547
1715
|
lastClose = summary(conn, { by: 'agent', reason });
|
|
1716
|
+
linkEnded(!!conn, lastClose.secs || 0);
|
|
1548
1717
|
try { w.close(); } catch {}
|
|
1549
1718
|
console.log(`${reason} — reconnecting… (link lived ${lastClose.secs}s, ${lastClose.rx} messages from Shellway, ${lastClose.ka} keepalive answers)`);
|
|
1550
1719
|
why = reason; prevCid = cid; cid = null;
|
|
@@ -1564,6 +1733,7 @@ function start() {
|
|
|
1564
1733
|
// 0.7.6: keepalives went out but Shellway's answers never arrived on this link -> something between is holding them.
|
|
1565
1734
|
if (conn && conn.ka === 0 && conn.tx >= 1 && t - conn.openedAt > NO_REPLY_MS) {
|
|
1566
1735
|
blockedRuns++;
|
|
1736
|
+
if (blockedRuns === 2) useFallback('Shellway\'s answers are blocked on the WebSocket link');
|
|
1567
1737
|
if (blockedRuns === 3) console.error('Shellway\'s answers are not reaching this computer. An antivirus "web protection / HTTPS scanning", VPN or proxy is probably holding them: add mcp.getshellway.com to its exceptions (or pause it) and Shellway will stay connected.');
|
|
1568
1738
|
return reconnectNow('No answers from Shellway on this link');
|
|
1569
1739
|
}
|
|
@@ -1577,13 +1747,16 @@ function start() {
|
|
|
1577
1747
|
const my = ++gen; connectingSince = Date.now();
|
|
1578
1748
|
if (!(await tokenValid(conf))) { console.error('This device was removed or its token is invalid. Pair again.'); process.exit(78); }
|
|
1579
1749
|
if (my !== gen) return; // a newer attempt took over while the check was running
|
|
1580
|
-
|
|
1750
|
+
if (transport === 'poll' && !forced && Date.now() > pollUntil) { transport = 'ws'; shortRuns = 0; blockedRuns = 0; lastFallbackEnd = Date.now(); writeLinkState({ pollUntil: 0, lastFallbackEnd }); console.log('Trying the WebSocket link again.'); }
|
|
1751
|
+
const ws = transport === 'poll' ? new PollLink(conf.server, conf.device_token, AGENT_VERSION)
|
|
1752
|
+
: new WebSocket(wsUrl, { headers: { authorization: `Bearer ${conf.device_token}`, 'x-shellway-version': AGENT_VERSION } });
|
|
1581
1753
|
current = ws;
|
|
1582
1754
|
ws.onopen = () => { if (my !== gen) { try { ws.close(); } catch {} return; } connectingSince = 0; lastMsg = Date.now();
|
|
1583
1755
|
// 0.7.6: the retry delay is reset only after a link has really worked for a minute (see onclose), not on every open.
|
|
1584
1756
|
conn = { openedAt: Date.now(), rx: 0, ka: 0, tx: 0, lastRx: 0, err: '' };
|
|
1585
|
-
try { ws.send(JSON.stringify({ type: 'info', v: AGENT_VERSION, node: process.versions.node, os: platform(), reason: why, ...(machineHash() ? { mid: machineHash() } : {}), ...(prevCid ? { replaced: prevCid } : {}), ...(lastClose ? { last: lastClose } : {}) })); } catch {}
|
|
1586
|
-
|
|
1757
|
+
try { ws.send(JSON.stringify({ type: 'info', v: AGENT_VERSION, node: process.versions.node, os: platform(), reason: why, ...(machineHash() ? { mid: machineHash() } : {}), ...(prevCid ? { replaced: prevCid } : {}), ...(lastClose ? { last: lastClose } : {}), caps: ['receipts'], boot: BOOT, t: transport })); } catch {}
|
|
1758
|
+
linkState.transport = transport; linkState.connectedAt = Date.now(); linkState.links++; linkState.lastClose = lastClose; linkState.journal = journal.size;
|
|
1759
|
+
why = 'network'; prevCid = null; lastClose = null; console.log(`Connected as "${conf.device_name}"${readonly ? ' (read-only)' : ''}${transport === 'poll' ? ' over the HTTPS fallback' : ''}. Leave this running.`); };
|
|
1587
1760
|
ws.onmessage = async (ev) => {
|
|
1588
1761
|
lastMsg = Date.now();
|
|
1589
1762
|
if (conn && current === ws) { conn.rx++; conn.lastRx = lastMsg; }
|
|
@@ -1591,11 +1764,15 @@ function start() {
|
|
|
1591
1764
|
if (m.type === 'ka') { kaSeen = true; if (conn && current === ws) { conn.ka++; blockedRuns = 0; } return; }
|
|
1592
1765
|
if (m.type === 'hello') { if (typeof m.cid === 'string') cid = m.cid; return; }
|
|
1593
1766
|
if (!m.id) return;
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
}
|
|
1767
|
+
const seen = journal.get(m.id);
|
|
1768
|
+
if (seen) { if (seen.done) sendNow(seen.reply, ws); return; } // sent again after a reconnect: never run twice
|
|
1769
|
+
const rec = remember(m.id);
|
|
1770
|
+
let reply;
|
|
1771
|
+
try { reply = JSON.stringify({ id: m.id, result: await dispatch(m.method, m.params) }); }
|
|
1772
|
+
catch (e) { reply = JSON.stringify({ id: m.id, error: e.message }); }
|
|
1773
|
+
linkState.journal = journal.size;
|
|
1774
|
+
rec.done = true; rec.reply = reply.length > 2_000_000 ? JSON.stringify({ id: m.id, error: 'The result was too large to keep for a resend; run the request again.' }) : reply;
|
|
1775
|
+
sendNow(reply, ws); // on the link that is up NOW (the one it came on may have dropped meanwhile)
|
|
1599
1776
|
};
|
|
1600
1777
|
ws.onclose = (ev) => {
|
|
1601
1778
|
if (my !== gen) return;
|
|
@@ -1603,6 +1780,7 @@ function start() {
|
|
|
1603
1780
|
const opened = !!(conn && conn.openedAt);
|
|
1604
1781
|
lastClose = summary(opened ? conn : null, { by: 'close', code: Number(ev && ev.code) || 0, why: clean(ev && ev.reason), clean: !!(ev && ev.wasClean), err: conn ? conn.err : '' });
|
|
1605
1782
|
if (opened && lastClose.secs >= 60) delay = 1000; // the link worked: start again quickly
|
|
1783
|
+
linkEnded(opened, lastClose.secs || 0);
|
|
1606
1784
|
const wait = Math.round(delay * (1 + Math.random() * 0.3));
|
|
1607
1785
|
console.log(`Disconnected (code ${lastClose.code}${lastClose.why ? ' "' + lastClose.why + '"' : ''}, ${lastClose.clean ? 'clean' : 'not clean'}${opened ? `, lived ${lastClose.secs}s, ${lastClose.rx} messages / ${lastClose.ka} keepalive answers from Shellway, last one ${lastClose.quiet}s ago` : ', never opened'}${lastClose.err ? ', error: ' + lastClose.err : ''}). Retrying in ${Math.round(wait / 1000)}s…`);
|
|
1608
1786
|
conn = null;
|
|
@@ -1716,10 +1894,115 @@ function service() {
|
|
|
1716
1894
|
}
|
|
1717
1895
|
}
|
|
1718
1896
|
|
|
1897
|
+
// 0.7.6 R8 (customer report 21 Nov: "reconnect messages alone cannot tell who closed the link"): `shellway doctor`
|
|
1898
|
+
// checks every layer between this computer and Shellway — DNS, HTTPS, who signed the certificate (antivirus HTTPS
|
|
1899
|
+
// scanning shows up here), the device token, a WebSocket round trip, the HTTPS fallback and recent reconnects in the
|
|
1900
|
+
// log — and prints a short report with no token, no file contents and the home folder shortened to ~.
|
|
1901
|
+
export async function doctor(opts = {}) {
|
|
1902
|
+
const conf = opts.conf || (existsSync(CONF) ? JSON.parse(readFileSync(CONF, 'utf8')) : null);
|
|
1903
|
+
const lines = [], problems = [];
|
|
1904
|
+
const t0 = () => Date.now();
|
|
1905
|
+
const add = (okay, text, hint) => { lines.push(`${okay === true ? '✓' : okay === false ? '✗' : '•'} ${text}`); if (okay === false && hint) problems.push(hint); };
|
|
1906
|
+
const within = (p, ms) => Promise.race([p, new Promise((_, no) => setTimeout(() => no(new Error(`no answer in ${ms / 1000}s`)), ms))]);
|
|
1907
|
+
const err = (e) => String((e && (e.cause && (e.cause.code || e.cause.message)) || e.code || e.message) || e).replace(/Bearer\s+\S+/g, 'Bearer ***').slice(0, 120);
|
|
1908
|
+
lines.push(`Shellway doctor ${AGENT_VERSION} — ${new Date().toISOString().slice(0, 19)}Z — ${platform()} ${release()}`);
|
|
1909
|
+
const major = Number(process.versions.node.split('.')[0]);
|
|
1910
|
+
add(major >= 20, `Node.js ${process.versions.node}`, 'Install Node.js 22 or newer from nodejs.org, then run: npx --yes shellway@beta service install');
|
|
1911
|
+
if (!conf || !conf.device_token) { add(false, 'Not paired on this computer', 'Pair it from your Shellway dashboard (Add computer).'); return finish(); }
|
|
1912
|
+
const server = String(conf.server || 'https://mcp.getshellway.com').replace(/\/$/, '');
|
|
1913
|
+
const u = new URL(server);
|
|
1914
|
+
add(true, `Paired as "${conf.device_name || '?'}" with ${u.origin}`);
|
|
1915
|
+
const H = { authorization: `Bearer ${conf.device_token}`, 'x-shellway-version': AGENT_VERSION };
|
|
1916
|
+
// DNS
|
|
1917
|
+
if (!/^(\d+\.){3}\d+$|^localhost$/.test(u.hostname)) {
|
|
1918
|
+
try { const s = t0(); const { lookup } = await import('node:dns/promises'); const a = await within(lookup(u.hostname, { all: true }), 8000); add(true, `DNS ${u.hostname} → ${a.length} address${a.length > 1 ? 'es' : ''} (${Date.now() - s} ms)`); }
|
|
1919
|
+
catch (e) { add(false, `DNS ${u.hostname}: ${err(e)}`, 'This computer cannot look up Shellway\'s address. Check the internet connection or DNS / VPN settings.'); }
|
|
1920
|
+
}
|
|
1921
|
+
// HTTPS
|
|
1922
|
+
try { const s = t0(); const r = await fetch(server + '/healthz', { signal: AbortSignal.timeout(10_000) }); add(r.ok, `HTTPS reachable (${r.status}, ${Date.now() - s} ms)`, 'Shellway\'s website does not answer from this computer: a firewall, proxy or VPN may block it.'); }
|
|
1923
|
+
catch (e) { add(false, `HTTPS: ${err(e)}`, /CERT|SELF_SIGNED|ISSUER/i.test(err(e)) ? 'Something on this computer replaces Shellway\'s security certificate (antivirus "HTTPS scanning" or a company proxy). Add mcp.getshellway.com to its exceptions.' : 'Shellway cannot be reached over HTTPS: a firewall, proxy or VPN may block it.'); }
|
|
1924
|
+
// who signed the certificate
|
|
1925
|
+
if (u.protocol === 'https:') {
|
|
1926
|
+
try {
|
|
1927
|
+
const { connect } = await import('node:tls');
|
|
1928
|
+
const info = await within(new Promise((ok, no) => { const sock = connect({ host: u.hostname, port: Number(u.port) || 443, servername: u.hostname, rejectUnauthorized: false }, () => { const c = sock.getPeerCertificate(); ok({ issuer: (c && c.issuer && (c.issuer.O || c.issuer.CN)) || '?', authorized: sock.authorized }); sock.end(); }); sock.on('error', no); }), 10_000);
|
|
1929
|
+
const clean = /let'?s encrypt|google trust|isrg|amazon|digicert|sectigo|zerossl/i.test(info.issuer);
|
|
1930
|
+
add(clean, `Certificate issued by ${info.issuer}${info.authorized ? '' : ' (not trusted by Node.js)'}`, `"${info.issuer}" is checking Shellway's encrypted traffic (antivirus web protection / HTTPS scanning or a company proxy). This is the most common cause of dropped links: add mcp.getshellway.com to its exceptions or turn HTTPS scanning off for it.`);
|
|
1931
|
+
} catch (e) { add(null, `Certificate check: ${err(e)}`); }
|
|
1932
|
+
}
|
|
1933
|
+
// device token
|
|
1934
|
+
try { const r = await fetch(server + '/agent/check', { headers: H, signal: AbortSignal.timeout(10_000) }); add(r.status !== 401, r.status === 401 ? 'Device token refused (this computer was removed)' : 'Device token accepted', 'This computer was removed from your account. Pair it again from the dashboard.'); }
|
|
1935
|
+
catch (e) { add(null, `Token check: ${err(e)}`); }
|
|
1936
|
+
// WebSocket round trip: hello + two keepalive answers. A request that reaches this test link is refused politely.
|
|
1937
|
+
const wsTest = () => new Promise((ok) => {
|
|
1938
|
+
const res = { hello: false, ka: 0, ms: [], code: null, why: '' }; let sentAt = 0, done = false;
|
|
1939
|
+
const end = () => { if (done) return; done = true; try { w.close(); } catch {} ok(res); };
|
|
1940
|
+
let w; try { w = new WebSocket(server.replace(/^http/, 'ws') + '/agent', { headers: H }); } catch (e) { res.why = err(e); return ok(res); }
|
|
1941
|
+
const timer = setTimeout(end, 12_000);
|
|
1942
|
+
w.onmessage = (ev) => { let m; try { m = JSON.parse(String(ev.data)); } catch { return; }
|
|
1943
|
+
if (m.type === 'hello') { res.hello = true; sentAt = Date.now(); try { w.send('{"type":"keepalive"}'); } catch {} return; }
|
|
1944
|
+
if (m.type === 'ka') { res.ka++; res.ms.push(Date.now() - sentAt); if (res.ka >= 2) { clearTimeout(timer); return end(); } setTimeout(() => { sentAt = Date.now(); try { w.send('{"type":"keepalive"}'); } catch {} }, 3000); return; }
|
|
1945
|
+
if (m.id) { try { w.send(JSON.stringify({ id: m.id, error: 'Shellway is being checked on this computer (shellway doctor). Try again in a few seconds.' })); } catch {} } };
|
|
1946
|
+
w.onclose = (ev) => { res.code = ev && ev.code; res.why = res.why || String((ev && ev.reason) || ''); clearTimeout(timer); end(); };
|
|
1947
|
+
w.onerror = (ev) => { res.why = err((ev && (ev.error || ev.message)) || 'error'); };
|
|
1948
|
+
});
|
|
1949
|
+
const ws = await wsTest();
|
|
1950
|
+
const avg = (a) => (a.length ? Math.round(a.reduce((x, y) => x + y, 0) / a.length) : 0);
|
|
1951
|
+
if (ws.ka >= 2) add(true, `WebSocket: connected, ${ws.ka}/2 answers (avg ${avg(ws.ms)} ms)`);
|
|
1952
|
+
else if (ws.hello) add(false, `WebSocket: connected but ${ws.ka}/2 answers came back`, 'The live link opens but Shellway\'s answers are held on the way — typical for antivirus web protection, a VPN or a proxy. Add mcp.getshellway.com to its exceptions. (Shellway 0.7.7 switches to HTTPS by itself when this happens.)');
|
|
1953
|
+
else add(false, `WebSocket: could not connect${ws.code ? ` (code ${ws.code})` : ''}${ws.why ? ': ' + ws.why : ''}`, 'The live WebSocket link is blocked on this computer or network. Shellway 0.7.7 uses its HTTPS fallback automatically; to use the faster link, allow mcp.getshellway.com in your antivirus / firewall / proxy.');
|
|
1954
|
+
// HTTPS fallback round trip
|
|
1955
|
+
try {
|
|
1956
|
+
const s = t0();
|
|
1957
|
+
const o = await fetch(server + '/agent/poll/open', { method: 'POST', headers: H, signal: AbortSignal.timeout(10_000) });
|
|
1958
|
+
if (!o.ok) throw new Error(`HTTP ${o.status}`);
|
|
1959
|
+
const { sid } = await o.json();
|
|
1960
|
+
let ack = 0, got = false;
|
|
1961
|
+
const p1 = await (await fetch(`${server}/agent/poll?sid=${sid}&ack=0`, { headers: H, signal: AbortSignal.timeout(40_000) })).json();
|
|
1962
|
+
for (const x of p1.msgs || []) ack = Math.max(ack, x.s);
|
|
1963
|
+
await fetch(`${server}/agent/poll/send?sid=${sid}`, { method: 'POST', headers: { ...H, 'content-type': 'application/json' }, body: '["{\\"type\\":\\"keepalive\\"}"]', signal: AbortSignal.timeout(10_000) });
|
|
1964
|
+
const p2 = await (await fetch(`${server}/agent/poll?sid=${sid}&ack=${ack}`, { headers: H, signal: AbortSignal.timeout(40_000) })).json();
|
|
1965
|
+
for (const x of p2.msgs || []) { try { const m = JSON.parse(x.m); if (m.type === 'ka') got = true; if (m.id) await fetch(`${server}/agent/poll/send?sid=${sid}`, { method: 'POST', headers: { ...H, 'content-type': 'application/json' }, body: JSON.stringify([JSON.stringify({ id: m.id, error: 'Shellway is being checked on this computer (shellway doctor). Try again in a few seconds.' })]) }); } catch {} }
|
|
1966
|
+
fetch(`${server}/agent/poll/close?sid=${sid}`, { method: 'POST', headers: H, signal: AbortSignal.timeout(5000) }).catch(() => {});
|
|
1967
|
+
add(got, `HTTPS fallback: ${got ? 'works' : 'no answer'} (${Date.now() - s} ms)`, 'Even plain HTTPS requests to Shellway are held. A firewall or proxy blocks mcp.getshellway.com.');
|
|
1968
|
+
} catch (e) { add(null, `HTTPS fallback: ${err(e)}`); }
|
|
1969
|
+
// the background app's log
|
|
1970
|
+
try {
|
|
1971
|
+
const log = join(CONF_DIR, 'agent.log');
|
|
1972
|
+
if (existsSync(log)) {
|
|
1973
|
+
const st = statSync(log), fd = await fsOpen(log, 'r');
|
|
1974
|
+
const len = Math.min(st.size, 400_000), buf = Buffer.alloc(len);
|
|
1975
|
+
try { await fd.read(buf, 0, len, st.size - len); } finally { await fd.close(); }
|
|
1976
|
+
const rows = buf.toString('utf8').split(/\r?\n/), since = Date.now() - 86_400_000;
|
|
1977
|
+
const stamped = rows.filter((l) => /^\d{4}-\d\d-\d\dT[\d:]{8}Z /.test(l));
|
|
1978
|
+
const recent = stamped.filter((l) => Date.parse(l.slice(0, 20)) >= since);
|
|
1979
|
+
const drops = (stamped.length ? recent : rows).filter((l) => /Disconnected|reconnecting…/.test(l)).length;
|
|
1980
|
+
const fallback = recent.some((l) => /HTTPS fallback/.test(l));
|
|
1981
|
+
add(drops < 30, `Background app log: ${drops} reconnects${stamped.length ? ' in the last 24 h' : ' (whole log)'}${fallback ? ', HTTPS fallback in use' : ''}; last write ${Math.round((Date.now() - st.mtimeMs) / 60000)} min ago`, 'The link to Shellway keeps dropping. Run: npx --yes shellway@beta service install (it reconnects in seconds, resends cut requests and switches to HTTPS by itself), and add mcp.getshellway.com to your antivirus / VPN exceptions.');
|
|
1982
|
+
const last = rows.filter((l) => /Disconnected \(code|reconnecting…/.test(l)).slice(-3);
|
|
1983
|
+
for (const l of last) lines.push(' ' + l.slice(0, 220));
|
|
1984
|
+
} else add(null, 'No background app log on this computer (auto-start not installed?)');
|
|
1985
|
+
} catch (e) { add(null, `Log: ${err(e)}`); }
|
|
1986
|
+
return finish();
|
|
1987
|
+
function finish() {
|
|
1988
|
+
lines.push(problems.length ? `\nProblems found (${problems.length}):\n${[...new Set(problems)].map((p, i) => `${i + 1}. ${p}`).join('\n')}` : '\nResult: everything between this computer and Shellway works.');
|
|
1989
|
+
const home = homedir();
|
|
1990
|
+
const text = lines.join('\n').split(home).join('~').replace(/Bearer\s+\S+/g, 'Bearer ***');
|
|
1991
|
+
return { ok: !problems.length, text };
|
|
1992
|
+
}
|
|
1993
|
+
}
|
|
1994
|
+
async function doctorCli() {
|
|
1995
|
+
const r = await doctor();
|
|
1996
|
+
console.log(r.text);
|
|
1997
|
+
try { writeFileSync(join(CONF_DIR, 'doctor-report.txt'), r.text + '\n'); console.log(`\nSaved to ${join(CONF_DIR, 'doctor-report.txt').split(homedir()).join('~')} — you can send it to hello@getshellway.com (it contains no password or token).`); } catch {}
|
|
1998
|
+
process.exit(r.ok ? 0 : 1);
|
|
1999
|
+
}
|
|
2000
|
+
|
|
1719
2001
|
if (process.env.SHELLWAY_NO_CLI) { /* imported by tests: do not run the command line */ }
|
|
1720
2002
|
else if (cmd === 'pair') await pair();
|
|
1721
2003
|
else if (cmd === 'start') start();
|
|
1722
2004
|
else if (cmd === 'service') service();
|
|
1723
2005
|
else if (cmd === 'policy') policyCli();
|
|
2006
|
+
else if (cmd === 'doctor') await doctorCli();
|
|
1724
2007
|
else if (cmd === 'native-host' || String(cmd || '').startsWith('chrome-extension://')) nativeHost();
|
|
1725
|
-
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)');
|
|
2008
|
+
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)');
|