shellway 0.7.5 → 0.7.7
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 +314 -21
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.7",
|
|
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.7'; // 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,28 @@ 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
|
+
const linkState = { transport: 'ws', connectedAt: 0, links: 0, lastClose: null, journal: 0, startedAt: Date.now() };
|
|
1514
|
+
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/;
|
|
1515
|
+
handlers.shellway_diagnostics = async () => {
|
|
1516
|
+
const out = [`Shellway app ${AGENT_VERSION} · Node.js ${process.versions.node} · ${platform()} ${release()}`,
|
|
1517
|
+
`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`];
|
|
1518
|
+
if (linkState.lastClose) out.push('Previous link: ' + JSON.stringify(linkState.lastClose).slice(0, 300));
|
|
1519
|
+
try {
|
|
1520
|
+
const log = join(CONF_DIR, 'agent.log');
|
|
1521
|
+
if (existsSync(log)) {
|
|
1522
|
+
const st = statSync(log), len = Math.min(st.size, 300_000), buf = Buffer.alloc(len), fd = await fsOpen(log, 'r');
|
|
1523
|
+
try { await fd.read(buf, 0, len, st.size - len); } finally { await fd.close(); }
|
|
1524
|
+
const rows = buf.toString('utf8').split(/\r?\n/).filter((l) => STATUS_LINE.test(l));
|
|
1525
|
+
out.push(`Log: ${rows.length} connection lines in the last ${Math.round(len / 1024)} KB; latest:`);
|
|
1526
|
+
for (const l of rows.slice(-25)) out.push(' ' + l.replace(/Bearer\s+\S+/g, 'Bearer ***').slice(0, 220));
|
|
1527
|
+
} else out.push('Log: none (auto-start not installed)');
|
|
1528
|
+
} catch (e) { out.push('Log: ' + e.message); }
|
|
1529
|
+
return out.join('\n').split(homedir()).join('~');
|
|
1530
|
+
};
|
|
1531
|
+
|
|
1489
1532
|
// One entry point for every request from the relay, so it can be tested without a network.
|
|
1490
1533
|
async function dispatch(method, params) {
|
|
1491
1534
|
if (readonly && writeMethods.has(method)) throw new Error('This computer is in read-only mode');
|
|
@@ -1508,6 +1551,87 @@ async function tokenValid(conf) {
|
|
|
1508
1551
|
} catch { return true; } // network down: keep retrying
|
|
1509
1552
|
}
|
|
1510
1553
|
|
|
1554
|
+
// 0.7.6 R5 (customer report 21 Nov: on some Windows PCs an antivirus / VPN / proxy holds or cuts WebSocket links):
|
|
1555
|
+
// the same conversation with Shellway over plain HTTPS requests (long-poll). It looks like a WebSocket to start(), so
|
|
1556
|
+
// keepalives, receipts and reconnects work the same. Messages from Shellway carry a number and are acknowledged on the
|
|
1557
|
+
// next poll, so an answer lost on the way is sent again and a repeat is ignored.
|
|
1558
|
+
export class PollLink {
|
|
1559
|
+
constructor(base, token, version) {
|
|
1560
|
+
this.base = base; this.h = { authorization: `Bearer ${token}`, 'x-shellway-version': version };
|
|
1561
|
+
this.readyState = 0; this.sid = null; this.ack = 0; this.outq = []; this.sending = false; this.ctl = new AbortController();
|
|
1562
|
+
this.onopen = null; this.onmessage = null; this.onclose = null; this.onerror = null;
|
|
1563
|
+
this._open();
|
|
1564
|
+
}
|
|
1565
|
+
get bufferedAmount() { return this.outq.length; }
|
|
1566
|
+
async _req(path, opts, ms) {
|
|
1567
|
+
const c = new AbortController(), t = setTimeout(() => c.abort(), ms), off = () => c.abort();
|
|
1568
|
+
this.ctl.signal.addEventListener('abort', off);
|
|
1569
|
+
try { return await fetch(this.base + path, { ...opts, headers: { ...this.h, ...(opts.headers || {}) }, signal: c.signal }); }
|
|
1570
|
+
finally { clearTimeout(t); this.ctl.signal.removeEventListener('abort', off); }
|
|
1571
|
+
}
|
|
1572
|
+
_fail(e) { try { this.onerror && this.onerror({ message: (e && (e.cause && e.cause.code || e.code || e.message)) || 'error' }); } catch {} }
|
|
1573
|
+
async _open() {
|
|
1574
|
+
try {
|
|
1575
|
+
const r = await this._req('/agent/poll/open', { method: 'POST' }, 15_000);
|
|
1576
|
+
if (!r.ok) return this._end(r.status === 401 ? 4001 : r.status === 429 ? 4003 : 1006, `HTTP ${r.status}`);
|
|
1577
|
+
const j = await r.json(); this.sid = j.sid; this.wait = Number(j.wait) || 25_000;
|
|
1578
|
+
} catch (e) { if (this.readyState === 0) { this._fail(e); this._end(1006, ''); } return; }
|
|
1579
|
+
if (this.readyState !== 0) return;
|
|
1580
|
+
this.readyState = 1;
|
|
1581
|
+
try { this.onopen && this.onopen(); } catch {}
|
|
1582
|
+
this._loop();
|
|
1583
|
+
}
|
|
1584
|
+
async _loop() {
|
|
1585
|
+
let fails = 0;
|
|
1586
|
+
while (this.readyState === 1) {
|
|
1587
|
+
try {
|
|
1588
|
+
const r = await this._req(`/agent/poll?sid=${this.sid}&ack=${this.ack}`, { method: 'GET' }, this.wait + 15_000);
|
|
1589
|
+
if (r.status === 410) return this._end(1006, 'closed by Shellway');
|
|
1590
|
+
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
1591
|
+
const j = await r.json(); fails = 0;
|
|
1592
|
+
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 {} }
|
|
1593
|
+
if (j.closed) return this._end(1000, 'closed by Shellway');
|
|
1594
|
+
} catch (e) {
|
|
1595
|
+
if (this.readyState !== 1) return;
|
|
1596
|
+
if (++fails >= 3) { this._fail(e); return this._end(1006, ''); }
|
|
1597
|
+
await new Promise((ok) => setTimeout(ok, 1000));
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
}
|
|
1601
|
+
send(text) { if (this.readyState !== 1) throw new Error('not connected'); this.outq.push(String(text)); this._flush(); }
|
|
1602
|
+
async _flush() {
|
|
1603
|
+
if (this.sending) return; this.sending = true;
|
|
1604
|
+
let fails = 0;
|
|
1605
|
+
try {
|
|
1606
|
+
while (this.outq.length && this.readyState === 1) {
|
|
1607
|
+
const batch = this.outq.splice(0, 50);
|
|
1608
|
+
try {
|
|
1609
|
+
const r = await this._req(`/agent/poll/send?sid=${this.sid}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(batch) }, 30_000);
|
|
1610
|
+
if (r.status === 410) { this._end(1006, 'closed by Shellway'); break; }
|
|
1611
|
+
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
1612
|
+
fails = 0;
|
|
1613
|
+
} catch (e) {
|
|
1614
|
+
if (this.readyState !== 1) break;
|
|
1615
|
+
this.outq.unshift(...batch);
|
|
1616
|
+
if (++fails >= 3) { this._fail(e); this._end(1006, ''); break; }
|
|
1617
|
+
await new Promise((ok) => setTimeout(ok, 1000));
|
|
1618
|
+
}
|
|
1619
|
+
}
|
|
1620
|
+
} finally { this.sending = false; }
|
|
1621
|
+
}
|
|
1622
|
+
close() {
|
|
1623
|
+
if (this.readyState >= 2) return;
|
|
1624
|
+
const sid = this.sid; this.readyState = 3; this.ctl.abort();
|
|
1625
|
+
if (sid) fetch(`${this.base}/agent/poll/close?sid=${sid}`, { method: 'POST', headers: this.h, signal: AbortSignal.timeout(5000) }).catch(() => {});
|
|
1626
|
+
const cb = this.onclose; if (cb) setImmediate(() => { try { cb({ code: 1000, reason: '', wasClean: true }); } catch {} });
|
|
1627
|
+
}
|
|
1628
|
+
_end(code, reason) {
|
|
1629
|
+
if (this.readyState === 3) return;
|
|
1630
|
+
this.readyState = 3; this.ctl.abort();
|
|
1631
|
+
const cb = this.onclose; if (cb) setImmediate(() => { try { cb({ code, reason, wasClean: false }); } catch {} });
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1511
1635
|
function start() {
|
|
1512
1636
|
const conf = loadConf();
|
|
1513
1637
|
startExtBridge();
|
|
@@ -1527,13 +1651,49 @@ function start() {
|
|
|
1527
1651
|
// (send-buffer size, timer gaps) are only a fallback for an old relay that never answers. After each new connection the
|
|
1528
1652
|
// agent reports its Node.js version, the reason, and the connection id it left, so the relay drops that one at once.
|
|
1529
1653
|
const TICK = Number(process.env.SHELLWAY_TICK_MS) || 15_000, KA_TIMEOUT = Number(process.env.SHELLWAY_KA_TIMEOUT_MS) || 75_000;
|
|
1654
|
+
// 0.7.6 (customer report 21 Nov: ~2,980 connect/disconnect cycles on Windows, no way to tell why): every log line gets a
|
|
1655
|
+
// UTC time; each closed link logs its close code, reason, wasClean, lifetime and what came back from Shellway, and the
|
|
1656
|
+
// next connection reports that summary to the relay. A link that never gets an answer from Shellway within
|
|
1657
|
+
// NO_REPLY_MS is treated as blocked (antivirus web protection / VPN / proxy) and replaced at once.
|
|
1658
|
+
const NO_REPLY_MS = Number(process.env.SHELLWAY_NO_REPLY_MS) || 20_000;
|
|
1659
|
+
if (!console.__swStamped) {
|
|
1660
|
+
const stamp = (fn) => (...a) => fn(new Date().toISOString().slice(0, 19) + 'Z', ...a);
|
|
1661
|
+
console.log = stamp(console.log.bind(console)); console.error = stamp(console.error.bind(console)); console.__swStamped = true;
|
|
1662
|
+
}
|
|
1530
1663
|
let current = null, lastTick = Date.now(), gen = 0, connectingSince = 0;
|
|
1531
1664
|
let lastMsg = Date.now(), kaSeen = false, cid = null, prevCid = null, why = 'start';
|
|
1665
|
+
let conn = null, lastClose = null, blockedRuns = 0;
|
|
1666
|
+
// 0.7.6 R5: WebSocket first; if its links keep dropping (4 links in a row under 3 minutes) or Shellway's answers are
|
|
1667
|
+
// blocked twice, use the HTTPS fallback for 30 minutes, then try the WebSocket again. SHELLWAY_TRANSPORT=poll forces it.
|
|
1668
|
+
const forced = process.env.SHELLWAY_TRANSPORT === 'poll';
|
|
1669
|
+
let transport = forced ? 'poll' : 'ws', pollUntil = 0, shortRuns = 0;
|
|
1670
|
+
const useFallback = (reason) => {
|
|
1671
|
+
if (transport === 'poll') return;
|
|
1672
|
+
transport = 'poll'; pollUntil = Date.now() + (Number(process.env.SHELLWAY_POLL_FOR_MS) || 30 * 60_000); shortRuns = 0;
|
|
1673
|
+
console.log(`Switching to the HTTPS fallback for 30 minutes (${reason}). Shellway keeps working; this is slower but gets through antivirus/VPN filters.`);
|
|
1674
|
+
};
|
|
1675
|
+
const linkEnded = (opened, secs) => { if (transport !== 'ws') return; if (!opened || secs < 180) { if (++shortRuns >= 4) useFallback('the WebSocket link keeps dropping'); } else shortRuns = 0; };
|
|
1676
|
+
// 0.7.6 receipts (customer report 21 Nov): every request from Shellway has an id. This agent remembers the recent ones
|
|
1677
|
+
// (BOOT identifies this process). If a link drops and Shellway sends the same id again on the new link, a finished
|
|
1678
|
+
// request gets its stored answer, a running one answers when it finishes, and nothing ever runs twice.
|
|
1679
|
+
const BOOT = randomBytes(6).toString('hex');
|
|
1680
|
+
const journal = new Map(); // id -> { done, reply, at }
|
|
1681
|
+
const remember = (id) => {
|
|
1682
|
+
const rec = { done: false, reply: null, at: Date.now() };
|
|
1683
|
+
journal.set(id, rec);
|
|
1684
|
+
if (journal.size > 300) for (const [k, v] of journal) { if (journal.size <= 200) break; if (v.done) journal.delete(k); }
|
|
1685
|
+
return rec;
|
|
1686
|
+
};
|
|
1687
|
+
const sendNow = (text, fallback) => { const w = current && current.readyState === 1 ? current : fallback; try { w.send(text); if (conn && w === current) conn.tx++; } catch {} };
|
|
1688
|
+
const clean = (x) => String(x || '').replace(/Bearer\s+\S+/gi, 'Bearer ***').replace(/[\r\n]+/g, ' ').slice(0, 120);
|
|
1689
|
+
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;
|
|
1532
1690
|
const reconnectNow = (reason) => {
|
|
1533
1691
|
const w = current; if (!w) return;
|
|
1534
1692
|
current = null; w.onclose = null; w.onmessage = null;
|
|
1693
|
+
lastClose = summary(conn, { by: 'agent', reason });
|
|
1694
|
+
linkEnded(!!conn, lastClose.secs || 0);
|
|
1535
1695
|
try { w.close(); } catch {}
|
|
1536
|
-
console.log(`${reason} — reconnecting
|
|
1696
|
+
console.log(`${reason} — reconnecting… (link lived ${lastClose.secs}s, ${lastClose.rx} messages from Shellway, ${lastClose.ka} keepalive answers)`);
|
|
1537
1697
|
why = reason; prevCid = cid; cid = null;
|
|
1538
1698
|
delay = 1000; setTimeout(connect, 500);
|
|
1539
1699
|
};
|
|
@@ -1548,35 +1708,63 @@ function start() {
|
|
|
1548
1708
|
}
|
|
1549
1709
|
const w = current; if (!w || w.readyState !== 1) return;
|
|
1550
1710
|
const quiet = t - lastMsg;
|
|
1711
|
+
// 0.7.6: keepalives went out but Shellway's answers never arrived on this link -> something between is holding them.
|
|
1712
|
+
if (conn && conn.ka === 0 && conn.tx >= 1 && t - conn.openedAt > NO_REPLY_MS) {
|
|
1713
|
+
blockedRuns++;
|
|
1714
|
+
if (blockedRuns === 2) useFallback('Shellway\'s answers are blocked on the WebSocket link');
|
|
1715
|
+
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.');
|
|
1716
|
+
return reconnectNow('No answers from Shellway on this link');
|
|
1717
|
+
}
|
|
1551
1718
|
if (slept && quiet > 30_000) return reconnectNow('Computer woke up');
|
|
1552
1719
|
if (kaSeen) { if (quiet > KA_TIMEOUT) return reconnectNow('No answer from Shellway'); }
|
|
1553
1720
|
// fallback for a relay without keepalive answers. 0.6.5: check the buffer BEFORE sending (right after send() it always holds the new frame)
|
|
1554
1721
|
else if (w.bufferedAmount > 0) { w._stuck = (w._stuck || 0) + 1; if (w._stuck >= 8) return reconnectNow('Connection stuck'); } else w._stuck = 0;
|
|
1555
|
-
try { w.send('{"type":"keepalive"}'); } catch { return reconnectNow('Connection lost'); }
|
|
1722
|
+
try { w.send('{"type":"keepalive"}'); if (conn) conn.tx++; } catch { return reconnectNow('Connection lost'); }
|
|
1556
1723
|
}, TICK);
|
|
1557
1724
|
const connect = async () => {
|
|
1558
1725
|
const my = ++gen; connectingSince = Date.now();
|
|
1559
1726
|
if (!(await tokenValid(conf))) { console.error('This device was removed or its token is invalid. Pair again.'); process.exit(78); }
|
|
1560
1727
|
if (my !== gen) return; // a newer attempt took over while the check was running
|
|
1561
|
-
|
|
1728
|
+
if (transport === 'poll' && !forced && Date.now() > pollUntil) { transport = 'ws'; shortRuns = 0; blockedRuns = 0; console.log('Trying the WebSocket link again.'); }
|
|
1729
|
+
const ws = transport === 'poll' ? new PollLink(conf.server, conf.device_token, AGENT_VERSION)
|
|
1730
|
+
: new WebSocket(wsUrl, { headers: { authorization: `Bearer ${conf.device_token}`, 'x-shellway-version': AGENT_VERSION } });
|
|
1562
1731
|
current = ws;
|
|
1563
|
-
ws.onopen = () => { if (my !== gen) { try { ws.close(); } catch {} return; } connectingSince = 0;
|
|
1564
|
-
|
|
1565
|
-
|
|
1732
|
+
ws.onopen = () => { if (my !== gen) { try { ws.close(); } catch {} return; } connectingSince = 0; lastMsg = Date.now();
|
|
1733
|
+
// 0.7.6: the retry delay is reset only after a link has really worked for a minute (see onclose), not on every open.
|
|
1734
|
+
conn = { openedAt: Date.now(), rx: 0, ka: 0, tx: 0, lastRx: 0, err: '' };
|
|
1735
|
+
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 {}
|
|
1736
|
+
linkState.transport = transport; linkState.connectedAt = Date.now(); linkState.links++; linkState.lastClose = lastClose; linkState.journal = journal.size;
|
|
1737
|
+
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.`); };
|
|
1566
1738
|
ws.onmessage = async (ev) => {
|
|
1567
1739
|
lastMsg = Date.now();
|
|
1740
|
+
if (conn && current === ws) { conn.rx++; conn.lastRx = lastMsg; }
|
|
1568
1741
|
let m; try { m = JSON.parse(String(ev.data)); } catch { return; }
|
|
1569
|
-
if (m.type === 'ka') { kaSeen = true; return; }
|
|
1742
|
+
if (m.type === 'ka') { kaSeen = true; if (conn && current === ws) { conn.ka++; blockedRuns = 0; } return; }
|
|
1570
1743
|
if (m.type === 'hello') { if (typeof m.cid === 'string') cid = m.cid; return; }
|
|
1571
1744
|
if (!m.id) return;
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
}
|
|
1745
|
+
const seen = journal.get(m.id);
|
|
1746
|
+
if (seen) { if (seen.done) sendNow(seen.reply, ws); return; } // sent again after a reconnect: never run twice
|
|
1747
|
+
const rec = remember(m.id);
|
|
1748
|
+
let reply;
|
|
1749
|
+
try { reply = JSON.stringify({ id: m.id, result: await dispatch(m.method, m.params) }); }
|
|
1750
|
+
catch (e) { reply = JSON.stringify({ id: m.id, error: e.message }); }
|
|
1751
|
+
linkState.journal = journal.size;
|
|
1752
|
+
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;
|
|
1753
|
+
sendNow(reply, ws); // on the link that is up NOW (the one it came on may have dropped meanwhile)
|
|
1754
|
+
};
|
|
1755
|
+
ws.onclose = (ev) => {
|
|
1756
|
+
if (my !== gen) return;
|
|
1757
|
+
if (current === ws) current = null; connectingSince = 0; prevCid = cid; cid = null;
|
|
1758
|
+
const opened = !!(conn && conn.openedAt);
|
|
1759
|
+
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 : '' });
|
|
1760
|
+
if (opened && lastClose.secs >= 60) delay = 1000; // the link worked: start again quickly
|
|
1761
|
+
linkEnded(opened, lastClose.secs || 0);
|
|
1762
|
+
const wait = Math.round(delay * (1 + Math.random() * 0.3));
|
|
1763
|
+
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…`);
|
|
1764
|
+
conn = null;
|
|
1765
|
+
setTimeout(connect, wait); delay = Math.min(delay * 2, 30_000);
|
|
1577
1766
|
};
|
|
1578
|
-
ws.
|
|
1579
|
-
ws.onerror = () => {};
|
|
1767
|
+
ws.onerror = (ev) => { const e = clean((ev && (ev.message || (ev.error && (ev.error.code || ev.error.message)))) || 'error'); if (conn && current === ws) conn.err = e; else console.error(`Connection error: ${e}`); };
|
|
1580
1768
|
};
|
|
1581
1769
|
connect();
|
|
1582
1770
|
}
|
|
@@ -1684,10 +1872,115 @@ function service() {
|
|
|
1684
1872
|
}
|
|
1685
1873
|
}
|
|
1686
1874
|
|
|
1875
|
+
// 0.7.6 R8 (customer report 21 Nov: "reconnect messages alone cannot tell who closed the link"): `shellway doctor`
|
|
1876
|
+
// checks every layer between this computer and Shellway — DNS, HTTPS, who signed the certificate (antivirus HTTPS
|
|
1877
|
+
// scanning shows up here), the device token, a WebSocket round trip, the HTTPS fallback and recent reconnects in the
|
|
1878
|
+
// log — and prints a short report with no token, no file contents and the home folder shortened to ~.
|
|
1879
|
+
export async function doctor(opts = {}) {
|
|
1880
|
+
const conf = opts.conf || (existsSync(CONF) ? JSON.parse(readFileSync(CONF, 'utf8')) : null);
|
|
1881
|
+
const lines = [], problems = [];
|
|
1882
|
+
const t0 = () => Date.now();
|
|
1883
|
+
const add = (okay, text, hint) => { lines.push(`${okay === true ? '✓' : okay === false ? '✗' : '•'} ${text}`); if (okay === false && hint) problems.push(hint); };
|
|
1884
|
+
const within = (p, ms) => Promise.race([p, new Promise((_, no) => setTimeout(() => no(new Error(`no answer in ${ms / 1000}s`)), ms))]);
|
|
1885
|
+
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);
|
|
1886
|
+
lines.push(`Shellway doctor ${AGENT_VERSION} — ${new Date().toISOString().slice(0, 19)}Z — ${platform()} ${release()}`);
|
|
1887
|
+
const major = Number(process.versions.node.split('.')[0]);
|
|
1888
|
+
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');
|
|
1889
|
+
if (!conf || !conf.device_token) { add(false, 'Not paired on this computer', 'Pair it from your Shellway dashboard (Add computer).'); return finish(); }
|
|
1890
|
+
const server = String(conf.server || 'https://mcp.getshellway.com').replace(/\/$/, '');
|
|
1891
|
+
const u = new URL(server);
|
|
1892
|
+
add(true, `Paired as "${conf.device_name || '?'}" with ${u.origin}`);
|
|
1893
|
+
const H = { authorization: `Bearer ${conf.device_token}`, 'x-shellway-version': AGENT_VERSION };
|
|
1894
|
+
// DNS
|
|
1895
|
+
if (!/^(\d+\.){3}\d+$|^localhost$/.test(u.hostname)) {
|
|
1896
|
+
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)`); }
|
|
1897
|
+
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.'); }
|
|
1898
|
+
}
|
|
1899
|
+
// HTTPS
|
|
1900
|
+
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.'); }
|
|
1901
|
+
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.'); }
|
|
1902
|
+
// who signed the certificate
|
|
1903
|
+
if (u.protocol === 'https:') {
|
|
1904
|
+
try {
|
|
1905
|
+
const { connect } = await import('node:tls');
|
|
1906
|
+
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);
|
|
1907
|
+
const clean = /let'?s encrypt|google trust|isrg|amazon|digicert|sectigo|zerossl/i.test(info.issuer);
|
|
1908
|
+
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.`);
|
|
1909
|
+
} catch (e) { add(null, `Certificate check: ${err(e)}`); }
|
|
1910
|
+
}
|
|
1911
|
+
// device token
|
|
1912
|
+
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.'); }
|
|
1913
|
+
catch (e) { add(null, `Token check: ${err(e)}`); }
|
|
1914
|
+
// WebSocket round trip: hello + two keepalive answers. A request that reaches this test link is refused politely.
|
|
1915
|
+
const wsTest = () => new Promise((ok) => {
|
|
1916
|
+
const res = { hello: false, ka: 0, ms: [], code: null, why: '' }; let sentAt = 0, done = false;
|
|
1917
|
+
const end = () => { if (done) return; done = true; try { w.close(); } catch {} ok(res); };
|
|
1918
|
+
let w; try { w = new WebSocket(server.replace(/^http/, 'ws') + '/agent', { headers: H }); } catch (e) { res.why = err(e); return ok(res); }
|
|
1919
|
+
const timer = setTimeout(end, 12_000);
|
|
1920
|
+
w.onmessage = (ev) => { let m; try { m = JSON.parse(String(ev.data)); } catch { return; }
|
|
1921
|
+
if (m.type === 'hello') { res.hello = true; sentAt = Date.now(); try { w.send('{"type":"keepalive"}'); } catch {} return; }
|
|
1922
|
+
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; }
|
|
1923
|
+
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 {} } };
|
|
1924
|
+
w.onclose = (ev) => { res.code = ev && ev.code; res.why = res.why || String((ev && ev.reason) || ''); clearTimeout(timer); end(); };
|
|
1925
|
+
w.onerror = (ev) => { res.why = err((ev && (ev.error || ev.message)) || 'error'); };
|
|
1926
|
+
});
|
|
1927
|
+
const ws = await wsTest();
|
|
1928
|
+
const avg = (a) => (a.length ? Math.round(a.reduce((x, y) => x + y, 0) / a.length) : 0);
|
|
1929
|
+
if (ws.ka >= 2) add(true, `WebSocket: connected, ${ws.ka}/2 answers (avg ${avg(ws.ms)} ms)`);
|
|
1930
|
+
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.)');
|
|
1931
|
+
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.');
|
|
1932
|
+
// HTTPS fallback round trip
|
|
1933
|
+
try {
|
|
1934
|
+
const s = t0();
|
|
1935
|
+
const o = await fetch(server + '/agent/poll/open', { method: 'POST', headers: H, signal: AbortSignal.timeout(10_000) });
|
|
1936
|
+
if (!o.ok) throw new Error(`HTTP ${o.status}`);
|
|
1937
|
+
const { sid } = await o.json();
|
|
1938
|
+
let ack = 0, got = false;
|
|
1939
|
+
const p1 = await (await fetch(`${server}/agent/poll?sid=${sid}&ack=0`, { headers: H, signal: AbortSignal.timeout(40_000) })).json();
|
|
1940
|
+
for (const x of p1.msgs || []) ack = Math.max(ack, x.s);
|
|
1941
|
+
await fetch(`${server}/agent/poll/send?sid=${sid}`, { method: 'POST', headers: { ...H, 'content-type': 'application/json' }, body: '["{\\"type\\":\\"keepalive\\"}"]', signal: AbortSignal.timeout(10_000) });
|
|
1942
|
+
const p2 = await (await fetch(`${server}/agent/poll?sid=${sid}&ack=${ack}`, { headers: H, signal: AbortSignal.timeout(40_000) })).json();
|
|
1943
|
+
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 {} }
|
|
1944
|
+
fetch(`${server}/agent/poll/close?sid=${sid}`, { method: 'POST', headers: H, signal: AbortSignal.timeout(5000) }).catch(() => {});
|
|
1945
|
+
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.');
|
|
1946
|
+
} catch (e) { add(null, `HTTPS fallback: ${err(e)}`); }
|
|
1947
|
+
// the background app's log
|
|
1948
|
+
try {
|
|
1949
|
+
const log = join(CONF_DIR, 'agent.log');
|
|
1950
|
+
if (existsSync(log)) {
|
|
1951
|
+
const st = statSync(log), fd = await fsOpen(log, 'r');
|
|
1952
|
+
const len = Math.min(st.size, 400_000), buf = Buffer.alloc(len);
|
|
1953
|
+
try { await fd.read(buf, 0, len, st.size - len); } finally { await fd.close(); }
|
|
1954
|
+
const rows = buf.toString('utf8').split(/\r?\n/), since = Date.now() - 86_400_000;
|
|
1955
|
+
const stamped = rows.filter((l) => /^\d{4}-\d\d-\d\dT[\d:]{8}Z /.test(l));
|
|
1956
|
+
const recent = stamped.filter((l) => Date.parse(l.slice(0, 20)) >= since);
|
|
1957
|
+
const drops = (stamped.length ? recent : rows).filter((l) => /Disconnected|reconnecting…/.test(l)).length;
|
|
1958
|
+
const fallback = recent.some((l) => /HTTPS fallback/.test(l));
|
|
1959
|
+
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.');
|
|
1960
|
+
const last = rows.filter((l) => /Disconnected \(code|reconnecting…/.test(l)).slice(-3);
|
|
1961
|
+
for (const l of last) lines.push(' ' + l.slice(0, 220));
|
|
1962
|
+
} else add(null, 'No background app log on this computer (auto-start not installed?)');
|
|
1963
|
+
} catch (e) { add(null, `Log: ${err(e)}`); }
|
|
1964
|
+
return finish();
|
|
1965
|
+
function finish() {
|
|
1966
|
+
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.');
|
|
1967
|
+
const home = homedir();
|
|
1968
|
+
const text = lines.join('\n').split(home).join('~').replace(/Bearer\s+\S+/g, 'Bearer ***');
|
|
1969
|
+
return { ok: !problems.length, text };
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
async function doctorCli() {
|
|
1973
|
+
const r = await doctor();
|
|
1974
|
+
console.log(r.text);
|
|
1975
|
+
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 {}
|
|
1976
|
+
process.exit(r.ok ? 0 : 1);
|
|
1977
|
+
}
|
|
1978
|
+
|
|
1687
1979
|
if (process.env.SHELLWAY_NO_CLI) { /* imported by tests: do not run the command line */ }
|
|
1688
1980
|
else if (cmd === 'pair') await pair();
|
|
1689
1981
|
else if (cmd === 'start') start();
|
|
1690
1982
|
else if (cmd === 'service') service();
|
|
1691
1983
|
else if (cmd === 'policy') policyCli();
|
|
1984
|
+
else if (cmd === 'doctor') await doctorCli();
|
|
1692
1985
|
else if (cmd === 'native-host' || String(cmd || '').startsWith('chrome-extension://')) nativeHost();
|
|
1693
|
-
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)');
|
|
1986
|
+
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)');
|