shellway 0.0.0-stage → 0.1.1

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.
Files changed (3) hide show
  1. package/README.md +34 -2
  2. package/package.json +12 -4
  3. package/shellway.js +193 -0
package/README.md CHANGED
@@ -1,3 +1,35 @@
1
- # Temporary Holding Version
1
+ # Shellway agent
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Lets ChatGPT, Claude and Cursor work on your own computer through [Shellway](https://getshellway.com).
4
+ Needs Node.js 22 or newer.
5
+
6
+ ## Set up
7
+
8
+ 1. Sign in at https://mcp.getshellway.com/dashboard and press "Generate pairing code".
9
+ 2. On the computer you want to control:
10
+
11
+ ```
12
+ npx shellway pair YOUR-CODE
13
+ npx shellway start
14
+ ```
15
+
16
+ Keep the second command running. Add `--readonly` to `start` so your AI can read files and list folders but cannot write files or run commands.
17
+
18
+ Optional: `--name "Home laptop"` on `pair` sets the computer's name. `--server URL` points at a different relay.
19
+
20
+ ## What it does
21
+
22
+ The agent makes an outbound connection to the Shellway relay. Requests from your AI app are passed to this computer and the result is passed back. File contents and command output are not stored by Shellway.
23
+
24
+ Support: support@getshellway.com
25
+
26
+ ## Keep it running automatically
27
+
28
+ After pairing, run once:
29
+
30
+ npx shellway service install # add --readonly for read-only mode
31
+
32
+ Shellway then starts at login/boot and restarts itself if it stops (Linux: systemd user service, macOS: launchd, Windows: scheduled task). On Linux, if you want it to keep running after you log out: `sudo loginctl enable-linger $USER`.
33
+
34
+ npx shellway service status
35
+ npx shellway service uninstall
package/package.json CHANGED
@@ -1,6 +1,14 @@
1
1
  {
2
2
  "name": "shellway",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Shellway agent: lets ChatGPT, Claude and Cursor work on this computer through the Shellway relay.",
5
+ "type": "module",
6
+ "bin": { "shellway": "./shellway.js" },
7
+ "files": ["shellway.js", "README.md"],
8
+ "engines": { "node": ">=22" },
9
+ "keywords": ["mcp", "remote-mcp", "chatgpt", "claude", "cursor", "ai-agent", "shellway"],
10
+ "homepage": "https://getshellway.com",
11
+ "bugs": { "email": "support@getshellway.com" },
12
+ "author": "Sandeep Kumar Saini",
13
+ "license": "UNLICENSED"
14
+ }
package/shellway.js ADDED
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from 'node:child_process';
3
+ import { homedir, hostname, platform, release } from 'node:os';
4
+ import { join, resolve } from 'node:path';
5
+ import { mkdirSync, readFileSync, writeFileSync, chmodSync, existsSync, copyFileSync, rmSync } from 'node:fs';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { execFileSync } from 'node:child_process';
8
+ import { readFile, writeFile, appendFile, readdir, stat } from 'node:fs/promises';
9
+
10
+ if (Number(process.versions.node.split('.')[0]) < 22) {
11
+ console.error(`Shellway needs Node.js 22 or newer (you have ${process.versions.node}). Get it at https://nodejs.org`);
12
+ process.exit(1);
13
+ }
14
+
15
+ const CONF_DIR = join(process.env.SHELLWAY_HOME || homedir(), '.shellway');
16
+ const CONF = join(CONF_DIR, 'config.json');
17
+ const MAX_OUT = 200_000;
18
+
19
+ const args = process.argv.slice(2);
20
+ const flag = (n) => { const i = args.indexOf(`--${n}`); return i >= 0 ? args[i + 1] : undefined; };
21
+ const has = (n) => args.includes(`--${n}`);
22
+ const cmd = args[0];
23
+
24
+ function loadConf() {
25
+ if (!existsSync(CONF)) { console.error('Not paired yet. Run: shellway pair <CODE> --server <URL>'); process.exit(1); }
26
+ return JSON.parse(readFileSync(CONF, 'utf8'));
27
+ }
28
+
29
+ async function pair() {
30
+ const code = args[1];
31
+ const server = (flag('server') || 'https://mcp.getshellway.com').replace(/\/$/, '');
32
+ if (!code || code.startsWith('--')) { console.error('Usage: shellway pair <CODE> [--server URL] [--name NAME]'); process.exit(1); }
33
+ const r = await fetch(`${server}/agent/pair`, {
34
+ method: 'POST',
35
+ headers: { 'content-type': 'application/json' },
36
+ body: JSON.stringify({ code, name: flag('name') || hostname(), platform: `${platform()} ${release()}` }),
37
+ });
38
+ const body = await r.json().catch(() => ({}));
39
+ if (!r.ok) { console.error('Pairing failed:', body.error || r.status); process.exit(1); }
40
+ mkdirSync(CONF_DIR, { recursive: true });
41
+ writeFileSync(CONF, JSON.stringify({ server, device_token: body.device_token, device_name: body.device_name }, null, 2));
42
+ try { chmodSync(CONF, 0o600); } catch {}
43
+ console.log(`Paired as "${body.device_name}". Now run: shellway start`);
44
+ }
45
+
46
+ // ---------- tool handlers (run on this computer) ----------
47
+ const cap = (s) => (s.length > MAX_OUT ? s.slice(0, MAX_OUT) + `\n…[truncated ${s.length - MAX_OUT} chars]` : s);
48
+
49
+ function runCommand({ command, cwd, timeout_seconds }) {
50
+ return new Promise((done) => {
51
+ const timeout = Math.min(Math.max(Number(timeout_seconds) || 60, 1), 600) * 1000;
52
+ const child = spawn(command, { shell: true, cwd: cwd ? resolve(cwd) : homedir(), env: process.env });
53
+ let stdout = '', stderr = '', timedOut = false;
54
+ const t = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, timeout);
55
+ child.stdout.on('data', (d) => { if (stdout.length < MAX_OUT * 2) stdout += d; });
56
+ child.stderr.on('data', (d) => { if (stderr.length < MAX_OUT * 2) stderr += d; });
57
+ child.on('error', (e) => { clearTimeout(t); done({ stdout, stderr: String(e.message), code: -1 }); });
58
+ child.on('close', (code) => { clearTimeout(t); done({ stdout: cap(stdout), stderr: cap(stderr), code: code ?? -1, timedOut }); });
59
+ });
60
+ }
61
+
62
+ const readonly = has('readonly');
63
+ const handlers = {
64
+ run_command: runCommand,
65
+ async read_file({ path, max_bytes }) {
66
+ const p = resolve(path);
67
+ const buf = await readFile(p);
68
+ const max = Number(max_bytes) || 200_000;
69
+ const s = buf.subarray(0, max).toString('utf8');
70
+ return buf.length > max ? `${s}\n…[truncated, file is ${buf.length} bytes]` : s;
71
+ },
72
+ async write_file({ path, content, append }) {
73
+ const p = resolve(path);
74
+ await (append ? appendFile(p, content) : writeFile(p, content));
75
+ return `Wrote ${Buffer.byteLength(content)} bytes to ${p}`;
76
+ },
77
+ async list_directory({ path }) {
78
+ const p = resolve(path);
79
+ const names = await readdir(p);
80
+ const out = [];
81
+ for (const n of names.slice(0, 1000)) {
82
+ try { const s = await stat(join(p, n)); out.push(`${s.isDirectory() ? 'd' : '-'} ${String(s.size).padStart(10)} ${n}`); }
83
+ catch { out.push(`? ${n}`); }
84
+ }
85
+ return out.join('\n') + (names.length > 1000 ? `\n…[${names.length - 1000} more]` : '');
86
+ },
87
+ };
88
+ const writeMethods = new Set(['run_command', 'write_file']);
89
+
90
+ async function tokenValid(conf) {
91
+ try {
92
+ const r = await fetch(`${conf.server}/agent/check`, { headers: { authorization: `Bearer ${conf.device_token}` } });
93
+ return r.status !== 401;
94
+ } catch { return true; } // network down: keep retrying
95
+ }
96
+
97
+ function start() {
98
+ const conf = loadConf();
99
+ const wsUrl = conf.server.replace(/^http/, 'ws') + '/agent';
100
+ let delay = 1000;
101
+ const connect = async () => {
102
+ if (!(await tokenValid(conf))) { console.error('This device was removed or its token is invalid. Pair again.'); process.exit(1); }
103
+ const ws = new WebSocket(wsUrl, { headers: { authorization: `Bearer ${conf.device_token}` } });
104
+ ws.onopen = () => { delay = 1000; console.log(`Connected as "${conf.device_name}"${readonly ? ' (read-only)' : ''}. Leave this running.`); };
105
+ ws.onmessage = async (ev) => {
106
+ let m; try { m = JSON.parse(String(ev.data)); } catch { return; }
107
+ if (m.type === 'hello' || !m.id) return;
108
+ try {
109
+ if (readonly && writeMethods.has(m.method)) throw new Error('This computer is in read-only mode');
110
+ const h = handlers[m.method];
111
+ if (!h) throw new Error(`unknown method ${m.method}`);
112
+ ws.send(JSON.stringify({ id: m.id, result: await h(m.params || {}) }));
113
+ } catch (e) {
114
+ ws.send(JSON.stringify({ id: m.id, error: e.message }));
115
+ }
116
+ };
117
+ ws.onclose = () => { console.log(`Disconnected. Retrying in ${Math.round(delay / 1000)}s…`); setTimeout(connect, delay); delay = Math.min(delay * 2, 30_000); };
118
+ ws.onerror = () => {};
119
+ };
120
+ connect();
121
+ }
122
+
123
+ // ---- auto-start service (systemd user unit / launchd agent / Windows scheduled task) ----
124
+ const xml = (v) => String(v).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
125
+ function serviceSpec() {
126
+ // Copy ourselves to a stable path so the service survives npx cache cleanup.
127
+ const dest = join(CONF_DIR, 'agent.mjs');
128
+ const argv = [process.execPath, dest, 'start', ...(has('readonly') ? ['--readonly'] : [])];
129
+ return { dest, argv };
130
+ }
131
+ const run = (c, a, opts = {}) => execFileSync(c, a, { stdio: opts.quiet ? 'pipe' : 'inherit', encoding: 'utf8' });
132
+
133
+ function renderService(os, argv) {
134
+ const home = process.env.SHELLWAY_HOME ? `Environment=SHELLWAY_HOME=${process.env.SHELLWAY_HOME}\n` : '';
135
+ if (os === 'linux') return `[Unit]\nDescription=Shellway agent\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\n${home}ExecStart=${argv.map((a) => (/\s/.test(a) ? `"${a}"` : a)).join(' ')}\nRestart=always\nRestartSec=5\n\n[Install]\nWantedBy=default.target\n`;
136
+ if (os === 'darwin') return `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>com.getshellway.agent</string>\n<key>ProgramArguments</key><array>${argv.map((a) => `<string>${xml(a)}</string>`).join('')}</array>\n${process.env.SHELLWAY_HOME ? `<key>EnvironmentVariables</key><dict><key>SHELLWAY_HOME</key><string>${xml(process.env.SHELLWAY_HOME)}</string></dict>\n` : ''}<key>RunAtLoad</key><true/>\n<key>KeepAlive</key><true/>\n<key>StandardOutPath</key><string>${xml(join(CONF_DIR, 'agent.log'))}</string>\n<key>StandardErrorPath</key><string>${xml(join(CONF_DIR, 'agent.log'))}</string>\n</dict></plist>\n`;
137
+ return null;
138
+ }
139
+
140
+ function service() {
141
+ const sub = args[1];
142
+ const os = platform();
143
+ const { dest, argv } = serviceSpec();
144
+ const unitPath = os === 'linux' ? join(homedir(), '.config/systemd/user/shellway.service')
145
+ : os === 'darwin' ? join(homedir(), 'Library/LaunchAgents/com.getshellway.agent.plist') : null;
146
+ if (!['install', 'uninstall', 'status', 'print'].includes(sub)) {
147
+ console.log('shellway service install [--readonly] start Shellway automatically at login / boot\nshellway service uninstall\nshellway service status'); return;
148
+ }
149
+ if (sub === 'print') { console.log(renderService(os, argv) ?? '(Windows uses a scheduled task)'); return; }
150
+ if (!['linux', 'darwin', 'win32'].includes(os)) { console.error(`Auto-start is not supported on ${os}. Use: shellway start`); process.exit(1); }
151
+ if (sub === 'install') {
152
+ loadConf();
153
+ mkdirSync(CONF_DIR, { recursive: true });
154
+ copyFileSync(fileURLToPath(import.meta.url), dest);
155
+ if (os === 'linux') {
156
+ mkdirSync(join(homedir(), '.config/systemd/user'), { recursive: true });
157
+ writeFileSync(unitPath, renderService(os, argv));
158
+ run('systemctl', ['--user', 'daemon-reload']);
159
+ run('systemctl', ['--user', 'enable', '--now', 'shellway.service']);
160
+ try { run('loginctl', ['enable-linger', process.env.USER || ''], { quiet: true }); }
161
+ catch { console.log('Note: to keep running after you log out, ask an admin to run: sudo loginctl enable-linger $USER'); }
162
+ } else if (os === 'darwin') {
163
+ mkdirSync(join(homedir(), 'Library/LaunchAgents'), { recursive: true });
164
+ writeFileSync(unitPath, renderService(os, argv));
165
+ try { run('launchctl', ['unload', unitPath], { quiet: true }); } catch {}
166
+ run('launchctl', ['load', '-w', unitPath]);
167
+ } else {
168
+ const tr = argv.map((a) => `"${a}"`).join(' ');
169
+ run('schtasks', ['/Create', '/F', '/SC', 'ONLOGON', '/RL', 'LIMITED', '/TN', 'Shellway', '/TR', tr]);
170
+ run('schtasks', ['/Run', '/TN', 'Shellway']);
171
+ }
172
+ console.log(`Done. Shellway now starts automatically${has('readonly') ? ' (read-only)' : ''}. Check: shellway service status`);
173
+ } else if (sub === 'uninstall') {
174
+ try {
175
+ if (os === 'linux') { try { run('systemctl', ['--user', 'disable', '--now', 'shellway.service']); } catch {} rmSync(unitPath, { force: true }); try { run('systemctl', ['--user', 'daemon-reload'], { quiet: true }); } catch {} }
176
+ else if (os === 'darwin') { try { run('launchctl', ['unload', '-w', unitPath], { quiet: true }); } catch {} rmSync(unitPath, { force: true }); }
177
+ else { try { run('schtasks', ['/End', '/TN', 'Shellway'], { quiet: true }); } catch {} run('schtasks', ['/Delete', '/F', '/TN', 'Shellway']); }
178
+ } catch (e) { console.error(e.message); process.exit(1); }
179
+ rmSync(dest, { force: true });
180
+ console.log('Auto-start removed. (Your pairing is kept; run "shellway start" to run manually.)');
181
+ } else {
182
+ try {
183
+ if (os === 'linux') run('systemctl', ['--user', 'status', 'shellway.service', '--no-pager', '-n', '5']);
184
+ else if (os === 'darwin') run('launchctl', ['list', 'com.getshellway.agent']);
185
+ else run('schtasks', ['/Query', '/TN', 'Shellway']);
186
+ } catch { console.log('Auto-start is not installed (or not running).'); }
187
+ }
188
+ }
189
+
190
+ if (cmd === 'pair') await pair();
191
+ else if (cmd === 'start') start();
192
+ else if (cmd === 'service') service();
193
+ else console.log('shellway pair <CODE> [--server URL] [--name NAME]\nshellway start [--readonly]\nshellway service install|uninstall|status [--readonly]');