shellway 0.8.10 → 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.
@@ -33,6 +33,8 @@ let port = null;
33
33
  let connected = false;
34
34
  let agentVersion = '';
35
35
  let lastError = '';
36
+ // 0.8.7 (Konstantin KO18): separate statuses for the popup
37
+ let lastErrorAt = 0, lastHandshakeAt = 0, serverLink = null, appPid = null;
36
38
  const attached = new Set();
37
39
  const groupByWindow = new Map();
38
40
  let idleTimer = null;
@@ -82,7 +84,7 @@ async function connect() {
82
84
  port.onMessage.addListener(onMessage);
83
85
  port.onDisconnect.addListener(() => {
84
86
  const err = chrome.runtime.lastError && chrome.runtime.lastError.message;
85
- if (err) lastError = /not found/i.test(err) ? 'The Shellway app is not set up for the extension on this computer. Run: npx shellway@beta policy browser extension' : err;
87
+ if (err) { lastError = /not found/i.test(err) ? 'The Shellway app is not set up for the extension on this computer. Run: npx shellway@beta policy browser extension' : /forbidden/i.test(err) ? 'This copy of the extension is not allowed by the Shellway app (different extension ID). Load the folder the app created (Shellway Extension in your user folder) or use the store version.' : err; lastErrorAt = Date.now(); }
86
88
  port = null; connected = false; badge(); detachAll();
87
89
  });
88
90
  badge();
@@ -104,7 +106,7 @@ function browserName() {
104
106
  async function onMessage(m) {
105
107
  if (!m || typeof m !== 'object') return;
106
108
  if (m.type === 'hello') {
107
- connected = true; agentVersion = m.version || ''; lastError = ''; badge();
109
+ connected = true; agentVersion = m.version || ''; lastError = ''; lastHandshakeAt = Date.now(); serverLink = m.server || null; appPid = m.pid || null; badge();
108
110
  // 0.7.2: the Shellway app refreshed this extension's folder (a newer version): reload once to use the new files.
109
111
  const mine = chrome.runtime.getManifest().version;
110
112
  if (port) port.postMessage({ type: 'ext', version: mine, browser: browserName() }); // 0.7.3: version; 0.8.6: and which browser
@@ -114,7 +116,9 @@ async function onMessage(m) {
114
116
  }
115
117
  return;
116
118
  }
117
- if (m.type === 'error') { lastError = m.message || 'error'; return; }
119
+ if (m.type === 'status') { serverLink = m.server || null; return; }
120
+ if (m.type === 'refused') { lastError = m.message || 'The Shellway app refused the link.'; lastErrorAt = Date.now(); connected = false; badge(); return; }
121
+ if (m.type === 'error') { lastError = m.message || 'error'; lastErrorAt = Date.now(); return; }
118
122
  if (m.id === undefined) return;
119
123
  try {
120
124
  const result = await handle(m.op, m.args || {});
@@ -229,7 +233,7 @@ chrome.runtime.onMessage.addListener((msg, _sender, reply) => {
229
233
  if (msg.cmd === 'clear-activity') await chrome.storage.session.set({ activity: [] });
230
234
  const s = await getSettings();
231
235
  const { activity = [] } = await chrome.storage.session.get({ activity: [] });
232
- reply({ enabled: s.enabled, blocked: s.blocked, allTabs: s.allTabs, connected, connecting: !!port && !connected, agentVersion, lastError, working: attached.size, activity, version: chrome.runtime.getManifest().version });
236
+ reply({ enabled: s.enabled, blocked: s.blocked, allTabs: s.allTabs, connected, connecting: !!port && !connected, agentVersion, lastError, lastErrorAt, lastHandshakeAt, serverLink, appPid, working: attached.size, activity, version: chrome.runtime.getManifest().version });
233
237
  })();
234
238
  return true;
235
239
  });
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Shellway",
4
- "version": "0.8.6",
4
+ "version": "0.8.7",
5
5
  "description": "Lets your AI (ChatGPT, Claude) use this browser through the Shellway app on your computer. Off until you turn it on.",
6
6
  "key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnZWALJr6dwkQu7eX3reFbtgMAErsCyODHKnwz97XMKpR9bAz4+irBlJ2KEXD6ERZFjuKYqNZ2HLe0eQp5y9fWscyWeTUXNTstsFaymsb5C0aRcpW/dXRl2Dy9vQ7y7+ATH4SCxcckncfmEXt4GFQ6TtyPsctuQfYez6o9MHmwGaKwpCPaWmqfYqomy0yjzMCbCg2b0aP2+hDmOhc0KARhGVnzlZBIBSybtkpAmzXfUxMJHDD5ly3g6ScCcR+3Zf7SKyCfLMGSkwYwiJvvS4sNCtBzwKdDdbEh865T7H5NCS8GOhSt0hxkPPxpbTlXrWXINDiSkF00/b7ZToBRTmK4QIDAQAB",
7
7
  "minimum_chrome_version": "116",
@@ -25,12 +25,17 @@
25
25
  .act li { padding: 3px 0; border-bottom: 1px solid #f0f0f2; display: flex; gap: 6px; }
26
26
  .act time { color: #888; min-width: 62px; white-space: nowrap; }
27
27
  .ver { color: #999; font-weight: 400; font-size: 11px; margin-left: auto; }
28
+ .checks { list-style: none; padding: 0; margin: 0 0 10px; font-size: 12px; }
29
+ .checks li { padding: 2px 0; display: flex; gap: 6px; }
30
+ .checks b { min-width: 14px; }
31
+ .checks .y { color: #0a7d4f; } .checks .n { color: #b00020; } .checks .q { color: #888; }
28
32
  </style>
29
33
  </head>
30
34
  <body>
31
35
  <h1><img src="icons/icon32.png" alt="">Shellway<span id="ver" class="ver"></span></h1>
32
36
  <div class="row"><span>Let my AI use this browser</span><label class="switch"><input id="on" type="checkbox"><span class="slider"></span></label></div>
33
37
  <div id="status" class="status">…</div>
38
+ <ul id="checks" class="checks"></ul>
34
39
  <p class="note">Your AI (ChatGPT, Claude) can open tabs, read pages, click, type and take screenshots here, with the sites you are already signed in to. It never types passwords or card numbers. While it works, the browser shows a "debugging this browser" bar: press <b>Cancel</b> on it to stop and turn Shellway off.</p>
35
40
  <div class="row" style="margin-top:8px"><span>AI can also use my other tabs<br><span class="note" style="margin:0">Off: only the tabs the AI opened</span></span><label class="switch"><input id="all" type="checkbox"><span class="slider"></span></label></div>
36
41
  <details open>
@@ -8,6 +8,17 @@ function render(s) {
8
8
  if (!s.enabled) st.textContent = 'Off. Turn it on to let your AI use this browser.';
9
9
  else if (s.connected) { st.className = 'status ok'; st.textContent = `Connected to the Shellway app${s.agentVersion ? ` (${s.agentVersion})` : ''}.${s.working ? ' The AI is working in a tab now.' : ''}`; }
10
10
  else { st.className = 'status warn'; st.textContent = s.lastError || (s.connecting ? 'Connecting to the Shellway app…' : 'Not connected. Is the Shellway app running on this computer?'); }
11
+ // 0.8.7 (KO18): one line per link, so "on" and "really connected" are not mixed up
12
+ const ago = (t) => { if (!t) return 'never'; const m = Math.round((Date.now() - t) / 60000); return m < 1 ? 'just now' : m < 60 ? `${m} min ago` : new Date(t).toLocaleString([], { day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit' }); };
13
+ const rows = [
14
+ [s.enabled, `Browser control: ${s.enabled ? 'on' : 'off'}`],
15
+ [s.connected, `Shellway app on this computer: ${s.connected ? `connected${s.agentVersion ? ' (' + s.agentVersion + ')' : ''}` : s.connecting ? 'connecting…' : 'not connected'}`],
16
+ [s.connected && s.serverLink ? !!s.serverLink.up : null, `App's link to the Shellway server: ${!s.connected || !s.serverLink ? 'unknown' : s.serverLink.up ? `connected (${s.serverLink.link === 'https' ? 'HTTPS fallback' : 'WebSocket'})` : 'not connected'}`],
17
+ [s.lastHandshakeAt ? true : null, `Last successful handshake: ${ago(s.lastHandshakeAt)}`],
18
+ [s.lastError ? false : null, `Last error: ${s.lastError ? s.lastError + ' (' + ago(s.lastErrorAt) + ')' : 'none'}`],
19
+ ];
20
+ const ck = $('checks'); ck.textContent = '';
21
+ for (const [ok, t] of rows) { const li = document.createElement('li'); const b = document.createElement('b'); b.className = ok === true ? 'y' : ok === false ? 'n' : 'q'; b.textContent = ok === true ? '✓' : ok === false ? '✗' : '•'; const sp = document.createElement('span'); sp.textContent = t; li.append(b, sp); ck.append(li); }
11
22
  if (!blockedShown) { $('blocked').value = s.blocked.join('\n'); blockedShown = true; }
12
23
  $('all').checked = !!s.allTabs;
13
24
  $('ver').textContent = s.version ? 'v' + s.version : '';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "shellway",
3
- "version": "0.8.10",
3
+ "version": "0.8.12",
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
@@ -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.10'; // keep equal to agent/package.json
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
- const isPsCommand = (command) => !/^\s*(?:powershell|pwsh)(?:\.exe)?\b/i.test(command) && PS_HINT.test(command);
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(`$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 }`);
847
- return `Opened ${name}${a ? ` ${a}` : ''}. Use list_windows to check it.`;
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
- await runPs(`Add-Type -AssemblyName System.Windows.Forms\n[System.Windows.Forms.SendKeys]::SendWait([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(sendKeysText(t))}')))`);
877
- return `Typed ${t.length} characters into the active window.`;
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
- await runPs(`Add-Type -AssemblyName System.Windows.Forms\n[System.Windows.Forms.SendKeys]::SendWait([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${b64(seq)}')))`);
883
- return `Pressed ${keys}.`;
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
- 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);'`;
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); 'FOCUSED|' + $m + '|' + $p.Id + '|' + $p.ProcessName + '|' + $p.MainWindowTitle }\n"
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');
@@ -1066,9 +1161,10 @@ function extAttach(sock, rest, hello = {}) {
1066
1161
  }
1067
1162
  };
1068
1163
  sock.on('data', (d) => { buf += d.toString('utf8'); take(); });
1164
+ const statusTimer = setInterval(() => { try { sock.write(JSON.stringify({ type: 'status', server: serverStatus() }) + '\n'); } catch {} }, 15_000); statusTimer.unref?.();
1069
1165
  let done = false;
1070
1166
  const gone = () => {
1071
- if (done) return; done = true;
1167
+ if (done) return; done = true; clearInterval(statusTimer);
1072
1168
  if (ext.links.get(L.browser) === L) ext.links.delete(L.browser);
1073
1169
  for (const p of L.pending.values()) { clearTimeout(p.timer); p.no(new Error('The browser extension disconnected (the browser was closed or Shellway was turned off there).')); }
1074
1170
  L.pending.clear();
@@ -1100,6 +1196,8 @@ async function extJson(path) {
1100
1196
  }
1101
1197
  const extSession = (id) => ({ send: (method, params = {}, ms = 20_000) => extCall('cdp', { id, method, params }, ms), close: () => {} });
1102
1198
  // Local endpoint for the native-messaging helper: 127.0.0.1 only, random port, a new random secret every start.
1199
+ // 0.8.11 (Konstantin KO18): the app's own link to the Shellway server, for the extension popup and doctor
1200
+ function serverStatus() { try { return { link: linkState.transport === 'poll' ? 'https' : 'websocket', up: !!linkState.up, since: linkState.connectedAt || null }; } catch { return { link: 'unknown', up: false, since: null }; } }
1103
1201
  function startExtBridge() {
1104
1202
  const token = randomBytes(24).toString('hex');
1105
1203
  const srv = netServer((sock) => {
@@ -1114,7 +1212,9 @@ function startExtBridge() {
1114
1212
  let given = '', hello = {};
1115
1213
  try { hello = JSON.parse(head.slice(0, i)) || {}; given = String(hello.token || ''); } catch {}
1116
1214
  const a = Buffer.from(given), b = Buffer.from(token);
1117
- if (a.length !== b.length || !timingSafeEqual(a, b)) { sock.destroy(); return; }
1215
+ if (a.length !== b.length || !timingSafeEqual(a, b)) { sock.destroy(); return; } // the native helper reports a link closed before the greeting
1216
+ try { sock.write(JSON.stringify({ type: 'hello', version: AGENT_VERSION, extVersion: extFolderVersion(), pid: process.pid, server: serverStatus(), browsers: [...ext.links.keys()] }) + '\n'); } catch {}
1217
+ if (hello.origin === 'doctor') { setTimeout(() => { try { sock.destroy(); } catch {} }, 200); return; } // doctor only checks the greeting
1118
1218
  extAttach(sock, head.slice(i + 1), { browser: hello.browser, origin: hello.origin });
1119
1219
  };
1120
1220
  sock.on('data', onHead);
@@ -1141,12 +1241,13 @@ function nativeHost() {
1141
1241
  const sock = netConnect(info.port, '127.0.0.1');
1142
1242
  let up = false;
1143
1243
  const origin = process.argv.find((a) => String(a).startsWith('chrome-extension://')) || '';
1144
- sock.on('connect', () => { up = true; sock.write(JSON.stringify({ token: info.token, origin }) + '\n'); frame({ type: 'hello', version: AGENT_VERSION, extVersion: extFolderVersion() }); });
1244
+ let welcomed = false; // 0.8.11: the app greets after checking the key; a link without a greeting is reported
1245
+ sock.on('connect', () => { up = true; sock.write(JSON.stringify({ token: info.token, origin }) + '\n'); setTimeout(() => { if (!welcomed) frame({ type: 'error', message: 'The Shellway app on this computer did not answer the browser link. Restart it once (run the same service install command you used to set it up, or restart the computer).' }); }, 5000).unref?.(); });
1145
1246
  const bye = (msg) => { if (msg) try { frame({ type: 'error', message: msg }); } catch {} setTimeout(() => process.exit(0), 200); };
1146
- sock.on('error', () => bye(up ? '' : 'The Shellway app is not running on this computer.'));
1147
- sock.on('close', () => bye(''));
1247
+ sock.on('error', () => bye(up ? '' : `The Shellway app is not running on this computer (nothing answers on its browser link, port ${info.port}). Start it (the service install command you used to set it up, or restart the computer).`));
1248
+ sock.on('close', () => bye(welcomed ? '' : 'The Shellway app closed the browser link before it was ready. Restart it once (run the same service install command you used to set it up, or restart the computer), then close and reopen the browser.'));
1148
1249
  let lb = '';
1149
- sock.on('data', (d) => { lb += d.toString('utf8'); let i; while ((i = lb.indexOf('\n')) >= 0) { const line = lb.slice(0, i); lb = lb.slice(i + 1); if (line) frame(line); } });
1250
+ sock.on('data', (d) => { lb += d.toString('utf8'); let i; while ((i = lb.indexOf('\n')) >= 0) { const line = lb.slice(0, i); lb = lb.slice(i + 1); if (!line) continue; if (!welcomed && /"type":"(hello|refused)"/.test(line)) welcomed = true; frame(line); } });
1150
1251
  let ib = Buffer.alloc(0);
1151
1252
  process.stdin.on('data', (d) => {
1152
1253
  ib = Buffer.concat([ib, d]);
@@ -2056,7 +2157,8 @@ function start() {
2056
2157
  writeAlive({ link: 'starting' });
2057
2158
  setInterval(() => {
2058
2159
  const t = Date.now(), slept = t - lastTick > Math.max(45_000, TICK * 3); lastTick = t;
2059
- writeAlive({ link: linkState.transport === 'poll' ? 'https' : 'websocket', up: !!(current && current.readyState === 1) });
2160
+ linkState.up = !!(current && current.readyState === 1); // 0.8.11: shown in the extension popup
2161
+ writeAlive({ link: linkState.transport === 'poll' ? 'https' : 'websocket', up: linkState.up });
2060
2162
  if (connectingSince && t - connectingSince > 30_000) {
2061
2163
  const w = current; current = null; connectingSince = 0;
2062
2164
  if (w) { w.onopen = null; w.onclose = null; w.onmessage = null; try { w.close(); } catch {} }
@@ -2091,7 +2193,7 @@ function start() {
2091
2193
  // 0.7.6: the retry delay is reset only after a link has really worked for a minute (see onclose), not on every open.
2092
2194
  conn = { openedAt: Date.now(), rx: 0, ka: 0, tx: 0, lastRx: 0, err: '' };
2093
2195
  try { ws.send(JSON.stringify({ type: 'info', v: AGENT_VERSION, node: process.versions.node, os: platform(), reason: why, ...(machineHash() ? { mid: machineHash() } : {}), ...(prevCid ? { replaced: prevCid } : {}), ...(lastClose ? { last: lastClose } : {}), caps: ['receipts'], boot: BOOT, t: transport })); } catch {}
2094
- linkState.transport = transport; linkState.connectedAt = Date.now(); linkState.links++; linkState.lastClose = lastClose; linkState.journal = journal.size;
2196
+ linkState.transport = transport; linkState.connectedAt = Date.now(); linkState.links++; linkState.lastClose = lastClose; linkState.journal = journal.size; linkState.up = true;
2095
2197
  why = 'network'; prevCid = null; lastClose = null; console.log(`Connected as "${conf.device_name}"${readonly ? ' (read-only)' : ''}${transport === 'poll' ? ' over the HTTPS fallback' : ''}. Leave this running.`); };
2096
2198
  ws.onmessage = async (ev) => {
2097
2199
  lastMsg = Date.now();
@@ -2310,6 +2412,22 @@ export async function doctor(opts = {}) {
2310
2412
  fetch(`${server}/agent/poll/close?sid=${sid}`, { method: 'POST', headers: H, signal: AbortSignal.timeout(5000) }).catch(() => {});
2311
2413
  add(got, `HTTPS fallback: ${got ? 'works' : 'no answer'} (${Date.now() - s} ms)`, 'Even plain HTTPS requests to Shellway are held. A firewall or proxy blocks mcp.getshellway.com.');
2312
2414
  } catch (e) { add(null, `HTTPS fallback: ${err(e)}`); }
2415
+ // 0.8.11 (Konstantin KO18): the browser extension link, tested the way the extension's helper connects
2416
+ try {
2417
+ let info = null; try { info = JSON.parse(readFileSync(EXT_BRIDGE, 'utf8')); } catch {}
2418
+ if (!info || !info.port) add(null, 'Browser extension link: not set up on this computer (only needed for the browser tools)');
2419
+ else {
2420
+ const r = await new Promise((resolve) => {
2421
+ const sk = netConnect(info.port, '127.0.0.1'); let b = '', done = false; const end = (x) => { if (done) return; done = true; try { sk.destroy(); } catch {} resolve(x); };
2422
+ const t = setTimeout(() => end({ err: 'no answer in 4 s' }), 4000);
2423
+ sk.on('connect', () => sk.write(JSON.stringify({ token: info.token, origin: 'doctor' }) + '\n'));
2424
+ sk.on('data', (d) => { b += d.toString('utf8'); const i = b.indexOf('\n'); if (i >= 0) { clearTimeout(t); let m = {}; try { m = JSON.parse(b.slice(0, i)); } catch {} end(m.type === 'hello' ? { hello: m } : { err: m.message || 'unexpected answer' }); } });
2425
+ sk.on('error', (e) => { clearTimeout(t); end({ err: e.code === 'ECONNREFUSED' ? `nothing listens on port ${info.port} (the app that wrote the link file is not running; pid ${info.pid})` : e.message }); });
2426
+ });
2427
+ if (r.hello) add(true, `Browser extension link: the Shellway app ${r.hello.version} (pid ${r.hello.pid}) answers${r.hello.browsers && r.hello.browsers.length ? '; connected browsers: ' + r.hello.browsers.join(', ') : '; no browser connected right now'}`);
2428
+ else add(false, `Browser extension link: ${r.err}`, 'The browser extension cannot reach the Shellway app. Run the service install command again (it restarts the app and rewrites the link), then close the browser completely and open it again.');
2429
+ }
2430
+ } catch (e) { add(null, `Browser extension link: ${err(e)}`); }
2313
2431
  // the background app's log
2314
2432
  try {
2315
2433
  const log = join(CONF_DIR, 'agent.log');