shellway 0.6.1 → 0.6.3

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 (2) hide show
  1. package/package.json +1 -1
  2. package/shellway.js +224 -6
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shellway",
3
- "version": "0.6.1",
3
+ "version": "0.6.3",
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": {
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.1'; // keep equal to agent/package.json
10
+ const AGENT_VERSION = '0.6.3'; // 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 = spawn(command, { shell: true, cwd: cwd ? resolve(cwd) : homedir(), env: process.env });
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 = spawn(command, { shell: true, cwd: cwd ? resolve(cwd) : homedir(), env: process.env, detached: platform() !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] });
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;
@@ -563,7 +563,35 @@ function blockedBy(text, pol) {
563
563
  return pol.blocked_commands.find((b) => new RegExp(`(^|[^\\w-])${escRe(b.trim()).replace(/\s+/g, '\\s+')}($|[^\\w-])`, 'i').test(text));
564
564
  }
565
565
  // Throws when the owner's rules forbid this call. May fill in a default cwd inside an allowed folder.
566
+ // Always on (with or without rules): the AI cannot read or change Shellway's own folder (pairing token, safety
567
+ // rules, the agent itself) with file tools, and cannot run "shellway policy" or touch that folder with commands.
568
+ const PROTECT_MSG = "Shellway's own settings (the .shellway folder and \"shellway policy\") can only be changed by the owner directly on the computer, not through the AI. Nothing was done.";
569
+ function protectSelf(method, params) {
570
+ if (PATH_PARAMS[method]) {
571
+ const root = normCase(realLocation(CONF_DIR));
572
+ for (const k of PATH_PARAMS[method]) {
573
+ if (k === 'cwd') continue;
574
+ const vals = k === 'paths' ? (Array.isArray(params[k]) ? params[k] : []) : (params[k] === undefined ? [] : [params[k]]);
575
+ for (const v of vals) {
576
+ if (method === 'open_file' && /^https?:\/\//.test(String(v))) continue;
577
+ const real = normCase(realLocation(String(v)));
578
+ if (real === root || real.startsWith(root + sep)) {
579
+ // backups stay readable so the AI can help restore an older copy of a file
580
+ const backups = root + sep + 'backups';
581
+ const readOnly = ['read_file', 'read_multiple_files', 'list_directory', 'get_file_info', 'search_files', 'start_search'].includes(method);
582
+ if (!(readOnly && (real === backups || real.startsWith(backups + sep)))) throw new Error(PROTECT_MSG);
583
+ }
584
+ }
585
+ }
586
+ }
587
+ if (COMMAND_METHODS.has(method)) {
588
+ const text = method === 'interact_with_process' ? String(params.input ?? '') : String(params.command ?? '');
589
+ if (/[\\/]\.shellway\b|%USERPROFILE%[\\/]\.shellway|~[\\/]\.shellway|\$HOME[\\/]\.shellway|\$env:USERPROFILE[\\/]\.shellway/i.test(text) || /\bshellway(?:@\S+)?(?:\.(?:js|mjs))?["']?\s+policy\b/i.test(text)) throw new Error(PROTECT_MSG);
590
+ }
591
+ }
592
+ export { protectSelf };
566
593
  function checkPolicy(method, params) {
594
+ protectSelf(method, params);
567
595
  const pol = loadPolicy();
568
596
  if (!pol) return params;
569
597
  const fix = 'The owner of this computer set this rule; it can only be changed on the computer (shellway policy).';
@@ -612,6 +640,8 @@ function policyCli() {
612
640
  console.log(`Commands: ${q.commands ? 'on' : 'OFF (file tools only)'}`);
613
641
  console.log(`Blocked commands: ${q.blocked_commands.length ? q.blocked_commands.join(', ') : 'none'}`);
614
642
  console.log(`Backups before a file is changed: ${q.backups ? `on (${join(CONF_DIR, 'backups')})` : 'off'}`);
643
+ console.log(`Keep awake while Shellway runs: ${q.keep_awake ? 'on' : 'off'}`);
644
+ console.log(`Screen, apps, mouse and keyboard: ${q.desktop ? (platform() === 'win32' ? 'ON (the AI can open, switch and close apps, click and type; no screenshots on Windows yet)' : 'ON (the AI can see the screen; apps, mouse and keyboard on Windows)') : 'off'}`);
615
645
  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
646
  console.log('Rules apply right away; no restart needed.');
617
647
  };
@@ -624,6 +654,8 @@ function policyCli() {
624
654
  else if (sub === 'block-deletes') { for (const w of DELETE_WORDS) if (!p.blocked_commands.includes(w)) p.blocked_commands.push(w); }
625
655
  else if (sub === 'commands' && (val === 'on' || val === 'off')) p.commands = val === 'on';
626
656
  else if (sub === 'backups' && (val === 'on' || val === 'off')) p.backups = val === 'on';
657
+ else if (sub === 'keep-awake' && (val === 'on' || val === 'off')) p.keep_awake = val === 'on';
658
+ else if (sub === 'desktop' && (val === 'on' || val === 'off')) p.desktop = val === 'on';
627
659
  else if (sub === 'reset') { rmSync(POLICY, { force: true }); policyCache = { mtime: -1, value: null }; console.log('Safety rules removed.'); return; }
628
660
  else {
629
661
  console.log(`shellway policy show the rules
@@ -634,6 +666,8 @@ shellway policy unblock "<command>"
634
666
  shellway policy block-deletes block delete commands (rm, del, Remove-Item, format ...)
635
667
  shellway policy commands on|off off = file tools only, no commands
636
668
  shellway policy backups on|off keep a copy of a file before the AI changes it
669
+ shellway policy keep-awake on|off stop the computer from sleeping while Shellway runs
670
+ shellway policy desktop on|off let the AI see the screen, open/close apps, click and type (off by default)
637
671
  shellway policy reset remove all rules`);
638
672
  return;
639
673
  }
@@ -641,11 +675,193 @@ shellway policy reset remove all rules`);
641
675
  show();
642
676
  }
643
677
 
678
+ // ---- W1: on Windows, commands written in PowerShell run in powershell.exe; cmd-style commands keep using cmd.exe ----
679
+ 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]+/;
680
+ const isPsCommand = (command) => !/^\s*(?:powershell|pwsh)(?:\.exe)?\b/i.test(command) && PS_HINT.test(command);
681
+ const looksLikePowerShell = (command) => platform() === 'win32' && isPsCommand(command);
682
+ // PowerShell scripts run from a temporary .ps1 file (-File), never -EncodedCommand: Windows Defender blocks
683
+ // encoded commands that touch the screen or the keyboard. The file is deleted when PowerShell exits.
684
+ let psSeq = 0;
685
+ function psSpawn(script, opts = {}) {
686
+ const dir = join(CONF_DIR, 'ps');
687
+ mkdirSync(dir, { recursive: true });
688
+ const file = join(dir, `run-${process.pid}-${Date.now()}-${++psSeq}.ps1`);
689
+ writeFileSync(file, '\ufeff' + script, 'utf8'); // BOM: Windows PowerShell 5 reads the file as UTF-8
690
+ const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', file], { ...opts, shell: false, windowsHide: true });
691
+ const clean = () => { try { rmSync(file, { force: true }); } catch {} };
692
+ child.on('close', clean); child.on('error', clean);
693
+ return child;
694
+ }
695
+ function shellSpawn(command, opts) {
696
+ if (looksLikePowerShell(command)) return psSpawn(`[Console]::OutputEncoding=[Text.Encoding]::UTF8\n${command}`, opts);
697
+ return spawn(command, { ...opts, shell: true, windowsHide: true });
698
+ }
699
+ export { looksLikePowerShell, isPsCommand };
700
+
701
+ // Run a PowerShell script and return its stdout (desktop tools, keep-awake).
702
+ function runPs(script, timeoutMs = 30_000) {
703
+ return new Promise((done, fail) => {
704
+ const c = psSpawn(script);
705
+ let out = '', err = '';
706
+ const t = setTimeout(() => { try { c.kill(); } catch {} fail(new Error('PowerShell timed out')); }, timeoutMs);
707
+ c.stdout.on('data', (d) => { if (out.length < 30_000_000) out += d; });
708
+ c.stderr.on('data', (d) => { if (err.length < 100_000) err += d; });
709
+ c.on('error', (e) => { clearTimeout(t); fail(e); });
710
+ 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}`)); });
711
+ });
712
+ }
713
+
714
+ // ---- W3: keep the computer awake while the agent runs (policy keep_awake) ----
715
+ let awakeChild = null;
716
+ function keepAwakeTick() {
717
+ const pol = loadPolicy();
718
+ const want = !!(pol && pol.keep_awake);
719
+ if (want && !awakeChild) {
720
+ try {
721
+ const os = platform();
722
+ if (os === 'win32') {
723
+ 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' });
724
+ } else if (os === 'darwin') {
725
+ awakeChild = spawn('caffeinate', ['-i', '-w', String(process.pid)], { stdio: 'ignore' });
726
+ } else {
727
+ awakeChild = spawn('systemd-inhibit', ['--what=sleep:idle', '--who=Shellway', '--why=Shellway keep-awake', '--mode=block', 'sleep', 'infinity'], { stdio: 'ignore' });
728
+ }
729
+ awakeChild.on('exit', () => { awakeChild = null; });
730
+ awakeChild.on('error', () => { awakeChild = null; });
731
+ } catch { awakeChild = null; }
732
+ } else if (!want && awakeChild) {
733
+ try { awakeChild.kill(); } catch {}
734
+ awakeChild = null;
735
+ }
736
+ }
737
+ process.on('exit', () => { try { awakeChild && awakeChild.kill(); } catch {} });
738
+
739
+ // ---- W5–W7: screen, windows and apps, mouse and keyboard (policy desktop, off by default) ----
740
+ const MAX_SHOT_W = 1280;
741
+ const b64 = (s) => Buffer.from(String(s), 'utf8').toString('base64');
742
+ // No P/Invoke here: Windows Defender flags screen capture combined with DllImport. Screenshot and mouse both use
743
+ // the same logical screen coordinates, so clicks still land where the screenshot shows.
744
+ 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";
745
+ // SendKeys text: special characters wrapped in braces, new lines as Enter.
746
+ function sendKeysText(t) {
747
+ return [...String(t)].map((ch) => ('+^%~(){}[]'.includes(ch) ? `{${ch}}` : ch === '\n' ? '{ENTER}' : ch === '\r' ? '' : ch === '\t' ? '{TAB}' : ch)).join('');
748
+ }
749
+ const KEY_NAMES = { enter: '{ENTER}', return: '{ENTER}', tab: '{TAB}', esc: '{ESC}', escape: '{ESC}', backspace: '{BACKSPACE}', delete: '{DEL}', del: '{DEL}', insert: '{INSERT}',
750
+ up: '{UP}', down: '{DOWN}', left: '{LEFT}', right: '{RIGHT}', home: '{HOME}', end: '{END}', pageup: '{PGUP}', pagedown: '{PGDN}', space: ' ', capslock: '{CAPSLOCK}', printscreen: '{PRTSC}' };
751
+ // "ctrl+l enter alt+f4" -> SendKeys string; throws on keys SendKeys cannot press.
752
+ function sendKeysCombo(keys) {
753
+ const parts = String(keys || '').trim().split(/\s+/).filter(Boolean);
754
+ if (!parts.length) throw new Error('keys is required, for example "ctrl+l" or "enter"');
755
+ return parts.map((combo) => {
756
+ const ks = combo.toLowerCase().split('+').filter(Boolean);
757
+ let mods = '', key = '';
758
+ for (const k of ks) {
759
+ if (k === 'ctrl' || k === 'control') mods += '^';
760
+ else if (k === 'shift') mods += '+';
761
+ else if (k === 'alt') mods += '%';
762
+ 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.');
763
+ else if (KEY_NAMES[k]) key = KEY_NAMES[k];
764
+ else if (/^f([1-9]|1[0-6])$/.test(k)) key = `{${k.toUpperCase()}}`;
765
+ else if (k.length === 1) key = sendKeysText(k);
766
+ else throw new Error(`Unknown key "${k}"`);
767
+ }
768
+ if (!key) throw new Error(`No key in "${combo}"`);
769
+ return mods ? `${mods}${key.length > 1 && !key.startsWith('{') ? `(${key})` : key}` : key;
770
+ }).join('');
771
+ }
772
+ export { sendKeysText, sendKeysCombo };
773
+ const notSupported = () => { throw new Error(`This desktop tool is not available on ${platform()} yet (Windows only for now).`); };
774
+ const desktopHandlers = {
775
+ async take_screenshot() {
776
+ const os = platform();
777
+ if (os === 'darwin') {
778
+ const f = join(CONF_DIR, `shot-${process.pid}.jpg`);
779
+ 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())));
780
+ await new Promise((ok) => execFile('sips', ['-Z', String(MAX_SHOT_W), f], () => ok()));
781
+ const data = (await readFile(f)).toString('base64');
782
+ await rm(f, { force: true });
783
+ return { type: 'image', mimeType: 'image/jpeg', data, note: 'Screenshot of the main screen (macOS). Mouse and keyboard tools are Windows-only for now.' };
784
+ }
785
+ // Windows: script-based screen capture is flagged by Windows Defender (AMSI) as malware-like, so it is not
786
+ // offered. Seeing the screen on Windows needs a signed native helper (planned) or the Claude desktop app.
787
+ throw new Error(os === 'win32'
788
+ ? '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.'
789
+ : `Screenshots are not available on ${os} yet.`);
790
+ },
791
+ async list_windows() {
792
+ if (platform() !== 'win32') notSupported();
793
+ 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 }");
794
+ return out ? `pid app window title\n${out}` : '(no open windows: the screen may be locked, or no apps are open)';
795
+ },
796
+ async open_app({ name, args: a }) {
797
+ if (typeof name !== 'string' || !name.trim()) throw new Error('name is required, for example "chrome", "notepad" or a full path');
798
+ if (platform() === 'darwin') {
799
+ await new Promise((ok, no) => execFile('open', ['-a', name, ...(a ? ['--args', ...String(a).split(' ')] : [])], (e) => (e ? no(new Error(`Could not open ${name}`)) : ok())));
800
+ return `Opened ${name}`;
801
+ }
802
+ if (platform() !== 'win32') notSupported();
803
+ 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 }`);
804
+ return `Opened ${name}${a ? ` ${a}` : ''}. Use list_windows to check it.`;
805
+ },
806
+ async close_app({ pid, name, force }) {
807
+ if (platform() !== 'win32') notSupported();
808
+ if (!pid && !name) throw new Error('pid or name is required (see list_windows)');
809
+ const sel = pid ? `Get-Process -Id ${Number(pid) | 0}` : `Get-Process -Name ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(String(name).replace(/\.exe$/i, ''))}')))`;
810
+ 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`);
811
+ return `${force ? 'Stopped' : 'Asked to close'} ${out}${force ? '' : '. Unsaved work may show a save dialog; use list_windows to check.'}`;
812
+ },
813
+ async focus_window({ pid, title }) {
814
+ if (platform() !== 'win32') notSupported();
815
+ if (!pid && !title) throw new Error('pid or title is required (see list_windows)');
816
+ const target = pid ? String(Number(pid) | 0) : `[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(title)}'))`;
817
+ const out = await runPs(`$ok=(New-Object -ComObject WScript.Shell).AppActivate(${target})\nif ($ok) { 'focused' } else { 'not found' }`);
818
+ if (out !== 'focused') throw new Error('Window not found. Use list_windows to see open windows.');
819
+ return 'Window brought to the front.';
820
+ },
821
+ async mouse_click({ x, y, button, double }) {
822
+ if (platform() !== 'win32') notSupported();
823
+ const X = Number(x), Y = Number(y);
824
+ if (!Number.isFinite(X) || !Number.isFinite(Y) || X < 0 || Y < 0) throw new Error('x and y (screen pixels) are required');
825
+ const [dn, up] = button === 'right' ? [8, 16] : [2, 4];
826
+ const times = double ? 2 : 1;
827
+ 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 }`);
828
+ return `${double ? 'Double-clicked' : 'Clicked'} ${button === 'right' ? 'right ' : ''}at ${X},${Y}. Ask the user to confirm the result if needed.`;
829
+ },
830
+ async type_text({ text: t }) {
831
+ if (platform() !== 'win32') notSupported();
832
+ if (typeof t !== 'string' || !t) throw new Error('text is required');
833
+ if (t.length > 5000) throw new Error('text is too long (max 5000 characters); paste longer text with write_file instead');
834
+ await runPs(`Add-Type -AssemblyName System.Windows.Forms\n[System.Windows.Forms.SendKeys]::SendWait([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(sendKeysText(t))}')))`);
835
+ return `Typed ${t.length} characters into the active window.`;
836
+ },
837
+ async press_keys({ keys }) {
838
+ if (platform() !== 'win32') notSupported();
839
+ const seq = sendKeysCombo(keys);
840
+ await runPs(`Add-Type -AssemblyName System.Windows.Forms\n[System.Windows.Forms.SendKeys]::SendWait([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(seq)}')))`);
841
+ return `Pressed ${keys}.`;
842
+ },
843
+ };
844
+ const DESKTOP_METHODS = new Set(Object.keys(desktopHandlers));
845
+ const DESKTOP_CONTROL = new Set(['open_app', 'close_app', 'focus_window', 'mouse_click', 'type_text', 'press_keys']);
846
+ function checkDesktop(method, params) {
847
+ if (!DESKTOP_METHODS.has(method)) return;
848
+ const pol = loadPolicy();
849
+ 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');
850
+ 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.');
851
+ if (method === 'open_app' || method === 'press_keys') {
852
+ const hit = blockedBy(`${params.name || ''} ${params.args || ''} ${params.keys || ''}`, pol);
853
+ if (hit) throw new Error(`Blocked: "${hit}" is on this computer's list of blocked commands.`);
854
+ }
855
+ }
856
+
857
+ Object.assign(handlers, desktopHandlers);
858
+
644
859
  // One entry point for every request from the relay, so it can be tested without a network.
645
860
  async function dispatch(method, params) {
646
861
  if (readonly && writeMethods.has(method)) throw new Error('This computer is in read-only mode');
647
862
  const h = handlers[method];
648
863
  if (!h) throw new Error(`unknown method ${method}`);
864
+ checkDesktop(method, params || {});
649
865
  const p = checkPolicy(method, params || {});
650
866
  const note = await backupBeforeChange(method, p);
651
867
  const r = await h(p);
@@ -662,6 +878,8 @@ async function tokenValid(conf) {
662
878
 
663
879
  function start() {
664
880
  const conf = loadConf();
881
+ keepAwakeTick();
882
+ setInterval(keepAwakeTick, 60_000);
665
883
  const wsUrl = conf.server.replace(/^http/, 'ws') + '/agent';
666
884
  let delay = 1000;
667
885
  const connect = async () => {