shellway 0.2.0 → 0.4.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 +9 -0
  2. package/package.json +1 -1
  3. package/shellway.js +245 -1
package/README.md CHANGED
@@ -26,9 +26,18 @@ Optional: `--name "Home laptop"` on `pair` sets the computer's name. `--server U
26
26
  | `write_file` | Create, overwrite or append to a file | yes |
27
27
  | `edit_block` | Replace exact text in a file; changes nothing if the text is missing or ambiguous | yes |
28
28
  | `search_files` | Find files by name, or text inside files (skips node_modules, .git, binary files) | no |
29
+ | `start_search`, `get_more_search_results`, `stop_search` | Advanced search in the background: by name or text, optional regular expression, file-type filter (`*.js,*.ts`), lines of context, results in pages | no |
29
30
  | `list_directory`, `get_file_info` | List a folder; show size, dates and permissions | no |
30
31
  | `move_file` | Move or rename; never overwrites an existing file | yes |
31
32
  | `create_directory` | Create a folder | yes |
33
+ | `start_process`, `interact_with_process` | Start a program that keeps running (dev server, Python or Node shell, `ssh`) and type into it | yes |
34
+ | `read_process_output`, `list_sessions` | See what a background program printed; list the ones Shellway started | no |
35
+ | `force_terminate` | Stop a program Shellway started | yes |
36
+ | `list_processes` | Show the programs running on the computer, busiest first | no |
37
+
38
+ Advanced searches run at most 3 at a time, stop after 2 minutes and keep up to 5,000 results.
39
+
40
+ 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).
32
41
 
33
42
  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.
34
43
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shellway",
3
- "version": "0.2.0",
3
+ "version": "0.4.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
@@ -62,6 +62,156 @@ function runCommand({ command, cwd, timeout_seconds }) {
62
62
  });
63
63
  }
64
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
+
128
+ // ---- background searches (start_search / get_more_search_results / stop_search)
129
+ const MAX_SEARCHES = 3, SEARCH_STORE = 5000, SEARCH_DEADLINE_MS = 120_000, SEARCH_KEEP_MS = 10 * 60_000;
130
+ const searches = new Map();
131
+ let searchSeq = 0;
132
+ const searchSweeper = setInterval(() => {
133
+ for (const [id, s] of searches) if (Date.now() - (s.finishedAt || s.startedAt) > SEARCH_KEEP_MS) searches.delete(id);
134
+ }, 60_000);
135
+ searchSweeper.unref();
136
+
137
+ function globRes(list, icase) {
138
+ return String(list).split(',').map((g) => g.trim()).filter(Boolean).map((g) =>
139
+ new RegExp(`^${g.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')}$`, icase ? 'i' : ''));
140
+ }
141
+
142
+ async function runSearch(s) {
143
+ const push = (item) => {
144
+ s.results.push(item);
145
+ if (s.results.length >= SEARCH_STORE) { s.note = `stopped at ${SEARCH_STORE} stored results`; s.stop = true; }
146
+ };
147
+ try {
148
+ const stack = [[s.root, 0]];
149
+ while (stack.length && !s.stop) {
150
+ const [dir, depth] = stack.pop();
151
+ let entries;
152
+ try { entries = await readdir(dir, { withFileTypes: true }); } catch { continue; }
153
+ entries.sort((a, b) => a.name.localeCompare(b.name));
154
+ for (const e of entries) {
155
+ if (s.stop) break;
156
+ if (Date.now() - s.startedAt > SEARCH_DEADLINE_MS) { s.note = 'stopped after 2 minutes, results may be incomplete'; s.stop = true; break; }
157
+ if (e.isSymbolicLink()) continue;
158
+ const full = join(dir, e.name);
159
+ if (e.isDirectory()) {
160
+ if (SKIP_DIRS.has(e.name) || depth >= 12) continue;
161
+ if (s.mode === 'name' && s.test(e.name)) push(`d ${full}`);
162
+ stack.push([full, depth + 1]);
163
+ } else if (e.isFile()) {
164
+ if (s.mode === 'name') { if (s.test(e.name)) push(`- ${full}`); continue; }
165
+ if (s.fileRes && !s.fileRes.some((re) => re.test(e.name))) continue;
166
+ let st; try { st = await stat(full); } catch { continue; }
167
+ if (st.size > MAX_SEARCH_FILE) continue;
168
+ let buf; try { buf = await readFile(full); } catch { continue; }
169
+ if (buf.subarray(0, 8000).includes(0)) continue;
170
+ const lines = buf.toString('utf8').split('\n');
171
+ let printed = -1; // last line number already included for this file
172
+ for (let i = 0; i < lines.length && !s.stop; i++) {
173
+ if (!s.test(lines[i].slice(0, 2000))) continue;
174
+ const from = Math.max(i - s.context, printed + 1);
175
+ const to = Math.min(i + s.context, lines.length - 1);
176
+ const block = [];
177
+ if (s.context && printed >= 0 && from > printed + 1) block.push('--');
178
+ for (let n = from; n <= to; n++) block.push(`${full}${n === i ? ':' : '-'}${n + 1}${n === i ? ':' : '-'} ${lines[n].trim().slice(0, 200)}`);
179
+ printed = to;
180
+ push(block.join('\n'));
181
+ }
182
+ }
183
+ }
184
+ }
185
+ } catch (err) { s.error = err.message; }
186
+ s.done = true; s.finishedAt = Date.now();
187
+ }
188
+
189
+ function searchStatus(s) { return s.error ? 'error' : !s.done ? 'running' : s.stopped ? 'stopped' : 'finished'; }
190
+
191
+ async function searchPage(s, limit, waitMs) {
192
+ const until = Date.now() + waitMs;
193
+ while (!s.done && s.results.length - s.cursor < limit && Date.now() < until) await new Promise((r) => setTimeout(r, 50));
194
+ const n = Math.min(Math.max(Math.floor(Number(limit)) || 100, 1), 500);
195
+ const page = s.results.slice(s.cursor, s.cursor + n);
196
+ s.cursor += page.length;
197
+ const left = s.results.length - s.cursor;
198
+ const head = `Search ${s.id}: ${searchStatus(s)}, ${s.results.length} result${s.results.length === 1 ? '' : 's'} found so far`;
199
+ const tail = [];
200
+ if (s.error) tail.push(`Error: ${s.error}`);
201
+ if (s.note) tail.push(s.note);
202
+ if (left > 0) tail.push(`${left} more result${left === 1 ? '' : 's'} ready: call get_more_search_results with search_id ${s.id}`);
203
+ else if (!s.done) tail.push(`Still searching: call get_more_search_results with search_id ${s.id} again`);
204
+ else if (!s.results.length) tail.push('No matches.');
205
+ else tail.push('Search complete, nothing more to read.');
206
+ return [head, ...page, ...tail].join('\n');
207
+ }
208
+
209
+ const getSearch = (id) => {
210
+ const s = searches.get(String(id));
211
+ if (!s) throw new Error(`No search with id ${id}. It may have finished long ago; start a new one.`);
212
+ return s;
213
+ };
214
+
65
215
  const readonly = has('readonly');
66
216
  const handlers = {
67
217
  run_command: runCommand,
@@ -192,6 +342,100 @@ const handlers = {
192
342
  const made = await mkdir(p, { recursive: true });
193
343
  return made ? `Created ${p}` : `Already exists: ${p}`;
194
344
  },
345
+ async start_process({ command, cwd, wait_ms }) {
346
+ if (typeof command !== 'string' || !command.trim()) throw new Error('command is required');
347
+ if ([...sessions.values()].filter((x) => !x.exited).length >= MAX_SESSIONS) {
348
+ throw new Error(`Too many running sessions (limit ${MAX_SESSIONS}). Stop one with force_terminate (see list_sessions).`);
349
+ }
350
+ const child = spawn(command, { shell: true, cwd: cwd ? resolve(cwd) : homedir(), env: process.env, detached: platform() !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
351
+ const s = { id: child.pid, child, command, started: Date.now(), last: Date.now(), out: '', base: 0, readPos: 0, exited: false, code: null, signal: null };
352
+ const add = (d) => {
353
+ s.out += d;
354
+ if (s.out.length > SESSION_BUF) { const cut = s.out.length - SESSION_BUF; s.out = s.out.slice(cut); s.base += cut; }
355
+ };
356
+ child.stdout.on('data', add);
357
+ child.stderr.on('data', add);
358
+ child.stdin.on('error', () => {});
359
+ child.on('error', (e) => { add(`[error: ${e.message}]\n`); s.exited = true; s.code = -1; });
360
+ child.on('close', (code, signal) => { s.exited = true; s.code = code; s.signal = signal; });
361
+ if (!child.pid) { await sleep(100); throw new Error(s.out.trim() || 'Could not start the process'); }
362
+ sessions.set(s.id, s);
363
+ await waitOutput(s, clampMs(wait_ms, 1500, 30_000));
364
+ return sessionReply(s);
365
+ },
366
+ async interact_with_process({ pid, input, wait_ms }) {
367
+ const s = getSession(pid);
368
+ if (typeof input !== 'string' || input === '') throw new Error('input is required (add \\n to press Enter)');
369
+ if (s.exited) throw new Error(`Session ${s.id} has already ended (${sessionState(s)}). Use read_process_output for its last output.`);
370
+ s.child.stdin.write(input);
371
+ await waitOutput(s, clampMs(wait_ms, 2000, 30_000));
372
+ return sessionReply(s);
373
+ },
374
+ async read_process_output({ pid, wait_ms }) {
375
+ const s = getSession(pid);
376
+ await waitOutput(s, clampMs(wait_ms, 500, 30_000));
377
+ return sessionReply(s);
378
+ },
379
+ async list_sessions() {
380
+ if (!sessions.size) return 'No sessions.';
381
+ return [...sessions.values()].map((s) => {
382
+ const age = Math.round((Date.now() - s.started) / 1000);
383
+ const unread = s.base + s.out.length - s.readPos;
384
+ return `${String(s.id).padStart(7)} ${sessionState(s).padEnd(14)} ${String(age).padStart(6)}s unread ${unread} ${s.command.slice(0, 70)}`;
385
+ }).join('\n');
386
+ },
387
+ async force_terminate({ pid }) {
388
+ const s = getSession(pid);
389
+ if (s.exited) return `Session ${s.id} had already ended (${sessionState(s)}).`;
390
+ killSession(s, false);
391
+ for (let i = 0; i < 30 && !s.exited; i++) await sleep(100);
392
+ if (!s.exited) { killSession(s, true); for (let i = 0; i < 20 && !s.exited; i++) await sleep(100); }
393
+ return `Stopped session ${s.id} (${sessionState(s)}).\n--- last output ---\n${cap(takeOutput(s))}`;
394
+ },
395
+ async list_processes() {
396
+ if (platform() === 'win32') {
397
+ const rows = (await capture('tasklist', ['/FO', 'CSV', '/NH'])).trim().split(/\r?\n/).slice(0, 80);
398
+ return rows.map((r) => r.replace(/"/g, '').split(',').slice(0, 2).join(' ')).join('\n');
399
+ }
400
+ const lines = (await capture('ps', ['-axo', 'pid,user,pcpu,pmem,etime,comm'])).trim().split('\n');
401
+ const head = lines.shift();
402
+ lines.sort((a, b) => parseFloat(b.trim().split(/\s+/)[2]) - parseFloat(a.trim().split(/\s+/)[2]));
403
+ return [head, ...lines.slice(0, 60)].join('\n') + (lines.length > 60 ? `\n…[${lines.length - 60} more, sorted by CPU]` : '');
404
+ },
405
+ async start_search({ path, pattern, mode, regex, ignore_case, file_pattern, context_lines, max_results }) {
406
+ if (typeof pattern !== 'string' || pattern === '') throw new Error('pattern is required');
407
+ const m = mode || 'name';
408
+ if (m !== 'name' && m !== 'content') throw new Error('mode must be "name" or "content"');
409
+ const icase = ignore_case !== false;
410
+ let test;
411
+ if (regex) {
412
+ let re; try { re = new RegExp(pattern, icase ? 'i' : ''); } catch (e) { throw new Error(`Invalid regular expression: ${e.message}`); }
413
+ test = (str) => re.test(str);
414
+ } else if (m === 'name' && /[*?]/.test(pattern)) {
415
+ const [re] = globRes(pattern, icase);
416
+ test = (str) => re.test(str);
417
+ } else {
418
+ const needle = icase ? pattern.toLowerCase() : pattern;
419
+ test = (str) => (icase ? str.toLowerCase() : str).includes(needle);
420
+ }
421
+ const context = Math.min(Math.max(Math.floor(Number(context_lines)) || 0, 0), 5);
422
+ if (m === 'name' && context) throw new Error('context_lines only works in content mode');
423
+ for (const [id, s] of searches) if (s.done && Date.now() - s.finishedAt > 60_000) searches.delete(id);
424
+ if ([...searches.values()].filter((s) => !s.done).length >= MAX_SEARCHES) throw new Error(`${MAX_SEARCHES} searches are already running. Wait for one or stop it with stop_search.`);
425
+ const s = { id: String(++searchSeq), root: resolve(path), mode: m, test, context, fileRes: file_pattern ? globRes(file_pattern, true) : null, results: [], cursor: 0, startedAt: Date.now(), done: false, stop: false, stopped: false, note: '' };
426
+ searches.set(s.id, s);
427
+ runSearch(s);
428
+ return searchPage(s, max_results || 100, 1500);
429
+ },
430
+ async get_more_search_results({ search_id, max_results, wait_ms }) {
431
+ const s = getSearch(search_id);
432
+ return searchPage(s, max_results || 100, Math.min(Math.max(Number(wait_ms) || 1500, 0), 5000));
433
+ },
434
+ async stop_search({ search_id }) {
435
+ const s = getSearch(search_id);
436
+ if (!s.done) { s.stop = true; s.stopped = true; }
437
+ return `Search ${s.id}: ${s.done && !s.stopped ? 'was already ' + searchStatus(s) : 'stopped'}, ${s.results.length} results found, ${s.results.length - s.cursor} unread.`;
438
+ },
195
439
  async list_directory({ path }) {
196
440
  const p = resolve(path);
197
441
  const names = await readdir(p);
@@ -203,7 +447,7 @@ const handlers = {
203
447
  return out.join('\n') + (names.length > 1000 ? `\n…[${names.length - 1000} more]` : '');
204
448
  },
205
449
  };
206
- const writeMethods = new Set(['run_command', 'write_file', 'edit_block', 'move_file', 'create_directory']);
450
+ const writeMethods = new Set(['run_command', 'write_file', 'edit_block', 'move_file', 'create_directory', 'start_process', 'interact_with_process', 'force_terminate']);
207
451
 
208
452
  // One entry point for every request from the relay, so it can be tested without a network.
209
453
  async function dispatch(method, params) {