shellway 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +22 -1
  2. package/package.json +1 -1
  3. package/shellway.js +255 -7
package/README.md CHANGED
@@ -13,10 +13,31 @@ npx shellway pair YOUR-CODE
13
13
  npx shellway start
14
14
  ```
15
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.
16
+ Keep the second command running. Add `--readonly` to `start` so your AI can read, search and list files but cannot write, edit, move or create anything and cannot run commands.
17
17
 
18
18
  Optional: `--name "Home laptop"` on `pair` sets the computer's name. `--server URL` points at a different relay.
19
19
 
20
+ ## What your AI can do
21
+
22
+ | Tool | What it does | Blocked in `--readonly` |
23
+ |---|---|---|
24
+ | `run_command` | Run a shell command and get its output | yes |
25
+ | `read_file`, `read_multiple_files` | Read text files (up to 20 at once) | no |
26
+ | `write_file` | Create, overwrite or append to a file | yes |
27
+ | `edit_block` | Replace exact text in a file; changes nothing if the text is missing or ambiguous | yes |
28
+ | `search_files` | Find files by name, or text inside files (skips node_modules, .git, binary files) | no |
29
+ | `list_directory`, `get_file_info` | List a folder; show size, dates and permissions | no |
30
+ | `move_file` | Move or rename; never overwrites an existing file | yes |
31
+ | `create_directory` | Create a folder | yes |
32
+ | `start_process`, `interact_with_process` | Start a program that keeps running (dev server, Python or Node shell, `ssh`) and type into it | yes |
33
+ | `read_process_output`, `list_sessions` | See what a background program printed; list the ones Shellway started | no |
34
+ | `force_terminate` | Stop a program Shellway started | yes |
35
+ | `list_processes` | Show the programs running on the computer, busiest first | no |
36
+
37
+ Background programs have limits: at most 5 at a time, a program nobody touches for 30 minutes is stopped, only the last 1 MB of output is kept, and everything is stopped when the agent stops. There is no terminal, so full-screen programs and password prompts do not work (use SSH keys).
38
+
39
+ Your AI app asks you before using a tool, and the agent only ever acts as the user it runs under. For anything you try with an AI, run the agent as a normal user without sudo rights, not as root.
40
+
20
41
  ## What it does
21
42
 
22
43
  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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shellway",
3
- "version": "0.1.2",
3
+ "version": "0.3.0",
4
4
  "description": "Shellway agent: lets ChatGPT, Claude and Cursor work on this computer through the Shellway relay.",
5
5
  "type": "module",
6
6
  "bin": { "shellway": "./shellway.js" },
package/shellway.js CHANGED
@@ -5,7 +5,7 @@ import { join, resolve } from 'node:path';
5
5
  import { mkdirSync, readFileSync, writeFileSync, chmodSync, existsSync, copyFileSync, rmSync } from 'node:fs';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { execFileSync } from 'node:child_process';
8
- import { readFile, writeFile, appendFile, readdir, stat } from 'node:fs/promises';
8
+ import { readFile, writeFile, appendFile, readdir, stat, lstat, mkdir, rename, cp, rm } from 'node:fs/promises';
9
9
 
10
10
  if (Number(process.versions.node.split('.')[0]) < 22) {
11
11
  console.error(`Shellway needs Node.js 22 or newer (you have ${process.versions.node}). Get it at https://nodejs.org`);
@@ -15,6 +15,9 @@ if (Number(process.versions.node.split('.')[0]) < 22) {
15
15
  const CONF_DIR = join(process.env.SHELLWAY_HOME || homedir(), '.shellway');
16
16
  const CONF = join(CONF_DIR, 'config.json');
17
17
  const MAX_OUT = 200_000;
18
+ const MAX_EDIT_BYTES = 10_000_000; // edit_block refuses bigger files
19
+ const MAX_SEARCH_FILE = 2_000_000; // search_files skips bigger files in content mode
20
+ const SKIP_DIRS = new Set(['node_modules', '.git', '.hg', '.svn']);
18
21
 
19
22
  const args = process.argv.slice(2);
20
23
  const flag = (n) => { const i = args.indexOf(`--${n}`); return i >= 0 ? args[i + 1] : undefined; };
@@ -59,6 +62,69 @@ function runCommand({ command, cwd, timeout_seconds }) {
59
62
  });
60
63
  }
61
64
 
65
+ // ---------- background sessions: start_process, interact_with_process, read_process_output ... ----------
66
+ const MAX_SESSIONS = 5; // running at the same time
67
+ const SESSION_BUF = 1_000_000; // characters of output kept per session (oldest dropped)
68
+ const SESSION_IDLE_MS = 30 * 60_000; // a session nobody reads or writes for 30 minutes is stopped
69
+ const sessions = new Map();
70
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
71
+ const clampMs = (v, def, max) => { const n = Number(v); return Math.min(Math.max(v === undefined || v === null || v === '' || !Number.isFinite(n) ? def : n, 0), max); };
72
+
73
+ function killSession(s, force) {
74
+ if (s.exited) return;
75
+ try {
76
+ if (platform() === 'win32') spawn('taskkill', ['/pid', String(s.child.pid), '/T', '/F']);
77
+ else process.kill(-s.child.pid, force ? 'SIGKILL' : 'SIGTERM'); // whole process group
78
+ } catch { try { s.child.kill(force ? 'SIGKILL' : 'SIGTERM'); } catch {} }
79
+ }
80
+ function killAllSessions() { for (const s of sessions.values()) killSession(s, true); }
81
+ process.on('exit', killAllSessions);
82
+ for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => { killAllSessions(); process.exit(0); });
83
+ const sweeper = setInterval(() => {
84
+ const now = Date.now();
85
+ for (const [id, s] of sessions) {
86
+ if (!s.exited && now - s.last > SESSION_IDLE_MS) killSession(s, true);
87
+ if (s.exited && now - s.last > 10 * 60_000) sessions.delete(id);
88
+ }
89
+ }, 60_000);
90
+ sweeper.unref();
91
+
92
+ function getSession(pid) {
93
+ const s = sessions.get(Number(pid));
94
+ if (!s) throw new Error(`No session with pid ${pid}. Use list_sessions to see what is running.`);
95
+ s.last = Date.now();
96
+ return s;
97
+ }
98
+ function takeOutput(s) {
99
+ const dropped = s.readPos < s.base;
100
+ const text = s.out.slice(Math.max(s.readPos - s.base, 0));
101
+ s.readPos = s.base + s.out.length;
102
+ return (dropped ? '…[older output was dropped]\n' : '') + text;
103
+ }
104
+ async function waitOutput(s, waitMs) {
105
+ const start = Date.now(), startLen = s.base + s.out.length;
106
+ let seen = startLen, last = start;
107
+ while (!s.exited && Date.now() - start < waitMs) {
108
+ await sleep(50);
109
+ const len = s.base + s.out.length;
110
+ if (len !== seen) { seen = len; last = Date.now(); }
111
+ else if (seen > startLen && Date.now() - last >= 300) break; // output arrived and went quiet
112
+ }
113
+ }
114
+ const sessionState = (s) => (s.exited ? `exited (${s.signal ? 'signal ' + s.signal : 'code ' + s.code})` : 'running');
115
+ const sessionReply = (s) => `pid: ${s.id}\nstatus: ${sessionState(s)}\n--- new output ---\n${cap(takeOutput(s))}`;
116
+
117
+ function capture(cmd, cmdArgs, ms = 10_000) {
118
+ return new Promise((done, fail) => {
119
+ const c = spawn(cmd, cmdArgs);
120
+ let out = '';
121
+ const t = setTimeout(() => { c.kill('SIGKILL'); fail(new Error(`${cmd} timed out`)); }, ms);
122
+ c.stdout.on('data', (d) => { if (out.length < 2_000_000) out += d; });
123
+ c.on('error', (e) => { clearTimeout(t); fail(e); });
124
+ c.on('close', () => { clearTimeout(t); done(out); });
125
+ });
126
+ }
127
+
62
128
  const readonly = has('readonly');
63
129
  const handlers = {
64
130
  run_command: runCommand,
@@ -74,6 +140,181 @@ const handlers = {
74
140
  await (append ? appendFile(p, content) : writeFile(p, content));
75
141
  return `Wrote ${Buffer.byteLength(content)} bytes to ${p}`;
76
142
  },
143
+ async edit_block({ path, old_string, new_string, expected_replacements }) {
144
+ const p = resolve(path);
145
+ if (typeof old_string !== 'string' || old_string === '') throw new Error('old_string must be a non-empty string');
146
+ if (typeof new_string !== 'string') throw new Error('new_string must be a string');
147
+ const exp = expected_replacements === undefined ? 1 : Number(expected_replacements);
148
+ if (!Number.isInteger(exp) || exp < 1) throw new Error('expected_replacements must be a whole number of 1 or more');
149
+ const st = await stat(p);
150
+ if (!st.isFile()) throw new Error('Not a regular file');
151
+ if (st.size > MAX_EDIT_BYTES) throw new Error(`File is too large to edit (${st.size} bytes, limit ${MAX_EDIT_BYTES})`);
152
+ const buf = await readFile(p);
153
+ if (buf.subarray(0, 8000).includes(0)) throw new Error('This looks like a binary file; edit_block only edits text files');
154
+ const parts = buf.toString('utf8').split(old_string);
155
+ const found = parts.length - 1;
156
+ if (found === 0) throw new Error('old_string was not found in the file. Nothing changed.');
157
+ 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}.`);
158
+ await writeFile(p, parts.join(new_string));
159
+ return `Replaced ${found} occurrence${found === 1 ? '' : 's'} in ${p}`;
160
+ },
161
+ async search_files({ path, pattern, mode, max_results, ignore_case }) {
162
+ if (typeof pattern !== 'string' || pattern === '') throw new Error('pattern is required');
163
+ const m = mode || 'name';
164
+ if (m !== 'name' && m !== 'content') throw new Error('mode must be "name" or "content"');
165
+ const root = resolve(path);
166
+ const limit = Math.min(Math.max(Math.floor(Number(max_results)) || 100, 1), 500);
167
+ const icase = ignore_case !== false;
168
+ const deadline = Date.now() + 20_000;
169
+ let nameRe = null, needle = icase ? pattern.toLowerCase() : pattern;
170
+ if (m === 'name' && /[*?]/.test(pattern)) {
171
+ const esc = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.');
172
+ nameRe = new RegExp(`^${esc}$`, icase ? 'i' : '');
173
+ }
174
+ const out = [];
175
+ let note = '';
176
+ const stack = [[root, 0]];
177
+ walk: while (stack.length) {
178
+ const [dir, depth] = stack.pop();
179
+ let entries;
180
+ try { entries = await readdir(dir, { withFileTypes: true }); } catch { continue; }
181
+ entries.sort((a, b) => a.name.localeCompare(b.name));
182
+ for (const e of entries) {
183
+ if (Date.now() > deadline) { note = '\n…[stopped after 20 seconds, results may be incomplete]'; break walk; }
184
+ const full = join(dir, e.name);
185
+ if (e.isSymbolicLink()) continue;
186
+ if (e.isDirectory()) {
187
+ if (SKIP_DIRS.has(e.name) || depth >= 12) continue;
188
+ if (m === 'name' && (nameRe ? nameRe.test(e.name) : (icase ? e.name.toLowerCase() : e.name).includes(needle))) out.push(`d ${full}`);
189
+ stack.push([full, depth + 1]);
190
+ } else if (e.isFile()) {
191
+ if (m === 'name') {
192
+ if (nameRe ? nameRe.test(e.name) : (icase ? e.name.toLowerCase() : e.name).includes(needle)) out.push(`- ${full}`);
193
+ } else {
194
+ let st; try { st = await stat(full); } catch { continue; }
195
+ if (st.size > MAX_SEARCH_FILE) continue;
196
+ let buf; try { buf = await readFile(full); } catch { continue; }
197
+ if (buf.subarray(0, 8000).includes(0)) continue;
198
+ const lines = buf.toString('utf8').split('\n');
199
+ for (let i = 0; i < lines.length; i++) {
200
+ if ((icase ? lines[i].toLowerCase() : lines[i]).includes(needle)) {
201
+ out.push(`${full}:${i + 1}: ${lines[i].trim().slice(0, 200)}`);
202
+ if (out.length >= limit) break;
203
+ }
204
+ }
205
+ }
206
+ if (out.length >= limit) break walk;
207
+ }
208
+ }
209
+ }
210
+ if (out.length >= limit) note = `\n…[stopped at ${limit} results, narrow the search or raise max_results]`;
211
+ return out.length ? out.slice(0, limit).join('\n') + note : `No matches.${note}`;
212
+ },
213
+ async read_multiple_files({ paths, max_bytes }) {
214
+ if (!Array.isArray(paths) || !paths.length) throw new Error('paths must be a non-empty list');
215
+ if (paths.length > 20) throw new Error('At most 20 files per call');
216
+ const max = Math.min(Number(max_bytes) || 100_000, 200_000);
217
+ const parts = [];
218
+ for (const raw of paths) {
219
+ try {
220
+ const p = resolve(String(raw));
221
+ const buf = await readFile(p);
222
+ const s = buf.subarray(0, max).toString('utf8');
223
+ parts.push(`=== ${p} ===\n${s}${buf.length > max ? `\n…[truncated, file is ${buf.length} bytes]` : ''}`);
224
+ } catch (e) {
225
+ parts.push(`=== ${String(raw)} ===\n[error: ${e.message}]`);
226
+ }
227
+ }
228
+ return parts.join('\n\n');
229
+ },
230
+ async get_file_info({ path }) {
231
+ const p = resolve(path);
232
+ const l = await lstat(p);
233
+ const type = l.isSymbolicLink() ? 'symlink' : l.isDirectory() ? 'directory' : l.isFile() ? 'file' : 'other';
234
+ return [
235
+ `path: ${p}`, `type: ${type}`, `size: ${l.size} bytes`,
236
+ `modified: ${l.mtime.toISOString()}`, `created: ${l.birthtime.toISOString()}`,
237
+ `mode: ${(l.mode & 0o777).toString(8).padStart(3, '0')}`,
238
+ ].join('\n');
239
+ },
240
+ async move_file({ source, destination }) {
241
+ if (!source || !destination) throw new Error('source and destination are required');
242
+ const from = resolve(source), to = resolve(destination);
243
+ try { await lstat(to); throw new Error(`Destination already exists: ${to}. Nothing moved.`); }
244
+ catch (e) { if (e.code !== 'ENOENT') throw e; }
245
+ try { await rename(from, to); }
246
+ catch (e) {
247
+ if (e.code !== 'EXDEV') throw e; // different disk: copy then remove
248
+ await cp(from, to, { recursive: true, errorOnExist: true });
249
+ await rm(from, { recursive: true });
250
+ }
251
+ return `Moved ${from} to ${to}`;
252
+ },
253
+ async create_directory({ path }) {
254
+ const p = resolve(path);
255
+ const made = await mkdir(p, { recursive: true });
256
+ return made ? `Created ${p}` : `Already exists: ${p}`;
257
+ },
258
+ async start_process({ command, cwd, wait_ms }) {
259
+ if (typeof command !== 'string' || !command.trim()) throw new Error('command is required');
260
+ if ([...sessions.values()].filter((x) => !x.exited).length >= MAX_SESSIONS) {
261
+ throw new Error(`Too many running sessions (limit ${MAX_SESSIONS}). Stop one with force_terminate (see list_sessions).`);
262
+ }
263
+ const child = spawn(command, { shell: true, cwd: cwd ? resolve(cwd) : homedir(), env: process.env, detached: platform() !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
264
+ const s = { id: child.pid, child, command, started: Date.now(), last: Date.now(), out: '', base: 0, readPos: 0, exited: false, code: null, signal: null };
265
+ const add = (d) => {
266
+ s.out += d;
267
+ if (s.out.length > SESSION_BUF) { const cut = s.out.length - SESSION_BUF; s.out = s.out.slice(cut); s.base += cut; }
268
+ };
269
+ child.stdout.on('data', add);
270
+ child.stderr.on('data', add);
271
+ child.stdin.on('error', () => {});
272
+ child.on('error', (e) => { add(`[error: ${e.message}]\n`); s.exited = true; s.code = -1; });
273
+ child.on('close', (code, signal) => { s.exited = true; s.code = code; s.signal = signal; });
274
+ if (!child.pid) { await sleep(100); throw new Error(s.out.trim() || 'Could not start the process'); }
275
+ sessions.set(s.id, s);
276
+ await waitOutput(s, clampMs(wait_ms, 1500, 30_000));
277
+ return sessionReply(s);
278
+ },
279
+ async interact_with_process({ pid, input, wait_ms }) {
280
+ const s = getSession(pid);
281
+ if (typeof input !== 'string' || input === '') throw new Error('input is required (add \\n to press Enter)');
282
+ if (s.exited) throw new Error(`Session ${s.id} has already ended (${sessionState(s)}). Use read_process_output for its last output.`);
283
+ s.child.stdin.write(input);
284
+ await waitOutput(s, clampMs(wait_ms, 2000, 30_000));
285
+ return sessionReply(s);
286
+ },
287
+ async read_process_output({ pid, wait_ms }) {
288
+ const s = getSession(pid);
289
+ await waitOutput(s, clampMs(wait_ms, 500, 30_000));
290
+ return sessionReply(s);
291
+ },
292
+ async list_sessions() {
293
+ if (!sessions.size) return 'No sessions.';
294
+ return [...sessions.values()].map((s) => {
295
+ const age = Math.round((Date.now() - s.started) / 1000);
296
+ const unread = s.base + s.out.length - s.readPos;
297
+ return `${String(s.id).padStart(7)} ${sessionState(s).padEnd(14)} ${String(age).padStart(6)}s unread ${unread} ${s.command.slice(0, 70)}`;
298
+ }).join('\n');
299
+ },
300
+ async force_terminate({ pid }) {
301
+ const s = getSession(pid);
302
+ if (s.exited) return `Session ${s.id} had already ended (${sessionState(s)}).`;
303
+ killSession(s, false);
304
+ for (let i = 0; i < 30 && !s.exited; i++) await sleep(100);
305
+ if (!s.exited) { killSession(s, true); for (let i = 0; i < 20 && !s.exited; i++) await sleep(100); }
306
+ return `Stopped session ${s.id} (${sessionState(s)}).\n--- last output ---\n${cap(takeOutput(s))}`;
307
+ },
308
+ async list_processes() {
309
+ if (platform() === 'win32') {
310
+ const rows = (await capture('tasklist', ['/FO', 'CSV', '/NH'])).trim().split(/\r?\n/).slice(0, 80);
311
+ return rows.map((r) => r.replace(/"/g, '').split(',').slice(0, 2).join(' ')).join('\n');
312
+ }
313
+ const lines = (await capture('ps', ['-axo', 'pid,user,pcpu,pmem,etime,comm'])).trim().split('\n');
314
+ const head = lines.shift();
315
+ lines.sort((a, b) => parseFloat(b.trim().split(/\s+/)[2]) - parseFloat(a.trim().split(/\s+/)[2]));
316
+ return [head, ...lines.slice(0, 60)].join('\n') + (lines.length > 60 ? `\n…[${lines.length - 60} more, sorted by CPU]` : '');
317
+ },
77
318
  async list_directory({ path }) {
78
319
  const p = resolve(path);
79
320
  const names = await readdir(p);
@@ -85,7 +326,16 @@ const handlers = {
85
326
  return out.join('\n') + (names.length > 1000 ? `\n…[${names.length - 1000} more]` : '');
86
327
  },
87
328
  };
88
- const writeMethods = new Set(['run_command', 'write_file']);
329
+ const writeMethods = new Set(['run_command', 'write_file', 'edit_block', 'move_file', 'create_directory', 'start_process', 'interact_with_process', 'force_terminate']);
330
+
331
+ // One entry point for every request from the relay, so it can be tested without a network.
332
+ async function dispatch(method, params) {
333
+ if (readonly && writeMethods.has(method)) throw new Error('This computer is in read-only mode');
334
+ const h = handlers[method];
335
+ if (!h) throw new Error(`unknown method ${method}`);
336
+ return h(params || {});
337
+ }
338
+ export { dispatch, writeMethods };
89
339
 
90
340
  async function tokenValid(conf) {
91
341
  try {
@@ -106,10 +356,7 @@ function start() {
106
356
  let m; try { m = JSON.parse(String(ev.data)); } catch { return; }
107
357
  if (m.type === 'hello' || !m.id) return;
108
358
  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 || {}) }));
359
+ ws.send(JSON.stringify({ id: m.id, result: await dispatch(m.method, m.params) }));
113
360
  } catch (e) {
114
361
  ws.send(JSON.stringify({ id: m.id, error: e.message }));
115
362
  }
@@ -187,7 +434,8 @@ function service() {
187
434
  }
188
435
  }
189
436
 
190
- if (cmd === 'pair') await pair();
437
+ if (process.env.SHELLWAY_NO_CLI) { /* imported by tests: do not run the command line */ }
438
+ else if (cmd === 'pair') await pair();
191
439
  else if (cmd === 'start') start();
192
440
  else if (cmd === 'service') service();
193
441
  else console.log('shellway pair <CODE> [--server URL] [--name NAME]\nshellway start [--readonly]\nshellway service install|uninstall|status [--readonly]');