shellway 0.8.11 → 0.8.12
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 +107 -12
package/package.json
CHANGED
package/shellway.js
CHANGED
|
@@ -10,7 +10,7 @@ import { readFile, writeFile, appendFile, readdir, stat, lstat, mkdir, rename, c
|
|
|
10
10
|
import { createServer as netServer, connect as netConnect } from 'node:net';
|
|
11
11
|
import { randomBytes, timingSafeEqual, createHash } from 'node:crypto';
|
|
12
12
|
|
|
13
|
-
const AGENT_VERSION = '0.8.
|
|
13
|
+
const AGENT_VERSION = '0.8.12'; // keep equal to agent/package.json
|
|
14
14
|
if (Number(process.versions.node.split('.')[0]) < 22) {
|
|
15
15
|
console.error(`Shellway needs Node.js 22 or newer (you have ${process.versions.node}). Get it at https://nodejs.org`);
|
|
16
16
|
process.exit(1);
|
|
@@ -720,7 +720,20 @@ shellway policy reset remove all rules`);
|
|
|
720
720
|
|
|
721
721
|
// ---- W1: on Windows, commands written in PowerShell run in powershell.exe; cmd-style commands keep using cmd.exe ----
|
|
722
722
|
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]+/;
|
|
723
|
-
|
|
723
|
+
// 29 Nov 2026 (owner PC test, B5): "node a.mjs x.db; node -v" ran in cmd.exe, which has no ";" separator, and created a file
|
|
724
|
+
// named "x.db;". A ";" outside quotes followed by a space and a command means PowerShell, unless the command uses cmd syntax.
|
|
725
|
+
const CMD_SYNTAX = /%[A-Za-z_][\w]*%|&&|\|\||(?:^|\s)&(?=\s|$)|^\s*(?:set|if|for|rem|call)\s/i;
|
|
726
|
+
function hasPsChain(command) {
|
|
727
|
+
let q = null;
|
|
728
|
+
for (let i = 0; i < command.length; i++) {
|
|
729
|
+
const ch = command[i];
|
|
730
|
+
if (q) { if (ch === q) q = null; continue; }
|
|
731
|
+
if (ch === '"' || ch === "'") { q = ch; continue; }
|
|
732
|
+
if (ch === ';' && /^\s+[A-Za-z.\\/$]/.test(command.slice(i + 1))) return true;
|
|
733
|
+
}
|
|
734
|
+
return false;
|
|
735
|
+
}
|
|
736
|
+
const isPsCommand = (command) => !/^\s*(?:powershell|pwsh)(?:\.exe)?\b/i.test(command) && (PS_HINT.test(command) || (hasPsChain(command) && !CMD_SYNTAX.test(command)));
|
|
724
737
|
const looksLikePowerShell = (command) => platform() === 'win32' && isPsCommand(command);
|
|
725
738
|
// PowerShell scripts run from a temporary .ps1 file (-File), never -EncodedCommand: Windows Defender blocks
|
|
726
739
|
// encoded commands that touch the screen or the keyboard. The file is deleted when PowerShell exits.
|
|
@@ -813,6 +826,81 @@ function sendKeysCombo(keys) {
|
|
|
813
826
|
}).join('');
|
|
814
827
|
}
|
|
815
828
|
export { sendKeysText, sendKeysCombo };
|
|
829
|
+
// 29 Nov 2026 (owner PC test, B9/B10): know which window is in front before typing, wait until it accepts input,
|
|
830
|
+
// type in small pieces, stop if another window comes to the front, and read the field back where Windows allows it
|
|
831
|
+
// (only found / not found is reported: the field's text never leaves the computer).
|
|
832
|
+
const psDec = (s) => "[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('" + b64(s) + "'))";
|
|
833
|
+
const FG_PS = [
|
|
834
|
+
'[Console]::OutputEncoding=[Text.Encoding]::UTF8',
|
|
835
|
+
'Add-Type -AssemblyName System.Windows.Forms',
|
|
836
|
+
"Add-Type -Name F -Namespace SwFg -MemberDefinition '[DllImport(\"user32.dll\")] public static extern IntPtr GetForegroundWindow(); [DllImport(\"user32.dll\", CharSet=CharSet.Unicode)] public static extern int GetWindowText(IntPtr h, System.Text.StringBuilder s, int n); [DllImport(\"user32.dll\")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint p); [DllImport(\"user32.dll\", EntryPoint=\"SendMessageTimeoutW\")] public static extern IntPtr SmtoN(IntPtr h, uint m, IntPtr w, IntPtr l, uint f, uint t, out IntPtr r); [DllImport(\"user32.dll\", CharSet=CharSet.Unicode, EntryPoint=\"SendMessageTimeoutW\")] public static extern IntPtr SmtoS(IntPtr h, uint m, IntPtr w, System.Text.StringBuilder l, uint f, uint t, out IntPtr r);'",
|
|
837
|
+
'function Fg { $h=[SwFg.F]::GetForegroundWindow(); $sb=New-Object System.Text.StringBuilder 512; [void][SwFg.F]::GetWindowText($h,$sb,512); $p=[uint32]0; [void][SwFg.F]::GetWindowThreadProcessId($h,[ref]$p); $n=""; try { $n=(Get-Process -Id $p -ErrorAction Stop).ProcessName } catch {}; return @{h=$h; t=$sb.ToString(); p=$p; n=$n} }',
|
|
838
|
+
'function Line($k,$w) { return ($k + "|" + $w.n + "|" + $w.p + "|" + ($w.t -replace "[\\r\\n|]"," ")) }',
|
|
839
|
+
].join('\n');
|
|
840
|
+
function winGatePs(expect) {
|
|
841
|
+
return FG_PS + '\n$exp=' + psDec(expect || '') + '\n$a=Fg\n'
|
|
842
|
+
+ 'if ($exp -and -not $a.t.ToLower().Contains($exp.ToLower())) { Line "WRONGWIN" $a; exit }\n'
|
|
843
|
+
+ 'try { [void](Get-Process -Id $a.p -ErrorAction Stop).WaitForInputIdle(3000) } catch {}\n';
|
|
844
|
+
}
|
|
845
|
+
// text -> SendKeys pieces of at most 20 characters each: {k: keys, n: characters}
|
|
846
|
+
function keyChunks(t, size = 20) {
|
|
847
|
+
const chars = [...String(t)];
|
|
848
|
+
const out = [];
|
|
849
|
+
for (let i = 0; i < chars.length; i += size) { const part = chars.slice(i, i + size); out.push({ k: part.map((ch) => sendKeysText(ch)).join(''), n: part.length }); }
|
|
850
|
+
return out;
|
|
851
|
+
}
|
|
852
|
+
function typePs(t, expect) {
|
|
853
|
+
return winGatePs(expect)
|
|
854
|
+
+ 'Start-Sleep -Milliseconds 120\n'
|
|
855
|
+
+ '$chunks=ConvertFrom-Json -InputObject (' + psDec(JSON.stringify(keyChunks(t))) + ')\n'
|
|
856
|
+
+ '$sent=0\n'
|
|
857
|
+
+ 'foreach ($c in $chunks) { $b=Fg; if ($b.h -ne $a.h) { Line ("MOVED|" + $sent) $b; exit }; [System.Windows.Forms.SendKeys]::SendWait($c.k); $sent += $c.n; Start-Sleep -Milliseconds 25 }\n'
|
|
858
|
+
+ 'Start-Sleep -Milliseconds 150\n'
|
|
859
|
+
+ '$plain=' + psDec(String(t).replace(/\r/g, '')) + '\n'
|
|
860
|
+
+ '$chk="UNKNOWN"\n'
|
|
861
|
+
+ 'try { Add-Type -AssemblyName UIAutomationClient,UIAutomationTypes; $el=[System.Windows.Automation.AutomationElement]::FocusedElement; $txt=$null; $pt=$null\n'
|
|
862
|
+
+ ' if ($el -and -not $el.Current.IsPassword) { if ($el.TryGetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern,[ref]$pt)) { $txt=$pt.Current.Value } elseif ($el.TryGetCurrentPattern([System.Windows.Automation.TextPattern]::Pattern,[ref]$pt)) { $txt=$pt.DocumentRange.GetText(2000000) } }\n'
|
|
863
|
+
+ ' if ($txt -eq $null -and $el -and -not $el.Current.IsPassword) { $hw=[IntPtr]$el.Current.NativeWindowHandle; if ($hw -ne [IntPtr]::Zero) { $r=[IntPtr]::Zero; if ([SwFg.F]::SmtoN($hw,0x0E,[IntPtr]::Zero,[IntPtr]::Zero,2,1000,[ref]$r) -ne [IntPtr]::Zero) { $len=[int64]$r; if ($len -gt 0 -and $len -lt 2000000) { $sb2=New-Object System.Text.StringBuilder ([int]$len+1); if ([SwFg.F]::SmtoS($hw,0x0D,[IntPtr]([int]$len+1),$sb2,2,1000,[ref]$r) -ne [IntPtr]::Zero) { $txt=$sb2.ToString() } } } } }\n'
|
|
864
|
+
+ ' if ($txt -ne $null) { if (($txt -replace "`r","").Contains($plain)) { $chk="FOUND" } else { $chk="MISSING" } } } catch {}\n'
|
|
865
|
+
+ 'Line ("DONE|" + $chk) $a';
|
|
866
|
+
}
|
|
867
|
+
function openPs(name, a) {
|
|
868
|
+
return FG_PS + '\n$n=' + psDec(name) + '\n$a=' + psDec(a || '') + '\n$b=Fg\nif ($a) { Start-Process -FilePath $n -ArgumentList $a } else { Start-Process -FilePath $n }\n$w=$b; $k="SAME"; $last=$b.h; $stable=0\nfor ($i=0; $i -lt 30; $i++) { Start-Sleep -Milliseconds 200; $w=Fg; if ($w.h -ne $last) { $last=$w.h; $stable=0 } else { $stable++ }; if ($w.h -ne $b.h) { $k="FG"; if ($stable -ge 3) { break } } }\nLine $k $w';
|
|
869
|
+
}
|
|
870
|
+
function keysPs(seq, expect) {
|
|
871
|
+
return winGatePs(expect) + '[System.Windows.Forms.SendKeys]::SendWait(' + psDec(seq) + ')\nLine "DONE|NA" $a';
|
|
872
|
+
}
|
|
873
|
+
// Output of typePs / keysPs -> { chk, win } or a clear error (nothing typed / stopped part way).
|
|
874
|
+
function typedResult(out, total, expect, verb) {
|
|
875
|
+
const line = String(out || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean).reverse().find((l) => /^(DONE|MOVED|WRONGWIN)\|/.test(l));
|
|
876
|
+
if (!line) throw new Error(`Windows did not confirm the ${verb === 'type' ? 'typing' : 'key press'}; check the screen before relying on it.`);
|
|
877
|
+
const parts = line.split('|');
|
|
878
|
+
if (parts[0] === 'WRONGWIN') {
|
|
879
|
+
const [, n, p, ...t] = parts;
|
|
880
|
+
throw new Error(`Nothing ${verb === 'type' ? 'typed' : 'pressed'}: the window in front is "${t.join('|') || '(no title)'}" (${n || '?'}, pid ${p}), not one whose title contains "${expect}". Bring the right window to the front with focus_window first.`);
|
|
881
|
+
}
|
|
882
|
+
if (parts[0] === 'MOVED') {
|
|
883
|
+
const [, sent, n, p, ...t] = parts;
|
|
884
|
+
throw new Error(`Stopped after ${sent} of ${total} characters: another window came to the front ("${t.join('|') || '(no title)'}", ${n || '?'}, pid ${p}). Check what was typed before going on.`);
|
|
885
|
+
}
|
|
886
|
+
const [, chk, n, p, ...t] = parts;
|
|
887
|
+
return { chk, win: `"${t.join('|') || '(no title)'}" (${n || '?'}, pid ${p})` };
|
|
888
|
+
}
|
|
889
|
+
function typedText(r, total) {
|
|
890
|
+
if (r.chk === 'FOUND') return `Typed ${total} characters into ${r.win}. Check: the text is now in the focused field.`;
|
|
891
|
+
if (r.chk === 'MISSING') return `Typed ${total} characters into ${r.win}, but Check: the text was NOT found in the focused field afterwards. Some characters may not have arrived (the app may still have been loading) or the field changes what is typed. Look (take_screenshot) before relying on it.`;
|
|
892
|
+
return `Typed ${total} characters into ${r.win}. Windows could not read this field back, so the text is not verified.`;
|
|
893
|
+
}
|
|
894
|
+
function openedText(out, name) {
|
|
895
|
+
const line = String(out || '').split(/\r?\n/).map((l) => l.trim()).filter(Boolean).reverse().find((l) => /^(FG|SAME)\|/.test(l));
|
|
896
|
+
if (!line) return `Opened ${name}. Use list_windows to check it.`;
|
|
897
|
+
const [k, n, p, ...t] = line.split('|');
|
|
898
|
+
const win = `"${t.join('|') || '(no title)'}" (${n || '?'}, pid ${p})`;
|
|
899
|
+
return k === 'FG'
|
|
900
|
+
? `Opened ${name}. In front now: ${win}. If that window holds the user's own documents or tabs, do not type into it: open a new empty one first (e.g. ctrl+n).`
|
|
901
|
+
: `Opened ${name}, but no new window came to the front (in front: ${win}). Use list_windows to check it.`;
|
|
902
|
+
}
|
|
903
|
+
export { keyChunks, typedResult, typedText, openedText, typePs, keysPs, openPs, focusPs, focusResult };
|
|
816
904
|
const notSupported = () => { throw new Error(`This desktop tool is not available on ${platform()} yet (Windows only for now).`); };
|
|
817
905
|
const desktopHandlers = {
|
|
818
906
|
async take_screenshot() {
|
|
@@ -843,8 +931,8 @@ const desktopHandlers = {
|
|
|
843
931
|
return `Opened ${name}`;
|
|
844
932
|
}
|
|
845
933
|
if (platform() !== 'win32') notSupported();
|
|
846
|
-
await runPs(
|
|
847
|
-
return
|
|
934
|
+
const out = await runPs(openPs(name, a));
|
|
935
|
+
return openedText(out, `${name}${a ? ` ${a}` : ''}`);
|
|
848
936
|
},
|
|
849
937
|
async close_app({ pid, name, force }) {
|
|
850
938
|
if (platform() !== 'win32') notSupported();
|
|
@@ -869,32 +957,39 @@ const desktopHandlers = {
|
|
|
869
957
|
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 }`);
|
|
870
958
|
return `${double ? 'Double-clicked' : 'Clicked'} ${button === 'right' ? 'right ' : ''}at ${X},${Y}. Ask the user to confirm the result if needed.`;
|
|
871
959
|
},
|
|
872
|
-
async type_text({ text: t }) {
|
|
960
|
+
async type_text({ text: t, expect_window: ew }) {
|
|
873
961
|
if (platform() !== 'win32') notSupported();
|
|
874
962
|
if (typeof t !== 'string' || !t) throw new Error('text is required');
|
|
875
963
|
if (t.length > 5000) throw new Error('text is too long (max 5000 characters); paste longer text with write_file instead');
|
|
876
|
-
|
|
877
|
-
return
|
|
964
|
+
const exp = typeof ew === 'string' ? ew.trim() : '';
|
|
965
|
+
return typedText(typedResult(await runPs(typePs(t, exp)), [...t].length, exp, 'type'), [...t].length);
|
|
878
966
|
},
|
|
879
|
-
async press_keys({ keys }) {
|
|
967
|
+
async press_keys({ keys, expect_window: ew }) {
|
|
880
968
|
if (platform() !== 'win32') notSupported();
|
|
881
969
|
const seq = sendKeysCombo(keys);
|
|
882
|
-
|
|
883
|
-
|
|
970
|
+
const exp = typeof ew === 'string' ? ew.trim() : '';
|
|
971
|
+
const r = typedResult(await runPs(keysPs(seq, exp)), 0, exp, 'keys');
|
|
972
|
+
return `Pressed ${keys} in ${r.win}.`;
|
|
884
973
|
},
|
|
885
974
|
};
|
|
886
975
|
// 0.8.8: Windows calls to restore a minimised window and bring it to the front (same Add-Type pattern as mouse_click).
|
|
887
|
-
|
|
976
|
+
// 0.8.12 (owner PC test 29 Nov): SetForegroundWindow alone was refused while Edge was in front, yet the reply said
|
|
977
|
+
// "brought to the front"; now the input of the foreground thread is attached first and the result is checked.
|
|
978
|
+
const WIN_API = `Add-Type -Name W -Namespace SwWin -MemberDefinition '[DllImport("user32.dll")] public static extern bool ShowWindowAsync(IntPtr h,int c); [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h); [DllImport("user32.dll")] public static extern bool IsIconic(IntPtr h); [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow(); [DllImport("user32.dll")] public static extern bool BringWindowToTop(IntPtr h); [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, IntPtr p); [DllImport("kernel32.dll")] public static extern uint GetCurrentThreadId(); [DllImport("user32.dll")] public static extern bool AttachThreadInput(uint a, uint b, bool f);'`;
|
|
888
979
|
function focusPs(pid, title) {
|
|
889
980
|
const find = pid
|
|
890
981
|
? `$p=@(Get-Process -Id ${pid} -ErrorAction SilentlyContinue | Where-Object { $_.MainWindowHandle -ne 0 })[0]`
|
|
891
982
|
: "$all=@(Get-Process | Where-Object { $_.MainWindowTitle })\n$p=@($all | Where-Object { $_.MainWindowTitle -eq $t })[0]\nif (-not $p) { $p=@($all | Where-Object { $_.MainWindowTitle.ToLower().Contains($t.ToLower()) })[0] }";
|
|
892
983
|
return `[Console]::OutputEncoding=[Text.Encoding]::UTF8\n${WIN_API}\n$t=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(title || '')}'))\n${find}\n`
|
|
893
|
-
+ "if ($p) { $h=$p.MainWindowHandle; $m=[SwWin.W]::IsIconic($h); if ($m) { [void][SwWin.W]::ShowWindowAsync($h,9); Start-Sleep -Milliseconds 250 }; [void](New-Object -ComObject WScript.Shell).AppActivate($p.Id); [void][SwWin.W]::SetForegroundWindow($h);
|
|
984
|
+
+ "if ($p) { $h=$p.MainWindowHandle; $m=[SwWin.W]::IsIconic($h); if ($m) { [void][SwWin.W]::ShowWindowAsync($h,9); Start-Sleep -Milliseconds 250 }; [void](New-Object -ComObject WScript.Shell).AppActivate($p.Id); [void][SwWin.W]::SetForegroundWindow($h); Start-Sleep -Milliseconds 120\n"
|
|
985
|
+
+ " if ([SwWin.W]::GetForegroundWindow() -ne $h) { $fg=[SwWin.W]::GetForegroundWindow(); $ft=[SwWin.W]::GetWindowThreadProcessId($fg,[IntPtr]::Zero); $me=[SwWin.W]::GetCurrentThreadId(); [void][SwWin.W]::AttachThreadInput($me,$ft,$true); [void][SwWin.W]::BringWindowToTop($h); [void][SwWin.W]::SetForegroundWindow($h); [void][SwWin.W]::AttachThreadInput($me,$ft,$false); Start-Sleep -Milliseconds 150 }\n"
|
|
986
|
+
+ " $k = if ([SwWin.W]::GetForegroundWindow() -eq $h) { 'FOCUSED|' } else { 'NOTFRONT|' }; $k + $m + '|' + $p.Id + '|' + $p.ProcessName + '|' + $p.MainWindowTitle }\n"
|
|
894
987
|
+ "else { 'NOTFOUND'; Get-Process | Where-Object { $_.MainWindowTitle } | Sort-Object ProcessName | Select-Object -First 25 | ForEach-Object { '{0} {1} {2}' -f $_.Id, $_.ProcessName, $_.MainWindowTitle } }";
|
|
895
988
|
}
|
|
896
989
|
function focusResult(out, pid, title) {
|
|
897
990
|
const lines = String(out || '').split(/\r?\n/).map((l) => l.trimEnd());
|
|
991
|
+
const nf = lines.find((l) => l.startsWith('NOTFRONT|'));
|
|
992
|
+
if (nf) { const [, , id, app, ...tt] = nf.split('|'); throw new Error(`Windows did not let "${tt.join('|') || '(no title)'}" (${app}, pid ${id}) come to the front, so do not type or press keys now: they would go to the window that is in front. Ask the user to click that window, or try focus_window again.`); }
|
|
898
993
|
const f = lines.find((l) => l.startsWith('FOCUSED|'));
|
|
899
994
|
if (f) { const [, min, id, app, ...tt] = f.split('|'); return `Window brought to the front: ${tt.join('|') || '(no title)'} (${app}, pid ${id})${/true/i.test(min) ? '. It was minimised and has been restored.' : '.'}`; }
|
|
900
995
|
const rest = lines.filter((l) => l && l !== 'NOTFOUND');
|