shellway 0.2.0 → 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.
- package/README.md +6 -0
- package/package.json +1 -1
- package/shellway.js +124 -1
package/README.md
CHANGED
|
@@ -29,6 +29,12 @@ Optional: `--name "Home laptop"` on `pair` sets the computer's name. `--server U
|
|
|
29
29
|
| `list_directory`, `get_file_info` | List a folder; show size, dates and permissions | no |
|
|
30
30
|
| `move_file` | Move or rename; never overwrites an existing file | yes |
|
|
31
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).
|
|
32
38
|
|
|
33
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.
|
|
34
40
|
|
package/package.json
CHANGED
package/shellway.js
CHANGED
|
@@ -62,6 +62,69 @@ 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
|
+
|
|
65
128
|
const readonly = has('readonly');
|
|
66
129
|
const handlers = {
|
|
67
130
|
run_command: runCommand,
|
|
@@ -192,6 +255,66 @@ const handlers = {
|
|
|
192
255
|
const made = await mkdir(p, { recursive: true });
|
|
193
256
|
return made ? `Created ${p}` : `Already exists: ${p}`;
|
|
194
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
|
+
},
|
|
195
318
|
async list_directory({ path }) {
|
|
196
319
|
const p = resolve(path);
|
|
197
320
|
const names = await readdir(p);
|
|
@@ -203,7 +326,7 @@ const handlers = {
|
|
|
203
326
|
return out.join('\n') + (names.length > 1000 ? `\n…[${names.length - 1000} more]` : '');
|
|
204
327
|
},
|
|
205
328
|
};
|
|
206
|
-
const writeMethods = new Set(['run_command', 'write_file', 'edit_block', 'move_file', 'create_directory']);
|
|
329
|
+
const writeMethods = new Set(['run_command', 'write_file', 'edit_block', 'move_file', 'create_directory', 'start_process', 'interact_with_process', 'force_terminate']);
|
|
207
330
|
|
|
208
331
|
// One entry point for every request from the relay, so it can be tested without a network.
|
|
209
332
|
async function dispatch(method, params) {
|