shellway 0.6.0 → 0.6.2
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/package.json +1 -1
- package/shellway.js +236 -13
package/package.json
CHANGED
package/shellway.js
CHANGED
|
@@ -4,10 +4,10 @@ import { homedir, hostname, platform, release } from 'node:os';
|
|
|
4
4
|
import { join, resolve, dirname, basename, sep } from 'node:path';
|
|
5
5
|
import { mkdirSync, readFileSync, writeFileSync, chmodSync, existsSync, copyFileSync, rmSync, statSync, realpathSync } from 'node:fs';
|
|
6
6
|
import { fileURLToPath } from 'node:url';
|
|
7
|
-
import { execFileSync } from 'node:child_process';
|
|
7
|
+
import { execFileSync, execFile } 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.6.
|
|
10
|
+
const AGENT_VERSION = '0.6.2'; // keep equal to agent/package.json
|
|
11
11
|
if (Number(process.versions.node.split('.')[0]) < 22) {
|
|
12
12
|
console.error(`Shellway needs Node.js 22 or newer (you have ${process.versions.node}). Get it at https://nodejs.org`);
|
|
13
13
|
process.exit(1);
|
|
@@ -53,7 +53,7 @@ const cap = (s) => (s.length > MAX_OUT ? s.slice(0, MAX_OUT) + `\n…[truncated
|
|
|
53
53
|
function runCommand({ command, cwd, timeout_seconds }) {
|
|
54
54
|
return new Promise((done) => {
|
|
55
55
|
const timeout = Math.min(Math.max(Number(timeout_seconds) || 60, 1), 600) * 1000;
|
|
56
|
-
const child =
|
|
56
|
+
const child = shellSpawn(command, { cwd: cwd ? resolve(cwd) : homedir(), env: process.env });
|
|
57
57
|
let stdout = '', stderr = '', timedOut = false;
|
|
58
58
|
const t = setTimeout(() => { timedOut = true; child.kill('SIGKILL'); }, timeout);
|
|
59
59
|
child.stdout.on('data', (d) => { if (stdout.length < MAX_OUT * 2) stdout += d; });
|
|
@@ -363,7 +363,7 @@ const handlers = {
|
|
|
363
363
|
if ([...sessions.values()].filter((x) => !x.exited).length >= MAX_SESSIONS) {
|
|
364
364
|
throw new Error(`Too many running sessions (limit ${MAX_SESSIONS}). Stop one with force_terminate (see list_sessions).`);
|
|
365
365
|
}
|
|
366
|
-
const child =
|
|
366
|
+
const child = shellSpawn(command, { cwd: cwd ? resolve(cwd) : homedir(), env: process.env, detached: platform() !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
|
|
367
367
|
const s = { id: child.pid, child, command, started: Date.now(), last: Date.now(), out: '', base: 0, readPos: 0, exited: false, code: null, signal: null };
|
|
368
368
|
const add = (d) => {
|
|
369
369
|
s.out += d;
|
|
@@ -506,14 +506,14 @@ const handlers = {
|
|
|
506
506
|
return out.join('\n') || '(empty)';
|
|
507
507
|
},
|
|
508
508
|
};
|
|
509
|
-
const writeMethods = new Set(['run_command', 'write_file', 'edit_block', 'move_file', 'create_directory', 'start_process', 'interact_with_process', 'force_terminate', 'download_file']);
|
|
509
|
+
const writeMethods = new Set(['run_command', 'write_file', 'edit_block', 'move_file', 'create_directory', 'start_process', 'interact_with_process', 'force_terminate', 'download_file', 'open_app', 'close_app', 'focus_window', 'mouse_click', 'type_text', 'press_keys']);
|
|
510
510
|
|
|
511
511
|
// ---- safety rules set by the computer's owner (~/.shellway/policy.json, edited with `shellway policy ...`) ----
|
|
512
512
|
// No file = no extra rules. The file lives on this computer, so the AI and the relay cannot change it.
|
|
513
513
|
const POLICY = join(CONF_DIR, 'policy.json');
|
|
514
514
|
const DELETE_WORDS = ['rm', 'rmdir', 'del', 'erase', 'rd', 'Remove-Item', 'shred', 'unlink', 'format', 'mkfs', 'diskpart'];
|
|
515
515
|
let policyCache = { mtime: -1, value: null };
|
|
516
|
-
function emptyPolicy() { return { allowed_folders: [], blocked_commands: [], commands: true, backups: false }; }
|
|
516
|
+
function emptyPolicy() { return { allowed_folders: [], blocked_commands: [], commands: true, backups: false, keep_awake: false, desktop: false }; }
|
|
517
517
|
function loadPolicy() {
|
|
518
518
|
let st; try { st = statSync(POLICY); } catch { policyCache = { mtime: -1, value: null }; return null; }
|
|
519
519
|
if (st.mtimeMs === policyCache.mtime) return policyCache.value;
|
|
@@ -612,6 +612,8 @@ function policyCli() {
|
|
|
612
612
|
console.log(`Commands: ${q.commands ? 'on' : 'OFF (file tools only)'}`);
|
|
613
613
|
console.log(`Blocked commands: ${q.blocked_commands.length ? q.blocked_commands.join(', ') : 'none'}`);
|
|
614
614
|
console.log(`Backups before a file is changed: ${q.backups ? `on (${join(CONF_DIR, 'backups')})` : 'off'}`);
|
|
615
|
+
console.log(`Keep awake while Shellway runs: ${q.keep_awake ? 'on' : 'off'}`);
|
|
616
|
+
console.log(`Screen, apps, mouse and keyboard: ${q.desktop ? 'ON (the AI can see the screen and click/type)' : 'off'}`);
|
|
615
617
|
if (q.allowed_folders.length && q.commands) console.log('Note: commands start inside an allowed folder, but a command can still reach other folders. For a strict lock, also run: shellway policy commands off');
|
|
616
618
|
console.log('Rules apply right away; no restart needed.');
|
|
617
619
|
};
|
|
@@ -624,6 +626,8 @@ function policyCli() {
|
|
|
624
626
|
else if (sub === 'block-deletes') { for (const w of DELETE_WORDS) if (!p.blocked_commands.includes(w)) p.blocked_commands.push(w); }
|
|
625
627
|
else if (sub === 'commands' && (val === 'on' || val === 'off')) p.commands = val === 'on';
|
|
626
628
|
else if (sub === 'backups' && (val === 'on' || val === 'off')) p.backups = val === 'on';
|
|
629
|
+
else if (sub === 'keep-awake' && (val === 'on' || val === 'off')) p.keep_awake = val === 'on';
|
|
630
|
+
else if (sub === 'desktop' && (val === 'on' || val === 'off')) p.desktop = val === 'on';
|
|
627
631
|
else if (sub === 'reset') { rmSync(POLICY, { force: true }); policyCache = { mtime: -1, value: null }; console.log('Safety rules removed.'); return; }
|
|
628
632
|
else {
|
|
629
633
|
console.log(`shellway policy show the rules
|
|
@@ -634,6 +638,8 @@ shellway policy unblock "<command>"
|
|
|
634
638
|
shellway policy block-deletes block delete commands (rm, del, Remove-Item, format ...)
|
|
635
639
|
shellway policy commands on|off off = file tools only, no commands
|
|
636
640
|
shellway policy backups on|off keep a copy of a file before the AI changes it
|
|
641
|
+
shellway policy keep-awake on|off stop the computer from sleeping while Shellway runs
|
|
642
|
+
shellway policy desktop on|off let the AI see the screen, open/close apps, click and type (off by default)
|
|
637
643
|
shellway policy reset remove all rules`);
|
|
638
644
|
return;
|
|
639
645
|
}
|
|
@@ -641,11 +647,193 @@ shellway policy reset remove all rules`);
|
|
|
641
647
|
show();
|
|
642
648
|
}
|
|
643
649
|
|
|
650
|
+
// ---- W1: on Windows, commands written in PowerShell run in powershell.exe; cmd-style commands keep using cmd.exe ----
|
|
651
|
+
const PS_HINT = /(?:^|;)\s*\$[A-Za-z_]\w*\s*=|\$env:|\$_\b|\$PSVersionTable|\$true|\$false|\$null|\b(?:Get|Set|New|Remove|Start|Stop|Select|Where|ForEach|Invoke|Test|Out|Write|Import|Export|Measure|Sort|Format|Copy|Move|Rename|Add|Clear|Restart|Resolve|Split|Join|Expand|Compress|ConvertTo|ConvertFrom|Group|Compare|Wait|Update|Enable|Disable|Register|Unregister|Read|Push|Pop|Suspend|Resume|Unblock|Mount|Dismount)-[A-Z][A-Za-z]+/;
|
|
652
|
+
const isPsCommand = (command) => !/^\s*(?:powershell|pwsh)(?:\.exe)?\b/i.test(command) && PS_HINT.test(command);
|
|
653
|
+
const looksLikePowerShell = (command) => platform() === 'win32' && isPsCommand(command);
|
|
654
|
+
// PowerShell scripts run from a temporary .ps1 file (-File), never -EncodedCommand: Windows Defender blocks
|
|
655
|
+
// encoded commands that touch the screen or the keyboard. The file is deleted when PowerShell exits.
|
|
656
|
+
let psSeq = 0;
|
|
657
|
+
function psSpawn(script, opts = {}) {
|
|
658
|
+
const dir = join(CONF_DIR, 'ps');
|
|
659
|
+
mkdirSync(dir, { recursive: true });
|
|
660
|
+
const file = join(dir, `run-${process.pid}-${Date.now()}-${++psSeq}.ps1`);
|
|
661
|
+
writeFileSync(file, '\ufeff' + script, 'utf8'); // BOM: Windows PowerShell 5 reads the file as UTF-8
|
|
662
|
+
const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', file], { ...opts, shell: false, windowsHide: true });
|
|
663
|
+
const clean = () => { try { rmSync(file, { force: true }); } catch {} };
|
|
664
|
+
child.on('close', clean); child.on('error', clean);
|
|
665
|
+
return child;
|
|
666
|
+
}
|
|
667
|
+
function shellSpawn(command, opts) {
|
|
668
|
+
if (looksLikePowerShell(command)) return psSpawn(`[Console]::OutputEncoding=[Text.Encoding]::UTF8\n${command}`, opts);
|
|
669
|
+
return spawn(command, { ...opts, shell: true, windowsHide: true });
|
|
670
|
+
}
|
|
671
|
+
export { looksLikePowerShell, isPsCommand };
|
|
672
|
+
|
|
673
|
+
// Run a PowerShell script and return its stdout (desktop tools, keep-awake).
|
|
674
|
+
function runPs(script, timeoutMs = 30_000) {
|
|
675
|
+
return new Promise((done, fail) => {
|
|
676
|
+
const c = psSpawn(script);
|
|
677
|
+
let out = '', err = '';
|
|
678
|
+
const t = setTimeout(() => { try { c.kill(); } catch {} fail(new Error('PowerShell timed out')); }, timeoutMs);
|
|
679
|
+
c.stdout.on('data', (d) => { if (out.length < 30_000_000) out += d; });
|
|
680
|
+
c.stderr.on('data', (d) => { if (err.length < 100_000) err += d; });
|
|
681
|
+
c.on('error', (e) => { clearTimeout(t); fail(e); });
|
|
682
|
+
c.on('close', (code) => { clearTimeout(t); code === 0 ? done(out.trim()) : fail(new Error((err || out).trim().split('\n').slice(-3).join(' ') || `PowerShell exit ${code}`)); });
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
// ---- W3: keep the computer awake while the agent runs (policy keep_awake) ----
|
|
687
|
+
let awakeChild = null;
|
|
688
|
+
function keepAwakeTick() {
|
|
689
|
+
const pol = loadPolicy();
|
|
690
|
+
const want = !!(pol && pol.keep_awake);
|
|
691
|
+
if (want && !awakeChild) {
|
|
692
|
+
try {
|
|
693
|
+
const os = platform();
|
|
694
|
+
if (os === 'win32') {
|
|
695
|
+
awakeChild = psSpawn(("Add-Type -Name P -Namespace SwAwake -MemberDefinition '[DllImport(\"kernel32.dll\")] public static extern uint SetThreadExecutionState(uint f);'\nwhile ($true) { [SwAwake.P]::SetThreadExecutionState([uint32]2147483649) | Out-Null; Start-Sleep -Seconds 50 }"), { stdio: 'ignore' });
|
|
696
|
+
} else if (os === 'darwin') {
|
|
697
|
+
awakeChild = spawn('caffeinate', ['-i', '-w', String(process.pid)], { stdio: 'ignore' });
|
|
698
|
+
} else {
|
|
699
|
+
awakeChild = spawn('systemd-inhibit', ['--what=sleep:idle', '--who=Shellway', '--why=Shellway keep-awake', '--mode=block', 'sleep', 'infinity'], { stdio: 'ignore' });
|
|
700
|
+
}
|
|
701
|
+
awakeChild.on('exit', () => { awakeChild = null; });
|
|
702
|
+
awakeChild.on('error', () => { awakeChild = null; });
|
|
703
|
+
} catch { awakeChild = null; }
|
|
704
|
+
} else if (!want && awakeChild) {
|
|
705
|
+
try { awakeChild.kill(); } catch {}
|
|
706
|
+
awakeChild = null;
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
process.on('exit', () => { try { awakeChild && awakeChild.kill(); } catch {} });
|
|
710
|
+
|
|
711
|
+
// ---- W5–W7: screen, windows and apps, mouse and keyboard (policy desktop, off by default) ----
|
|
712
|
+
const MAX_SHOT_W = 1280;
|
|
713
|
+
const b64 = (s) => Buffer.from(String(s), 'utf8').toString('base64');
|
|
714
|
+
// No P/Invoke here: Windows Defender flags screen capture combined with DllImport. Screenshot and mouse both use
|
|
715
|
+
// the same logical screen coordinates, so clicks still land where the screenshot shows.
|
|
716
|
+
const PS_DPI = "Add-Type -AssemblyName System.Windows.Forms,System.Drawing\n$b=[System.Windows.Forms.SystemInformation]::VirtualScreen\n$w=[Math]::Min(" + MAX_SHOT_W + ",$b.Width); $k=$b.Width/$w\n";
|
|
717
|
+
// SendKeys text: special characters wrapped in braces, new lines as Enter.
|
|
718
|
+
function sendKeysText(t) {
|
|
719
|
+
return [...String(t)].map((ch) => ('+^%~(){}[]'.includes(ch) ? `{${ch}}` : ch === '\n' ? '{ENTER}' : ch === '\r' ? '' : ch === '\t' ? '{TAB}' : ch)).join('');
|
|
720
|
+
}
|
|
721
|
+
const KEY_NAMES = { enter: '{ENTER}', return: '{ENTER}', tab: '{TAB}', esc: '{ESC}', escape: '{ESC}', backspace: '{BACKSPACE}', delete: '{DEL}', del: '{DEL}', insert: '{INSERT}',
|
|
722
|
+
up: '{UP}', down: '{DOWN}', left: '{LEFT}', right: '{RIGHT}', home: '{HOME}', end: '{END}', pageup: '{PGUP}', pagedown: '{PGDN}', space: ' ', capslock: '{CAPSLOCK}', printscreen: '{PRTSC}' };
|
|
723
|
+
// "ctrl+l enter alt+f4" -> SendKeys string; throws on keys SendKeys cannot press.
|
|
724
|
+
function sendKeysCombo(keys) {
|
|
725
|
+
const parts = String(keys || '').trim().split(/\s+/).filter(Boolean);
|
|
726
|
+
if (!parts.length) throw new Error('keys is required, for example "ctrl+l" or "enter"');
|
|
727
|
+
return parts.map((combo) => {
|
|
728
|
+
const ks = combo.toLowerCase().split('+').filter(Boolean);
|
|
729
|
+
let mods = '', key = '';
|
|
730
|
+
for (const k of ks) {
|
|
731
|
+
if (k === 'ctrl' || k === 'control') mods += '^';
|
|
732
|
+
else if (k === 'shift') mods += '+';
|
|
733
|
+
else if (k === 'alt') mods += '%';
|
|
734
|
+
else if (k === 'win' || k === 'windows' || k === 'cmd' || k === 'meta') throw new Error('The Windows key cannot be pressed this way; use open_app or ctrl+esc instead.');
|
|
735
|
+
else if (KEY_NAMES[k]) key = KEY_NAMES[k];
|
|
736
|
+
else if (/^f([1-9]|1[0-6])$/.test(k)) key = `{${k.toUpperCase()}}`;
|
|
737
|
+
else if (k.length === 1) key = sendKeysText(k);
|
|
738
|
+
else throw new Error(`Unknown key "${k}"`);
|
|
739
|
+
}
|
|
740
|
+
if (!key) throw new Error(`No key in "${combo}"`);
|
|
741
|
+
return mods ? `${mods}${key.length > 1 && !key.startsWith('{') ? `(${key})` : key}` : key;
|
|
742
|
+
}).join('');
|
|
743
|
+
}
|
|
744
|
+
export { sendKeysText, sendKeysCombo };
|
|
745
|
+
const notSupported = () => { throw new Error(`This desktop tool is not available on ${platform()} yet (Windows only for now).`); };
|
|
746
|
+
const desktopHandlers = {
|
|
747
|
+
async take_screenshot() {
|
|
748
|
+
const os = platform();
|
|
749
|
+
if (os === 'darwin') {
|
|
750
|
+
const f = join(CONF_DIR, `shot-${process.pid}.jpg`);
|
|
751
|
+
await new Promise((ok, no) => execFile('screencapture', ['-x', '-t', 'jpg', f], (e) => (e ? no(new Error('screencapture failed: allow Screen Recording for the terminal or node in System Settings > Privacy')) : ok())));
|
|
752
|
+
await new Promise((ok) => execFile('sips', ['-Z', String(MAX_SHOT_W), f], () => ok()));
|
|
753
|
+
const data = (await readFile(f)).toString('base64');
|
|
754
|
+
await rm(f, { force: true });
|
|
755
|
+
return { type: 'image', mimeType: 'image/jpeg', data, note: 'Screenshot of the main screen (macOS). Mouse and keyboard tools are Windows-only for now.' };
|
|
756
|
+
}
|
|
757
|
+
// Windows: script-based screen capture is flagged by Windows Defender (AMSI) as malware-like, so it is not
|
|
758
|
+
// offered. Seeing the screen on Windows needs a signed native helper (planned) or the Claude desktop app.
|
|
759
|
+
throw new Error(os === 'win32'
|
|
760
|
+
? 'Screenshots are not available on Windows yet (Windows Defender blocks script-based screen capture). Use list_windows, focus_window, open_app, type_text and press_keys, or ask the user to describe the screen.'
|
|
761
|
+
: `Screenshots are not available on ${os} yet.`);
|
|
762
|
+
},
|
|
763
|
+
async list_windows() {
|
|
764
|
+
if (platform() !== 'win32') notSupported();
|
|
765
|
+
const out = await runPs("[Console]::OutputEncoding=[Text.Encoding]::UTF8\nGet-Process | Where-Object { $_.MainWindowTitle } | Sort-Object ProcessName | ForEach-Object { '{0} {1} {2}' -f $_.Id, $_.ProcessName, $_.MainWindowTitle }");
|
|
766
|
+
return out ? `pid app window title\n${out}` : '(no open windows: the screen may be locked, or no apps are open)';
|
|
767
|
+
},
|
|
768
|
+
async open_app({ name, args: a }) {
|
|
769
|
+
if (typeof name !== 'string' || !name.trim()) throw new Error('name is required, for example "chrome", "notepad" or a full path');
|
|
770
|
+
if (platform() === 'darwin') {
|
|
771
|
+
await new Promise((ok, no) => execFile('open', ['-a', name, ...(a ? ['--args', ...String(a).split(' ')] : [])], (e) => (e ? no(new Error(`Could not open ${name}`)) : ok())));
|
|
772
|
+
return `Opened ${name}`;
|
|
773
|
+
}
|
|
774
|
+
if (platform() !== 'win32') notSupported();
|
|
775
|
+
await runPs(`$n=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(name)}'))\n$a=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(a || '')}'))\nif ($a) { Start-Process -FilePath $n -ArgumentList $a } else { Start-Process -FilePath $n }`);
|
|
776
|
+
return `Opened ${name}${a ? ` ${a}` : ''}. Use list_windows to check it.`;
|
|
777
|
+
},
|
|
778
|
+
async close_app({ pid, name, force }) {
|
|
779
|
+
if (platform() !== 'win32') notSupported();
|
|
780
|
+
if (!pid && !name) throw new Error('pid or name is required (see list_windows)');
|
|
781
|
+
const sel = pid ? `Get-Process -Id ${Number(pid) | 0}` : `Get-Process -Name ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(String(name).replace(/\.exe$/i, ''))}')))`;
|
|
782
|
+
const out = await runPs(`$ps=@(${sel} -ErrorAction Stop)\nforeach ($p in $ps) { if (${force ? '$true' : '$false'}) { Stop-Process -Id $p.Id -Force } else { [void]$p.CloseMainWindow() } }\n'{0} process(es)' -f $ps.Count`);
|
|
783
|
+
return `${force ? 'Stopped' : 'Asked to close'} ${out}${force ? '' : '. Unsaved work may show a save dialog; use list_windows to check.'}`;
|
|
784
|
+
},
|
|
785
|
+
async focus_window({ pid, title }) {
|
|
786
|
+
if (platform() !== 'win32') notSupported();
|
|
787
|
+
if (!pid && !title) throw new Error('pid or title is required (see list_windows)');
|
|
788
|
+
const target = pid ? String(Number(pid) | 0) : `[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(title)}'))`;
|
|
789
|
+
const out = await runPs(`$ok=(New-Object -ComObject WScript.Shell).AppActivate(${target})\nif ($ok) { 'focused' } else { 'not found' }`);
|
|
790
|
+
if (out !== 'focused') throw new Error('Window not found. Use list_windows to see open windows.');
|
|
791
|
+
return 'Window brought to the front.';
|
|
792
|
+
},
|
|
793
|
+
async mouse_click({ x, y, button, double }) {
|
|
794
|
+
if (platform() !== 'win32') notSupported();
|
|
795
|
+
const X = Number(x), Y = Number(y);
|
|
796
|
+
if (!Number.isFinite(X) || !Number.isFinite(Y) || X < 0 || Y < 0) throw new Error('x and y (screen pixels) are required');
|
|
797
|
+
const [dn, up] = button === 'right' ? [8, 16] : [2, 4];
|
|
798
|
+
const times = double ? 2 : 1;
|
|
799
|
+
await runPs(`Add-Type -AssemblyName System.Windows.Forms,System.Drawing\nAdd-Type -Name M -Namespace SwMouse -MemberDefinition '[DllImport("user32.dll")] public static extern void mouse_event(uint f,uint x,uint y,uint d,UIntPtr e);'\n[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point(${Math.round(X)}, ${Math.round(Y)})\nStart-Sleep -Milliseconds 60\nfor ($i=0; $i -lt ${times}; $i++) { [SwMouse.M]::mouse_event(${dn},0,0,0,[UIntPtr]::Zero); [SwMouse.M]::mouse_event(${up},0,0,0,[UIntPtr]::Zero); Start-Sleep -Milliseconds 80 }`);
|
|
800
|
+
return `${double ? 'Double-clicked' : 'Clicked'} ${button === 'right' ? 'right ' : ''}at ${X},${Y}. Ask the user to confirm the result if needed.`;
|
|
801
|
+
},
|
|
802
|
+
async type_text({ text: t }) {
|
|
803
|
+
if (platform() !== 'win32') notSupported();
|
|
804
|
+
if (typeof t !== 'string' || !t) throw new Error('text is required');
|
|
805
|
+
if (t.length > 5000) throw new Error('text is too long (max 5000 characters); paste longer text with write_file instead');
|
|
806
|
+
await runPs(`Add-Type -AssemblyName System.Windows.Forms\n[System.Windows.Forms.SendKeys]::SendWait([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(sendKeysText(t))}')))`);
|
|
807
|
+
return `Typed ${t.length} characters into the active window.`;
|
|
808
|
+
},
|
|
809
|
+
async press_keys({ keys }) {
|
|
810
|
+
if (platform() !== 'win32') notSupported();
|
|
811
|
+
const seq = sendKeysCombo(keys);
|
|
812
|
+
await runPs(`Add-Type -AssemblyName System.Windows.Forms\n[System.Windows.Forms.SendKeys]::SendWait([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(seq)}')))`);
|
|
813
|
+
return `Pressed ${keys}.`;
|
|
814
|
+
},
|
|
815
|
+
};
|
|
816
|
+
const DESKTOP_METHODS = new Set(Object.keys(desktopHandlers));
|
|
817
|
+
const DESKTOP_CONTROL = new Set(['open_app', 'close_app', 'focus_window', 'mouse_click', 'type_text', 'press_keys']);
|
|
818
|
+
function checkDesktop(method, params) {
|
|
819
|
+
if (!DESKTOP_METHODS.has(method)) return;
|
|
820
|
+
const pol = loadPolicy();
|
|
821
|
+
if (!pol || !pol.desktop) throw new Error('Screen and app control is turned off on this computer. The owner can turn it on there with: npx shellway policy desktop on');
|
|
822
|
+
if (DESKTOP_CONTROL.has(method) && pol.commands === false) throw new Error('Commands are turned off on this computer, so apps, mouse and keyboard cannot be controlled either.');
|
|
823
|
+
if (method === 'open_app' || method === 'press_keys') {
|
|
824
|
+
const hit = blockedBy(`${params.name || ''} ${params.args || ''} ${params.keys || ''}`, pol);
|
|
825
|
+
if (hit) throw new Error(`Blocked: "${hit}" is on this computer's list of blocked commands.`);
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
Object.assign(handlers, desktopHandlers);
|
|
830
|
+
|
|
644
831
|
// One entry point for every request from the relay, so it can be tested without a network.
|
|
645
832
|
async function dispatch(method, params) {
|
|
646
833
|
if (readonly && writeMethods.has(method)) throw new Error('This computer is in read-only mode');
|
|
647
834
|
const h = handlers[method];
|
|
648
835
|
if (!h) throw new Error(`unknown method ${method}`);
|
|
836
|
+
checkDesktop(method, params || {});
|
|
649
837
|
const p = checkPolicy(method, params || {});
|
|
650
838
|
const note = await backupBeforeChange(method, p);
|
|
651
839
|
const r = await h(p);
|
|
@@ -662,6 +850,8 @@ async function tokenValid(conf) {
|
|
|
662
850
|
|
|
663
851
|
function start() {
|
|
664
852
|
const conf = loadConf();
|
|
853
|
+
keepAwakeTick();
|
|
854
|
+
setInterval(keepAwakeTick, 60_000);
|
|
665
855
|
const wsUrl = conf.server.replace(/^http/, 'ws') + '/agent';
|
|
666
856
|
let delay = 1000;
|
|
667
857
|
const connect = async () => {
|
|
@@ -683,7 +873,7 @@ function start() {
|
|
|
683
873
|
connect();
|
|
684
874
|
}
|
|
685
875
|
|
|
686
|
-
// ---- auto-start service (systemd user unit / launchd agent / Windows
|
|
876
|
+
// ---- auto-start service (systemd user unit / launchd agent / Windows Startup-folder launcher) ----
|
|
687
877
|
const xml = (v) => String(v).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
688
878
|
function serviceSpec() {
|
|
689
879
|
// Copy ourselves to a stable path so the service survives npx cache cleanup.
|
|
@@ -693,6 +883,27 @@ function serviceSpec() {
|
|
|
693
883
|
}
|
|
694
884
|
const run = (c, a, opts = {}) => execFileSync(c, a, { stdio: opts.quiet ? 'pipe' : 'inherit', encoding: 'utf8' });
|
|
695
885
|
|
|
886
|
+
// Windows auto-start without admin rights: a hidden launcher in the user's Startup folder runs a small
|
|
887
|
+
// loop that restarts the agent after a crash (exit 78 = device removed: stop).
|
|
888
|
+
const winStartup = () => join(process.env.APPDATA || join(homedir(), 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup', 'Shellway.vbs');
|
|
889
|
+
const winLoop = () => join(CONF_DIR, 'shellway-agent.cmd');
|
|
890
|
+
function renderWinLoop(argv, home = process.env.SHELLWAY_HOME) {
|
|
891
|
+
const q = (a) => `"${a}"`;
|
|
892
|
+
return ['@echo off', 'rem Shellway agent, kept running in the background. Remove Shellway.vbs from the Startup folder to stop it.',
|
|
893
|
+
...(home ? [`set "SHELLWAY_HOME=${home}"`] : []),
|
|
894
|
+
':loop', `${argv.map(q).join(' ')} >> ${q(join(CONF_DIR, 'agent.log'))} 2>&1`,
|
|
895
|
+
'if %errorlevel%==78 exit /b 78', 'ping -n 11 127.0.0.1 >nul', 'goto loop', ''].join('\r\n');
|
|
896
|
+
}
|
|
897
|
+
function renderWinVbs(loopPath) {
|
|
898
|
+
return `' Starts the Shellway agent hidden at login. Delete this file to stop auto-start.\r\nCreateObject("WScript.Shell").Run """${loopPath}""", 0, False\r\n`;
|
|
899
|
+
}
|
|
900
|
+
const winStopAgents = () => {
|
|
901
|
+
// stop running background agents started from ~/.shellway (not this process)
|
|
902
|
+
const ps = `Get-CimInstance Win32_Process | Where-Object { ($_.Name -eq 'node.exe' -or $_.Name -eq 'cmd.exe') -and $_.CommandLine -like '*${CONF_DIR.replace(/'/g, "''")}*' -and $_.ProcessId -ne ${process.pid} } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }`;
|
|
903
|
+
try { run('powershell', ['-NoProfile', '-Command', ps], { quiet: true }); } catch {}
|
|
904
|
+
};
|
|
905
|
+
export { renderWinLoop, renderWinVbs };
|
|
906
|
+
|
|
696
907
|
function renderService(os, argv) {
|
|
697
908
|
const home = process.env.SHELLWAY_HOME ? `Environment=SHELLWAY_HOME=${process.env.SHELLWAY_HOME}\n` : '';
|
|
698
909
|
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`;
|
|
@@ -709,7 +920,7 @@ function service() {
|
|
|
709
920
|
if (!['install', 'uninstall', 'status', 'print'].includes(sub)) {
|
|
710
921
|
console.log('shellway service install [--readonly] start Shellway automatically at login / boot\nshellway service uninstall\nshellway service status'); return;
|
|
711
922
|
}
|
|
712
|
-
if (sub === 'print') { console.log(
|
|
923
|
+
if (sub === 'print') { console.log(os === 'win32' ? renderWinLoop(argv) : renderService(os, argv)); return; }
|
|
713
924
|
if (!['linux', 'darwin', 'win32'].includes(os)) { console.error(`Auto-start is not supported on ${os}. Use: shellway start`); process.exit(1); }
|
|
714
925
|
if (sub === 'install') {
|
|
715
926
|
loadConf();
|
|
@@ -728,16 +939,23 @@ function service() {
|
|
|
728
939
|
try { run('launchctl', ['unload', unitPath], { quiet: true }); } catch {}
|
|
729
940
|
run('launchctl', ['load', '-w', unitPath]);
|
|
730
941
|
} else {
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
942
|
+
try { run('schtasks', ['/Delete', '/F', '/TN', 'Shellway'], { quiet: true }); } catch {} // older versions used a task
|
|
943
|
+
winStopAgents();
|
|
944
|
+
writeFileSync(winLoop(), renderWinLoop(argv));
|
|
945
|
+
mkdirSync(dirname(winStartup()), { recursive: true });
|
|
946
|
+
writeFileSync(winStartup(), renderWinVbs(winLoop()));
|
|
947
|
+
spawn('wscript', [winStartup()], { detached: true, stdio: 'ignore', windowsHide: true }).unref();
|
|
948
|
+
console.log(`Auto-start file: ${winStartup()}`);
|
|
734
949
|
}
|
|
735
950
|
console.log(`Done. Shellway now starts automatically${has('readonly') ? ' (read-only)' : ''}. Check: shellway service status`);
|
|
736
951
|
} else if (sub === 'uninstall') {
|
|
737
952
|
try {
|
|
738
953
|
if (os === 'linux') { try { run('systemctl', ['--user', 'disable', '--now', 'shellway.service']); } catch {} rmSync(unitPath, { force: true }); try { run('systemctl', ['--user', 'daemon-reload'], { quiet: true }); } catch {} }
|
|
739
954
|
else if (os === 'darwin') { try { run('launchctl', ['unload', '-w', unitPath], { quiet: true }); } catch {} rmSync(unitPath, { force: true }); }
|
|
740
|
-
else {
|
|
955
|
+
else {
|
|
956
|
+
try { run('schtasks', ['/End', '/TN', 'Shellway'], { quiet: true }); run('schtasks', ['/Delete', '/F', '/TN', 'Shellway'], { quiet: true }); } catch {}
|
|
957
|
+
rmSync(winStartup(), { force: true }); rmSync(winLoop(), { force: true }); winStopAgents();
|
|
958
|
+
}
|
|
741
959
|
} catch (e) { console.error(e.message); process.exit(1); }
|
|
742
960
|
rmSync(dest, { force: true });
|
|
743
961
|
console.log('Auto-start removed. (Your pairing is kept; run "shellway start" to run manually.)');
|
|
@@ -745,7 +963,12 @@ function service() {
|
|
|
745
963
|
try {
|
|
746
964
|
if (os === 'linux') run('systemctl', ['--user', 'status', 'shellway.service', '--no-pager', '-n', '5']);
|
|
747
965
|
else if (os === 'darwin') run('launchctl', ['list', 'com.getshellway.agent']);
|
|
748
|
-
else
|
|
966
|
+
else {
|
|
967
|
+
if (!existsSync(winStartup())) throw new Error('not installed');
|
|
968
|
+
let n = 0;
|
|
969
|
+
try { n = Number(run('powershell', ['-NoProfile', '-Command', `(Get-CimInstance Win32_Process | Where-Object { $_.Name -eq 'node.exe' -and $_.CommandLine -like '*${CONF_DIR.replace(/'/g, "''")}*agent.mjs*' }).Count`], { quiet: true }).trim()) || 0; } catch {}
|
|
970
|
+
console.log(`Auto-start installed (${winStartup()}). Background agent: ${n > 0 ? 'running' : 'not running - log out and in, or run the install again'}. Log: ${join(CONF_DIR, 'agent.log')}`);
|
|
971
|
+
}
|
|
749
972
|
} catch { console.log('Auto-start is not installed (or not running).'); }
|
|
750
973
|
}
|
|
751
974
|
}
|