shellway 0.1.1 → 0.2.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.
- package/README.md +16 -1
- package/package.json +1 -1
- package/shellway.js +136 -11
package/README.md
CHANGED
|
@@ -13,10 +13,25 @@ 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
|
|
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
|
+
|
|
33
|
+
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
|
+
|
|
20
35
|
## What it does
|
|
21
36
|
|
|
22
37
|
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
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; };
|
|
@@ -22,7 +25,7 @@ const has = (n) => args.includes(`--${n}`);
|
|
|
22
25
|
const cmd = args[0];
|
|
23
26
|
|
|
24
27
|
function loadConf() {
|
|
25
|
-
if (!existsSync(CONF)) { console.error('Not paired yet. Run: shellway pair <CODE> --server <URL>'); process.exit(
|
|
28
|
+
if (!existsSync(CONF)) { console.error('Not paired yet. Run: shellway pair <CODE> --server <URL>'); process.exit(78); }
|
|
26
29
|
return JSON.parse(readFileSync(CONF, 'utf8'));
|
|
27
30
|
}
|
|
28
31
|
|
|
@@ -74,6 +77,121 @@ const handlers = {
|
|
|
74
77
|
await (append ? appendFile(p, content) : writeFile(p, content));
|
|
75
78
|
return `Wrote ${Buffer.byteLength(content)} bytes to ${p}`;
|
|
76
79
|
},
|
|
80
|
+
async edit_block({ path, old_string, new_string, expected_replacements }) {
|
|
81
|
+
const p = resolve(path);
|
|
82
|
+
if (typeof old_string !== 'string' || old_string === '') throw new Error('old_string must be a non-empty string');
|
|
83
|
+
if (typeof new_string !== 'string') throw new Error('new_string must be a string');
|
|
84
|
+
const exp = expected_replacements === undefined ? 1 : Number(expected_replacements);
|
|
85
|
+
if (!Number.isInteger(exp) || exp < 1) throw new Error('expected_replacements must be a whole number of 1 or more');
|
|
86
|
+
const st = await stat(p);
|
|
87
|
+
if (!st.isFile()) throw new Error('Not a regular file');
|
|
88
|
+
if (st.size > MAX_EDIT_BYTES) throw new Error(`File is too large to edit (${st.size} bytes, limit ${MAX_EDIT_BYTES})`);
|
|
89
|
+
const buf = await readFile(p);
|
|
90
|
+
if (buf.subarray(0, 8000).includes(0)) throw new Error('This looks like a binary file; edit_block only edits text files');
|
|
91
|
+
const parts = buf.toString('utf8').split(old_string);
|
|
92
|
+
const found = parts.length - 1;
|
|
93
|
+
if (found === 0) throw new Error('old_string was not found in the file. Nothing changed.');
|
|
94
|
+
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}.`);
|
|
95
|
+
await writeFile(p, parts.join(new_string));
|
|
96
|
+
return `Replaced ${found} occurrence${found === 1 ? '' : 's'} in ${p}`;
|
|
97
|
+
},
|
|
98
|
+
async search_files({ path, pattern, mode, max_results, ignore_case }) {
|
|
99
|
+
if (typeof pattern !== 'string' || pattern === '') throw new Error('pattern is required');
|
|
100
|
+
const m = mode || 'name';
|
|
101
|
+
if (m !== 'name' && m !== 'content') throw new Error('mode must be "name" or "content"');
|
|
102
|
+
const root = resolve(path);
|
|
103
|
+
const limit = Math.min(Math.max(Math.floor(Number(max_results)) || 100, 1), 500);
|
|
104
|
+
const icase = ignore_case !== false;
|
|
105
|
+
const deadline = Date.now() + 20_000;
|
|
106
|
+
let nameRe = null, needle = icase ? pattern.toLowerCase() : pattern;
|
|
107
|
+
if (m === 'name' && /[*?]/.test(pattern)) {
|
|
108
|
+
const esc = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.');
|
|
109
|
+
nameRe = new RegExp(`^${esc}$`, icase ? 'i' : '');
|
|
110
|
+
}
|
|
111
|
+
const out = [];
|
|
112
|
+
let note = '';
|
|
113
|
+
const stack = [[root, 0]];
|
|
114
|
+
walk: while (stack.length) {
|
|
115
|
+
const [dir, depth] = stack.pop();
|
|
116
|
+
let entries;
|
|
117
|
+
try { entries = await readdir(dir, { withFileTypes: true }); } catch { continue; }
|
|
118
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
119
|
+
for (const e of entries) {
|
|
120
|
+
if (Date.now() > deadline) { note = '\n…[stopped after 20 seconds, results may be incomplete]'; break walk; }
|
|
121
|
+
const full = join(dir, e.name);
|
|
122
|
+
if (e.isSymbolicLink()) continue;
|
|
123
|
+
if (e.isDirectory()) {
|
|
124
|
+
if (SKIP_DIRS.has(e.name) || depth >= 12) continue;
|
|
125
|
+
if (m === 'name' && (nameRe ? nameRe.test(e.name) : (icase ? e.name.toLowerCase() : e.name).includes(needle))) out.push(`d ${full}`);
|
|
126
|
+
stack.push([full, depth + 1]);
|
|
127
|
+
} else if (e.isFile()) {
|
|
128
|
+
if (m === 'name') {
|
|
129
|
+
if (nameRe ? nameRe.test(e.name) : (icase ? e.name.toLowerCase() : e.name).includes(needle)) out.push(`- ${full}`);
|
|
130
|
+
} else {
|
|
131
|
+
let st; try { st = await stat(full); } catch { continue; }
|
|
132
|
+
if (st.size > MAX_SEARCH_FILE) continue;
|
|
133
|
+
let buf; try { buf = await readFile(full); } catch { continue; }
|
|
134
|
+
if (buf.subarray(0, 8000).includes(0)) continue;
|
|
135
|
+
const lines = buf.toString('utf8').split('\n');
|
|
136
|
+
for (let i = 0; i < lines.length; i++) {
|
|
137
|
+
if ((icase ? lines[i].toLowerCase() : lines[i]).includes(needle)) {
|
|
138
|
+
out.push(`${full}:${i + 1}: ${lines[i].trim().slice(0, 200)}`);
|
|
139
|
+
if (out.length >= limit) break;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (out.length >= limit) break walk;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (out.length >= limit) note = `\n…[stopped at ${limit} results, narrow the search or raise max_results]`;
|
|
148
|
+
return out.length ? out.slice(0, limit).join('\n') + note : `No matches.${note}`;
|
|
149
|
+
},
|
|
150
|
+
async read_multiple_files({ paths, max_bytes }) {
|
|
151
|
+
if (!Array.isArray(paths) || !paths.length) throw new Error('paths must be a non-empty list');
|
|
152
|
+
if (paths.length > 20) throw new Error('At most 20 files per call');
|
|
153
|
+
const max = Math.min(Number(max_bytes) || 100_000, 200_000);
|
|
154
|
+
const parts = [];
|
|
155
|
+
for (const raw of paths) {
|
|
156
|
+
try {
|
|
157
|
+
const p = resolve(String(raw));
|
|
158
|
+
const buf = await readFile(p);
|
|
159
|
+
const s = buf.subarray(0, max).toString('utf8');
|
|
160
|
+
parts.push(`=== ${p} ===\n${s}${buf.length > max ? `\n…[truncated, file is ${buf.length} bytes]` : ''}`);
|
|
161
|
+
} catch (e) {
|
|
162
|
+
parts.push(`=== ${String(raw)} ===\n[error: ${e.message}]`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
return parts.join('\n\n');
|
|
166
|
+
},
|
|
167
|
+
async get_file_info({ path }) {
|
|
168
|
+
const p = resolve(path);
|
|
169
|
+
const l = await lstat(p);
|
|
170
|
+
const type = l.isSymbolicLink() ? 'symlink' : l.isDirectory() ? 'directory' : l.isFile() ? 'file' : 'other';
|
|
171
|
+
return [
|
|
172
|
+
`path: ${p}`, `type: ${type}`, `size: ${l.size} bytes`,
|
|
173
|
+
`modified: ${l.mtime.toISOString()}`, `created: ${l.birthtime.toISOString()}`,
|
|
174
|
+
`mode: ${(l.mode & 0o777).toString(8).padStart(3, '0')}`,
|
|
175
|
+
].join('\n');
|
|
176
|
+
},
|
|
177
|
+
async move_file({ source, destination }) {
|
|
178
|
+
if (!source || !destination) throw new Error('source and destination are required');
|
|
179
|
+
const from = resolve(source), to = resolve(destination);
|
|
180
|
+
try { await lstat(to); throw new Error(`Destination already exists: ${to}. Nothing moved.`); }
|
|
181
|
+
catch (e) { if (e.code !== 'ENOENT') throw e; }
|
|
182
|
+
try { await rename(from, to); }
|
|
183
|
+
catch (e) {
|
|
184
|
+
if (e.code !== 'EXDEV') throw e; // different disk: copy then remove
|
|
185
|
+
await cp(from, to, { recursive: true, errorOnExist: true });
|
|
186
|
+
await rm(from, { recursive: true });
|
|
187
|
+
}
|
|
188
|
+
return `Moved ${from} to ${to}`;
|
|
189
|
+
},
|
|
190
|
+
async create_directory({ path }) {
|
|
191
|
+
const p = resolve(path);
|
|
192
|
+
const made = await mkdir(p, { recursive: true });
|
|
193
|
+
return made ? `Created ${p}` : `Already exists: ${p}`;
|
|
194
|
+
},
|
|
77
195
|
async list_directory({ path }) {
|
|
78
196
|
const p = resolve(path);
|
|
79
197
|
const names = await readdir(p);
|
|
@@ -85,7 +203,16 @@ const handlers = {
|
|
|
85
203
|
return out.join('\n') + (names.length > 1000 ? `\n…[${names.length - 1000} more]` : '');
|
|
86
204
|
},
|
|
87
205
|
};
|
|
88
|
-
const writeMethods = new Set(['run_command', 'write_file']);
|
|
206
|
+
const writeMethods = new Set(['run_command', 'write_file', 'edit_block', 'move_file', 'create_directory']);
|
|
207
|
+
|
|
208
|
+
// One entry point for every request from the relay, so it can be tested without a network.
|
|
209
|
+
async function dispatch(method, params) {
|
|
210
|
+
if (readonly && writeMethods.has(method)) throw new Error('This computer is in read-only mode');
|
|
211
|
+
const h = handlers[method];
|
|
212
|
+
if (!h) throw new Error(`unknown method ${method}`);
|
|
213
|
+
return h(params || {});
|
|
214
|
+
}
|
|
215
|
+
export { dispatch, writeMethods };
|
|
89
216
|
|
|
90
217
|
async function tokenValid(conf) {
|
|
91
218
|
try {
|
|
@@ -99,17 +226,14 @@ function start() {
|
|
|
99
226
|
const wsUrl = conf.server.replace(/^http/, 'ws') + '/agent';
|
|
100
227
|
let delay = 1000;
|
|
101
228
|
const connect = async () => {
|
|
102
|
-
if (!(await tokenValid(conf))) { console.error('This device was removed or its token is invalid. Pair again.'); process.exit(
|
|
229
|
+
if (!(await tokenValid(conf))) { console.error('This device was removed or its token is invalid. Pair again.'); process.exit(78); }
|
|
103
230
|
const ws = new WebSocket(wsUrl, { headers: { authorization: `Bearer ${conf.device_token}` } });
|
|
104
231
|
ws.onopen = () => { delay = 1000; console.log(`Connected as "${conf.device_name}"${readonly ? ' (read-only)' : ''}. Leave this running.`); };
|
|
105
232
|
ws.onmessage = async (ev) => {
|
|
106
233
|
let m; try { m = JSON.parse(String(ev.data)); } catch { return; }
|
|
107
234
|
if (m.type === 'hello' || !m.id) return;
|
|
108
235
|
try {
|
|
109
|
-
|
|
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 || {}) }));
|
|
236
|
+
ws.send(JSON.stringify({ id: m.id, result: await dispatch(m.method, m.params) }));
|
|
113
237
|
} catch (e) {
|
|
114
238
|
ws.send(JSON.stringify({ id: m.id, error: e.message }));
|
|
115
239
|
}
|
|
@@ -132,8 +256,8 @@ const run = (c, a, opts = {}) => execFileSync(c, a, { stdio: opts.quiet ? 'pipe'
|
|
|
132
256
|
|
|
133
257
|
function renderService(os, argv) {
|
|
134
258
|
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`;
|
|
259
|
+
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\nRestartPreventExitStatus=78\n\n[Install]\nWantedBy=default.target\n`;
|
|
260
|
+
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>ThrottleInterval</key><integer>30</integer>\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
261
|
return null;
|
|
138
262
|
}
|
|
139
263
|
|
|
@@ -187,7 +311,8 @@ function service() {
|
|
|
187
311
|
}
|
|
188
312
|
}
|
|
189
313
|
|
|
190
|
-
if (
|
|
314
|
+
if (process.env.SHELLWAY_NO_CLI) { /* imported by tests: do not run the command line */ }
|
|
315
|
+
else if (cmd === 'pair') await pair();
|
|
191
316
|
else if (cmd === 'start') start();
|
|
192
317
|
else if (cmd === 'service') service();
|
|
193
318
|
else console.log('shellway pair <CODE> [--server URL] [--name NAME]\nshellway start [--readonly]\nshellway service install|uninstall|status [--readonly]');
|