shellway 0.3.0 → 0.4.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.
- package/README.md +3 -0
- package/package.json +1 -1
- package/shellway.js +141 -4
package/README.md
CHANGED
|
@@ -26,6 +26,7 @@ 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 |
|
|
@@ -34,6 +35,8 @@ Optional: `--name "Home laptop"` on `pair` sets the computer's name. `--server U
|
|
|
34
35
|
| `force_terminate` | Stop a program Shellway started | yes |
|
|
35
36
|
| `list_processes` | Show the programs running on the computer, busiest first | no |
|
|
36
37
|
|
|
38
|
+
Advanced searches run at most 3 at a time, stop after 2 minutes and keep up to 5,000 results.
|
|
39
|
+
|
|
37
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).
|
|
38
41
|
|
|
39
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.
|
package/package.json
CHANGED
package/shellway.js
CHANGED
|
@@ -7,6 +7,7 @@ import { fileURLToPath } from 'node:url';
|
|
|
7
7
|
import { execFileSync } from 'node:child_process';
|
|
8
8
|
import { readFile, writeFile, appendFile, readdir, stat, lstat, mkdir, rename, cp, rm } from 'node:fs/promises';
|
|
9
9
|
|
|
10
|
+
const AGENT_VERSION = '0.4.1'; // keep equal to agent/package.json
|
|
10
11
|
if (Number(process.versions.node.split('.')[0]) < 22) {
|
|
11
12
|
console.error(`Shellway needs Node.js 22 or newer (you have ${process.versions.node}). Get it at https://nodejs.org`);
|
|
12
13
|
process.exit(1);
|
|
@@ -125,6 +126,93 @@ function capture(cmd, cmdArgs, ms = 10_000) {
|
|
|
125
126
|
});
|
|
126
127
|
}
|
|
127
128
|
|
|
129
|
+
// ---- background searches (start_search / get_more_search_results / stop_search)
|
|
130
|
+
const MAX_SEARCHES = 3, SEARCH_STORE = 5000, SEARCH_DEADLINE_MS = 120_000, SEARCH_KEEP_MS = 10 * 60_000;
|
|
131
|
+
const searches = new Map();
|
|
132
|
+
let searchSeq = 0;
|
|
133
|
+
const searchSweeper = setInterval(() => {
|
|
134
|
+
for (const [id, s] of searches) if (Date.now() - (s.finishedAt || s.startedAt) > SEARCH_KEEP_MS) searches.delete(id);
|
|
135
|
+
}, 60_000);
|
|
136
|
+
searchSweeper.unref();
|
|
137
|
+
|
|
138
|
+
function globRes(list, icase) {
|
|
139
|
+
return String(list).split(',').map((g) => g.trim()).filter(Boolean).map((g) =>
|
|
140
|
+
new RegExp(`^${g.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')}$`, icase ? 'i' : ''));
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async function runSearch(s) {
|
|
144
|
+
const push = (item) => {
|
|
145
|
+
s.results.push(item);
|
|
146
|
+
if (s.results.length >= SEARCH_STORE) { s.note = `stopped at ${SEARCH_STORE} stored results`; s.stop = true; }
|
|
147
|
+
};
|
|
148
|
+
try {
|
|
149
|
+
const stack = [[s.root, 0]];
|
|
150
|
+
while (stack.length && !s.stop) {
|
|
151
|
+
const [dir, depth] = stack.pop();
|
|
152
|
+
let entries;
|
|
153
|
+
try { entries = await readdir(dir, { withFileTypes: true }); } catch { continue; }
|
|
154
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
155
|
+
for (const e of entries) {
|
|
156
|
+
if (s.stop) break;
|
|
157
|
+
if (Date.now() - s.startedAt > SEARCH_DEADLINE_MS) { s.note = 'stopped after 2 minutes, results may be incomplete'; s.stop = true; break; }
|
|
158
|
+
if (e.isSymbolicLink()) continue;
|
|
159
|
+
const full = join(dir, e.name);
|
|
160
|
+
if (e.isDirectory()) {
|
|
161
|
+
if (SKIP_DIRS.has(e.name) || depth >= 12) continue;
|
|
162
|
+
if (s.mode === 'name' && s.test(e.name)) push(`d ${full}`);
|
|
163
|
+
stack.push([full, depth + 1]);
|
|
164
|
+
} else if (e.isFile()) {
|
|
165
|
+
if (s.mode === 'name') { if (s.test(e.name)) push(`- ${full}`); continue; }
|
|
166
|
+
if (s.fileRes && !s.fileRes.some((re) => re.test(e.name))) continue;
|
|
167
|
+
let st; try { st = await stat(full); } catch { continue; }
|
|
168
|
+
if (st.size > MAX_SEARCH_FILE) continue;
|
|
169
|
+
let buf; try { buf = await readFile(full); } catch { continue; }
|
|
170
|
+
if (buf.subarray(0, 8000).includes(0)) continue;
|
|
171
|
+
const lines = buf.toString('utf8').split('\n');
|
|
172
|
+
let printed = -1; // last line number already included for this file
|
|
173
|
+
for (let i = 0; i < lines.length && !s.stop; i++) {
|
|
174
|
+
if (!s.test(lines[i].slice(0, 2000))) continue;
|
|
175
|
+
const from = Math.max(i - s.context, printed + 1);
|
|
176
|
+
const to = Math.min(i + s.context, lines.length - 1);
|
|
177
|
+
const block = [];
|
|
178
|
+
if (s.context && printed >= 0 && from > printed + 1) block.push('--');
|
|
179
|
+
for (let n = from; n <= to; n++) block.push(`${full}${n === i ? ':' : '-'}${n + 1}${n === i ? ':' : '-'} ${lines[n].trim().slice(0, 200)}`);
|
|
180
|
+
printed = to;
|
|
181
|
+
push(block.join('\n'));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
} catch (err) { s.error = err.message; }
|
|
187
|
+
s.done = true; s.finishedAt = Date.now();
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function searchStatus(s) { return s.error ? 'error' : !s.done ? 'running' : s.stopped ? 'stopped' : 'finished'; }
|
|
191
|
+
|
|
192
|
+
async function searchPage(s, limit, waitMs) {
|
|
193
|
+
const until = Date.now() + waitMs;
|
|
194
|
+
while (!s.done && s.results.length - s.cursor < limit && Date.now() < until) await new Promise((r) => setTimeout(r, 50));
|
|
195
|
+
const n = Math.min(Math.max(Math.floor(Number(limit)) || 100, 1), 500);
|
|
196
|
+
const page = s.results.slice(s.cursor, s.cursor + n);
|
|
197
|
+
s.cursor += page.length;
|
|
198
|
+
const left = s.results.length - s.cursor;
|
|
199
|
+
const head = `Search ${s.id}: ${searchStatus(s)}, ${s.results.length} result${s.results.length === 1 ? '' : 's'} found so far`;
|
|
200
|
+
const tail = [];
|
|
201
|
+
if (s.error) tail.push(`Error: ${s.error}`);
|
|
202
|
+
if (s.note) tail.push(s.note);
|
|
203
|
+
if (left > 0) tail.push(`${left} more result${left === 1 ? '' : 's'} ready: call get_more_search_results with search_id ${s.id}`);
|
|
204
|
+
else if (!s.done) tail.push(`Still searching: call get_more_search_results with search_id ${s.id} again`);
|
|
205
|
+
else if (!s.results.length) tail.push('No matches.');
|
|
206
|
+
else tail.push('Search complete, nothing more to read.');
|
|
207
|
+
return [head, ...page, ...tail].join('\n');
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const getSearch = (id) => {
|
|
211
|
+
const s = searches.get(String(id));
|
|
212
|
+
if (!s) throw new Error(`No search with id ${id}. It may have finished long ago; start a new one.`);
|
|
213
|
+
return s;
|
|
214
|
+
};
|
|
215
|
+
|
|
128
216
|
const readonly = has('readonly');
|
|
129
217
|
const handlers = {
|
|
130
218
|
run_command: runCommand,
|
|
@@ -151,11 +239,26 @@ const handlers = {
|
|
|
151
239
|
if (st.size > MAX_EDIT_BYTES) throw new Error(`File is too large to edit (${st.size} bytes, limit ${MAX_EDIT_BYTES})`);
|
|
152
240
|
const buf = await readFile(p);
|
|
153
241
|
if (buf.subarray(0, 8000).includes(0)) throw new Error('This looks like a binary file; edit_block only edits text files');
|
|
154
|
-
const
|
|
242
|
+
const text = buf.toString('utf8');
|
|
243
|
+
let oldS = old_string, newS = new_string;
|
|
244
|
+
let parts = text.split(oldS);
|
|
245
|
+
// Windows files often use CRLF line endings while the AI sends plain LF: retry with the file's own line endings.
|
|
246
|
+
if (parts.length === 1 && text.includes('\r\n') && /\n/.test(oldS)) {
|
|
247
|
+
const crlf = (x) => x.replace(/\r?\n/g, '\r\n');
|
|
248
|
+
const retry = text.split(crlf(oldS));
|
|
249
|
+
if (retry.length > 1) { parts = retry; oldS = crlf(oldS); newS = crlf(newS); }
|
|
250
|
+
}
|
|
155
251
|
const found = parts.length - 1;
|
|
156
|
-
if (found === 0)
|
|
252
|
+
if (found === 0) {
|
|
253
|
+
const first = old_string.split(/\r?\n/).map((l) => l.trim()).find(Boolean);
|
|
254
|
+
const lines = text.split(/\r?\n/);
|
|
255
|
+
const at = first ? lines.findIndex((l) => l.includes(first)) : -1;
|
|
256
|
+
throw new Error(`old_string was not found in the file. Nothing changed. ${at >= 0
|
|
257
|
+
? `Its first line does appear at line ${at + 1}, so the difference is further down: check spaces, tabs and blank lines. Read that part of the file again and copy the text exactly.`
|
|
258
|
+
: 'No line contains the start of it. The file may have changed: read it again and copy the text exactly.'}`);
|
|
259
|
+
}
|
|
157
260
|
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(
|
|
261
|
+
await writeFile(p, parts.join(newS));
|
|
159
262
|
return `Replaced ${found} occurrence${found === 1 ? '' : 's'} in ${p}`;
|
|
160
263
|
},
|
|
161
264
|
async search_files({ path, pattern, mode, max_results, ignore_case }) {
|
|
@@ -315,6 +418,40 @@ const handlers = {
|
|
|
315
418
|
lines.sort((a, b) => parseFloat(b.trim().split(/\s+/)[2]) - parseFloat(a.trim().split(/\s+/)[2]));
|
|
316
419
|
return [head, ...lines.slice(0, 60)].join('\n') + (lines.length > 60 ? `\n…[${lines.length - 60} more, sorted by CPU]` : '');
|
|
317
420
|
},
|
|
421
|
+
async start_search({ path, pattern, mode, regex, ignore_case, file_pattern, context_lines, max_results }) {
|
|
422
|
+
if (typeof pattern !== 'string' || pattern === '') throw new Error('pattern is required');
|
|
423
|
+
const m = mode || 'name';
|
|
424
|
+
if (m !== 'name' && m !== 'content') throw new Error('mode must be "name" or "content"');
|
|
425
|
+
const icase = ignore_case !== false;
|
|
426
|
+
let test;
|
|
427
|
+
if (regex) {
|
|
428
|
+
let re; try { re = new RegExp(pattern, icase ? 'i' : ''); } catch (e) { throw new Error(`Invalid regular expression: ${e.message}`); }
|
|
429
|
+
test = (str) => re.test(str);
|
|
430
|
+
} else if (m === 'name' && /[*?]/.test(pattern)) {
|
|
431
|
+
const [re] = globRes(pattern, icase);
|
|
432
|
+
test = (str) => re.test(str);
|
|
433
|
+
} else {
|
|
434
|
+
const needle = icase ? pattern.toLowerCase() : pattern;
|
|
435
|
+
test = (str) => (icase ? str.toLowerCase() : str).includes(needle);
|
|
436
|
+
}
|
|
437
|
+
const context = Math.min(Math.max(Math.floor(Number(context_lines)) || 0, 0), 5);
|
|
438
|
+
if (m === 'name' && context) throw new Error('context_lines only works in content mode');
|
|
439
|
+
for (const [id, s] of searches) if (s.done && Date.now() - s.finishedAt > 60_000) searches.delete(id);
|
|
440
|
+
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.`);
|
|
441
|
+
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: '' };
|
|
442
|
+
searches.set(s.id, s);
|
|
443
|
+
runSearch(s);
|
|
444
|
+
return searchPage(s, max_results || 100, 1500);
|
|
445
|
+
},
|
|
446
|
+
async get_more_search_results({ search_id, max_results, wait_ms }) {
|
|
447
|
+
const s = getSearch(search_id);
|
|
448
|
+
return searchPage(s, max_results || 100, Math.min(Math.max(Number(wait_ms) || 1500, 0), 5000));
|
|
449
|
+
},
|
|
450
|
+
async stop_search({ search_id }) {
|
|
451
|
+
const s = getSearch(search_id);
|
|
452
|
+
if (!s.done) { s.stop = true; s.stopped = true; }
|
|
453
|
+
return `Search ${s.id}: ${s.done && !s.stopped ? 'was already ' + searchStatus(s) : 'stopped'}, ${s.results.length} results found, ${s.results.length - s.cursor} unread.`;
|
|
454
|
+
},
|
|
318
455
|
async list_directory({ path }) {
|
|
319
456
|
const p = resolve(path);
|
|
320
457
|
const names = await readdir(p);
|
|
@@ -350,7 +487,7 @@ function start() {
|
|
|
350
487
|
let delay = 1000;
|
|
351
488
|
const connect = async () => {
|
|
352
489
|
if (!(await tokenValid(conf))) { console.error('This device was removed or its token is invalid. Pair again.'); process.exit(78); }
|
|
353
|
-
const ws = new WebSocket(wsUrl, { headers: { authorization: `Bearer ${conf.device_token}
|
|
490
|
+
const ws = new WebSocket(wsUrl, { headers: { authorization: `Bearer ${conf.device_token}`, 'x-shellway-version': AGENT_VERSION } });
|
|
354
491
|
ws.onopen = () => { delay = 1000; console.log(`Connected as "${conf.device_name}"${readonly ? ' (read-only)' : ''}. Leave this running.`); };
|
|
355
492
|
ws.onmessage = async (ev) => {
|
|
356
493
|
let m; try { m = JSON.parse(String(ev.data)); } catch { return; }
|