webhelm 1.0.57 → 1.0.59

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "webhelm",
3
- "version": "1.0.57",
3
+ "version": "1.0.59",
4
4
  "description": "Agent browser automation in a visible managed Chrome with persistent JavaScript sessions",
5
5
  "type": "module",
6
6
  "bin": {
@@ -110,7 +110,7 @@ function chromeMajor(chromePath){
110
110
  return chromeMajorFromVersion(execFileSync(chromePath,['--version'],{encoding:'utf8',timeout:5000}).trim());
111
111
  }
112
112
  export function chromeLaunchArgs(profile,port,extensionPath,major){
113
- const args=[`--user-data-dir=${profile}`,`--remote-debugging-port=${port}`];
113
+ const args=[`--user-data-dir=${profile}`,`--remote-debugging-port=${port}`,'--enable-features=WebMCP'];
114
114
  // Chrome 138 can load unpacked extensions with a compatibility flag.
115
115
  // Chrome 139+ must rely on Extensions.loadUnpacked through CDP instead:
116
116
  // passing --load-extension can leave a stale, non-running extension entry.
@@ -17,6 +17,9 @@ Commands:
17
17
  webhelm capacity Report available browser capacity (JSON)
18
18
  webhelm session start [--url URL] Start a persistent browser Session
19
19
  webhelm session list List CLI-owned Sessions
20
+ webhelm chatgpt identify MARKER Resolve calling ChatGPT conversation (experimental)
21
+ webhelm session tools ID Discover native WebMCP tools (JSON)
22
+ webhelm session snapshot ID Capture current page snapshot (JSON)
20
23
  webhelm session exec ID [--code-file F] Run JavaScript in a Session
21
24
  webhelm session heartbeat ID Keep a Session alive during idle waits
22
25
  webhelm session stop ID|--all Stop a Session or explicitly stop all CLI Sessions
@@ -189,6 +192,8 @@ Usage:
189
192
  Subcommands:
190
193
  start [--url URL] Start a Session and receive a session_id
191
194
  list List active CLI-owned Sessions
195
+ tools ID [--discovery-ms MS] Discover current-page WebMCP tools
196
+ snapshot ID Capture current page and element references
192
197
  exec ID [--code-file FILE] Run JavaScript in a persistent Session
193
198
  heartbeat ID Refresh the idle timer for a Session
194
199
  stop ID Stop one Session and release its tab
@@ -228,6 +233,54 @@ Does not create a Session.
228
233
 
229
234
  Example:
230
235
  webhelm session list`,
236
+ chatgpt: `webhelm chatgpt — ChatGPT convenience commands
237
+
238
+ Usage:
239
+ webhelm chatgpt identify MARKER
240
+
241
+ Read-only caller identification using a unique tool-call marker.
242
+ Run webhelm chatgpt identify --help for details.`,
243
+ 'chatgpt identify': `webhelm chatgpt identify — identify a conversation from a tool-call marker
244
+
245
+ Usage:
246
+ webhelm chatgpt identify MARKER
247
+
248
+ MARKER must be a fresh unique 16–128 character token (letters, digits,
249
+ hyphens or underscores). Use the exact standalone command in a Neo shell
250
+ tool call. Opens an owned temporary Session, examines recent conversation
251
+ records for the exact structured call and releases the Session.
252
+ Returns only identity evidence (JSON). Inconclusive exits nonzero.
253
+ Experimental: current coverage is the first ten ordinary visible Recents
254
+ rows; no guarantee that an in-flight call has been persisted.`,
255
+ 'session snapshot': `webhelm session snapshot — inspect the current page
256
+
257
+ Usage:
258
+ webhelm session snapshot SESSION_ID
259
+
260
+ Runs the existing snapshot helper on the selected tab of a CLI-owned Session.
261
+ Returns JSON with session_id, target_id and snapshot text, including element
262
+ references. Refresh references after navigation or another snapshot. Does not
263
+ navigate or click.
264
+
265
+ Example:
266
+ webhelm session snapshot SESSION_ID | jq -r '.snapshot'`,
267
+ 'session tools': `webhelm session tools — discover native WebMCP tools
268
+
269
+ Usage:
270
+ webhelm session tools SESSION_ID [--discovery-ms MS]
271
+
272
+ Options:
273
+ --discovery-ms MS Discovery window (0–5000 ms; default 500)
274
+
275
+ Lists tools registered in the selected main frame of an existing CLI-owned
276
+ Session. Does not navigate or invoke tools. Output: JSON with session_id,
277
+ target_id and tools (names, descriptions, input schemas and annotations).
278
+ An empty tools array means no tools were discovered or Chrome does not
279
+ support WebMCP. Other unavailable discovery
280
+ exits nonzero.
281
+
282
+ Example:
283
+ webhelm session tools SESSION_ID --discovery-ms 2000`,
231
284
  'session exec': `webhelm session exec — run JavaScript in an existing Session
232
285
 
233
286
  Usage:
@@ -244,7 +297,7 @@ Options:
244
297
  -h, --help Show help without executing code
245
298
 
246
299
  The JavaScript context persists across exec calls. Browser helpers are async:
247
- snapshot, page_info, goto_url, wait_for_load, wait_for_element,
300
+ snapshot, page_info, goto_url, wait_for_response, wait_for_load, wait_for_element,
248
301
  fill_input, click, js, new_tab, current_tab, list_tabs,
249
302
  switch_tab, activate_tab, close_tab, upload_file, type_text, press_key,
250
303
  add_init_script, list_frames, js_in_frame, capture_screenshot, events, wait.
@@ -399,7 +452,7 @@ Example:
399
452
  export const helpTopics = Object.freeze(Object.keys(sections).filter(Boolean));
400
453
  export function cliHelp(topics=[]) {
401
454
  const parts = topics.filter(Boolean);
402
- const key = parts.length>1 && ['session','platform','design'].includes(parts[0])
455
+ const key = parts.length>1 && ['session','platform','design','chatgpt'].includes(parts[0])
403
456
  ? parts.slice(0,2).join(' ') : (parts[0] || '');
404
457
  if (!Object.hasOwn(sections,key)) throw Error(`unknown help topic: ${parts.join(' ')}`);
405
458
  return sections[key];
package/runtime/cli.mjs CHANGED
@@ -74,7 +74,7 @@ async function requireCliSession(sessionId) {
74
74
  async function main(args = process.argv.slice(2)) {
75
75
  const [group, command] = args;
76
76
  if (!group || ['--help', '-h', 'help'].includes(group) || has(args, '--help') || has(args, '-h') ||
77
- ((group === 'session' || group === 'platform' || group === 'design' || group === 'demo') && (!command || command === 'help'))) {
77
+ ((group === 'session' || group === 'platform' || group === 'design' || group === 'demo' || group === 'chatgpt') && (!command || command === 'help'))) {
78
78
  const topics = group === 'help'
79
79
  ? args.slice(1).filter(item => !['--help', '-h'].includes(item))
80
80
  : ['--help', '-h'].includes(group) ? [] : args.filter(item => !['--help', '-h', 'help'].includes(item));
@@ -151,6 +151,21 @@ async function main(args = process.argv.slice(2)) {
151
151
  }
152
152
  throw Error('unknown design command: '+String(command||''));
153
153
  }
154
+ if (group === 'chatgpt' && command === 'identify') {
155
+ const id=args[2];
156
+ if(args.length!==3||!/^[A-Za-z0-9_-]{16,128}$/.test(id||''))
157
+ throw Error('usage: webhelm chatgpt identify MARKER (unique 16–128 characters)');
158
+ await ensureActions();
159
+ actionPath('chatgpt','identify');
160
+ const response=await request({op:'platform-run',platform:'chatgpt',action:'identify',
161
+ config:{id},auto_session:true,url:'https://chatgpt.com/',workspace:CLI_WORKSPACE});
162
+ const result=response.result;
163
+ if(!result?.ok)throw Error(result?.error||'ChatGPT identification failed');
164
+ if(result.cleanup?.release_error)throw Error('ChatGPT identity session release failed');
165
+ emit(result.value);
166
+ if(result.value?.status!=='identified')process.exitCode=1;
167
+ return;
168
+ }
154
169
  if (group === 'session') {
155
170
  if (command === 'start') return emit(await request({op:'start', workspace:CLI_WORKSPACE, url:arg(args,'--url')}));
156
171
  if (command === 'list') {
@@ -167,6 +182,31 @@ async function main(args = process.argv.slice(2)) {
167
182
  await requireCliSession(args[2]);
168
183
  return emit(await request({op:'stop',session_id:args[2]}));
169
184
  }
185
+ if (command === 'snapshot') {
186
+ const sessionId=args[2];
187
+ if(!sessionId||sessionId.startsWith('--')||args.length!==3)
188
+ throw Error('usage: webhelm session snapshot SESSION_ID');
189
+ await requireCliSession(sessionId);
190
+ const result=await request({op:'exec',session_id:sessionId,code:'await helpers.snapshot()'});
191
+ if(!result.ok)throw Error(result.error||'Session snapshot failed');
192
+ if(typeof result.value!=='string')throw Error('Session snapshot unavailable');
193
+ return emit({session_id:sessionId,target_id:result.target_id,snapshot:result.value});
194
+ }
195
+ if (command === 'tools') {
196
+ const sessionId=args[2];
197
+ if(!sessionId||sessionId.startsWith('--')||args.length!==3&&
198
+ !(args.length===5&&args[3]==='--discovery-ms'))
199
+ throw Error('usage: webhelm session tools SESSION_ID [--discovery-ms MS]');
200
+ const discovery_ms=args.length===5&&/^\d+$/.test(args[4])?Number(args[4]):args.length===3?500:NaN;
201
+ if(!Number.isInteger(discovery_ms)||discovery_ms<0||discovery_ms>5000)
202
+ throw Error('--discovery-ms must be an integer from 0 to 5000');
203
+ await requireCliSession(sessionId);
204
+ const result=await request({op:'exec',session_id:sessionId,
205
+ code:'await helpers.webmcp.tools('+JSON.stringify({discovery_ms})+')'});
206
+ if(!result.ok)throw Error(result.error||'WebMCP discovery failed');
207
+ if(!Array.isArray(result.value))throw Error('WebMCP discovery unavailable in this Session');
208
+ return emit({session_id:sessionId,target_id:result.target_id,tools:result.value});
209
+ }
170
210
  if (command === 'exec') {
171
211
  await requireCliSession(args[2]);
172
212
  const file = arg(args, '--code-file');
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "WebHelm",
4
- "version": "1.0.57",
4
+ "version": "1.0.59",
5
5
  "description": "Own named Chrome tab-group workspaces and lazy reusable tab pools for browser agents.",
6
6
  "permissions": [
7
7
  "storage",
@@ -0,0 +1,108 @@
1
+ // One-shot, owned-target JSON response observer. No headers, credentials,
2
+ // raw CDP handles, or persistent response capture leave the Runtime.
3
+ const MAX_BYTES=8*1024*1024;
4
+ function webUrl(value){
5
+ const u=new URL(value);
6
+ if(u.username||u.password||u.hash||!(u.protocol==='https:'||
7
+ u.protocol==='http:'&&['localhost','127.0.0.1','[::1]'].includes(u.hostname)))
8
+ throw Error('wait_for_response requires HTTPS or loopback HTTP URLs');
9
+ return u;
10
+ }
11
+ export function responseOptions(options={}){
12
+ const {url,navigate,timeout_ms=15000,max_bytes=MAX_BYTES}=options;
13
+ const expected=webUrl(url),page=webUrl(navigate);
14
+ if(expected.origin!==page.origin)throw Error('response and navigation must share an origin');
15
+ if(!Number.isInteger(timeout_ms)||timeout_ms<1||timeout_ms>30000||
16
+ !Number.isInteger(max_bytes)||max_bytes<1||max_bytes>MAX_BYTES)
17
+ throw Error('invalid response timeout or size limit');
18
+ return {expected,page,timeout_ms,max_bytes};
19
+ }
20
+ export async function observeJsonResponse(browser,sessionId,options,isOwned){
21
+ const {expected,page,timeout_ms,max_bytes}=responseOptions(options);
22
+ const matches=value=>{
23
+ try{const u=new URL(value);return u.origin===expected.origin&&
24
+ u.pathname===expected.pathname&&(!expected.search||u.search===expected.search);}
25
+ catch{return false;}
26
+ };
27
+ const active=()=>isOwned()&&!browser.closed;
28
+ let settle,timer,done=false,reading=false;
29
+ const requests=new Map(),responses=new Map(),off=[];
30
+ let navigation=null;
31
+ const answer=new Promise(resolve=>{settle=resolve;});
32
+ const finish=result=>{
33
+ if(done)return;
34
+ done=true;clearTimeout(timer);
35
+ for(const unsubscribe of off)unsubscribe();
36
+ settle(result);
37
+ };
38
+ function on(method,callback){
39
+ off.push(browser.on(method,(p,owner)=>{
40
+ if(done||owner!==sessionId)return;
41
+ if(!active()){finish(null);return;}
42
+ callback(p);
43
+ }));
44
+ }
45
+ // Only requests started after arming the observer qualify. Redirects
46
+ // replace the prior request identity, so a nonmatching redirect is ignored.
47
+ on('Network.requestWillBeSent',p=>{
48
+ requests.delete(p.requestId);responses.delete(p.requestId);
49
+ if(p.request?.method==='GET'&&matches(p.request.url)&&requests.size+responses.size<32)
50
+ requests.set(p.requestId,{loaderId:p.loaderId,frameId:p.frameId});
51
+ });
52
+ on('Network.responseReceived',p=>{
53
+ if(!requests.has(p.requestId)||!matches(p.response?.url))return;
54
+ if(p.response.status!==200||!/^application\/(?:[\w.+-]*\+)?json(?:\s*;|$)/i.test(p.response.mimeType||'')){
55
+ requests.delete(p.requestId);return;
56
+ }
57
+ responses.set(p.requestId,{status:p.response.status,url:p.response.url,...requests.get(p.requestId)});
58
+ });
59
+ on('Network.loadingFailed',p=>{requests.delete(p.requestId);responses.delete(p.requestId);});
60
+ function consume(requestId,response){
61
+ if(done||reading||!navigation||!response.finished)return;
62
+ if(response.loaderId!==navigation.loaderId||response.frameId!==navigation.frameId)return;
63
+ if(response.encodedDataLength>max_bytes){finish(null);return;}
64
+ reading=true;
65
+ void (async()=>{
66
+ try{
67
+ const result=await browser.send('Network.getResponseBody',{requestId},sessionId);
68
+ if(done||!active()){finish(null);return;}
69
+ const bytes=Buffer.from(result.body||'',result.base64Encoded?'base64':'utf8');
70
+ if(bytes.length>max_bytes){finish(null);return;}
71
+ const json=JSON.parse(bytes.toString('utf8'));
72
+ finish({status:response.status,url:response.url,json});
73
+ }catch{finish(null);}
74
+ })();
75
+ }
76
+ on('Network.loadingFinished',p=>{
77
+ const response=responses.get(p.requestId);
78
+ requests.delete(p.requestId);
79
+ if(!response)return;
80
+ Object.assign(response,{finished:true,encodedDataLength:p.encodedDataLength});
81
+ if(navigation){
82
+ consume(p.requestId,response);
83
+ responses.delete(p.requestId);
84
+ }
85
+ });
86
+ timer=setTimeout(()=>finish(null),timeout_ms);
87
+ // Register all listeners before triggering navigation.
88
+ try{
89
+ if(!active())finish(null);
90
+ else {
91
+ // Hold the navigation effect until CDP acknowledges it; do not release
92
+ // a lease while a previously issued browser operation remains pending.
93
+ const nav=browser.send('Page.navigate',{url:page.href},sessionId).then(result=>{
94
+ if(done)return;
95
+ if(result.errorText||!result.loaderId||!result.frameId){finish(null);return;}
96
+ navigation=result;
97
+ for(const [id,response] of responses){
98
+ consume(id,response);
99
+ if(response.finished)responses.delete(id);
100
+ }
101
+ },()=>finish(null));
102
+ const result=await answer;
103
+ await nav;
104
+ return active()?result:null;
105
+ }
106
+ return await answer;
107
+ }finally{finish(null);}
108
+ }
@@ -8,6 +8,8 @@ import crypto from 'node:crypto';
8
8
  import { fileURLToPath, pathToFileURL } from 'node:url';
9
9
  import { invokePlatformAction } from './platforms.mjs';
10
10
  import { validateExtensionCommand, diagnosticEvent, loadUserHelpers } from './user-helpers.mjs';
11
+ import { observeJsonResponse, responseOptions } from './network-response.mjs';
12
+ import { createWebMCPNamespace, listWebMCPTools, webmcpListOptions, readWebMCPTool, webmcpReadOptions } from './webmcp.mjs';
11
13
  import {createSiteKeepaliveScheduler} from './site-keepalive.mjs';
12
14
  import { PlatformQueueRegistry } from './queue-registry.mjs';
13
15
  import { idleUrlFromIdentity, sameIdleUrl, staleSession, withinDeadline, SessionDeadlineError, endedDesignSessions } from './session-lifecycle.mjs';
@@ -213,6 +215,14 @@ function makeHelpers(s){
213
215
  const h={
214
216
  js:(expression,target_id)=>evaluate(s,expression,target_id||s.targetId),
215
217
  async goto_url(url,{wait=true}={}){await cdp(s,'Page.navigate',{url});if(wait)await h.wait_for_load();return h.page_info()},
218
+ async wait_for_response(options){
219
+ responseOptions(options);
220
+ const target=s.targetId;
221
+ const browser=await connectBrowser();
222
+ const owned=()=>!s.poisoned&&!s.closing&&s.targetId===target&&s.targets.has(target);
223
+ if(!owned())return null;
224
+ return observeJsonResponse(browser,sidFor(s,target),options,owned);
225
+ },
216
226
  async current_tab(){const info=await cdp(s,'Target.getTargetInfo',{targetId:s.targetId});return info.targetInfo},
217
227
  async new_tab(url='about:blank') {
218
228
  const browser=await connectBrowser();
@@ -355,19 +365,30 @@ function makeHelpers(s){
355
365
  // Revoke even helper references retained by unresolved async VM scripts.
356
366
  // A rejected async VM execution does not cancel browser operations it
357
367
  // already started. Keep their tab ownership until those operations settle.
358
- const effectHelpers=new Set(['js','goto_url','new_tab','close_tab','fill_input','press_key','add_init_script','list_frames','js_in_frame',
368
+ const effectHelpers=new Set(['js','goto_url','wait_for_response','new_tab','close_tab','fill_input','press_key','add_init_script','list_frames','js_in_frame',
359
369
  'click','capture_screenshot','snapshot','type_text','upload_file','switch_tab','activate_tab']);
370
+ const guardHelper=(helper,hasEffect)=>(...args)=>{
371
+ if(s.poisoned || s.closing)throw Error('Session execution expired or closing');
372
+ if(!hasEffect)return helper(...args);
373
+ s.pendingEffects++;
374
+ try{
375
+ return Promise.resolve(helper(...args)).finally(()=>{s.pendingEffects--;});
376
+ }catch(error){s.pendingEffects--;throw error;}
377
+ };
360
378
  for(const [name,helper] of Object.entries(h)){
361
- if(typeof helper!=='function')continue;
362
- h[name]=(...args)=>{
363
- if(s.poisoned || s.closing)throw Error('Session execution expired or closing');
364
- if(!effectHelpers.has(name))return helper(...args);
365
- s.pendingEffects++;
366
- try{
367
- return Promise.resolve(helper(...args)).finally(()=>{s.pendingEffects--;});
368
- }catch(error){s.pendingEffects--;throw error;}
369
- };
379
+ if(typeof helper==='function')h[name]=guardHelper(helper,effectHelpers.has(name));
370
380
  }
381
+ const webmcpOperation=async(operation,options)=>{
382
+ const target=s.targetId;
383
+ const browser=await connectBrowser();
384
+ const owned=()=>!s.poisoned&&!s.closing&&s.targetId===target&&s.targets.has(target);
385
+ if(!owned())return null;
386
+ return operation(browser,sidFor(s,target),options,owned);
387
+ };
388
+ h.webmcp=createWebMCPNamespace({
389
+ list:guardHelper((options)=>webmcpOperation(listWebMCPTools,webmcpListOptions(options)),true),
390
+ read:guardHelper((name,input,options)=>webmcpOperation(readWebMCPTool,webmcpReadOptions(name,input,options)),true),
391
+ });
371
392
  Object.defineProperty(h,'target_id',{get:()=>s.targetId});
372
393
  Object.defineProperty(h,'targetId',{get:()=>s.targetId});
373
394
  return h;
@@ -0,0 +1,146 @@
1
+ // One-shot WebMCP discovery and read on the owned main frame. Keep CDP private to Runtime.
2
+ // Tool output is untrusted data; consumers must validate their own schemas.
3
+ const locks = new WeakMap();
4
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
5
+ const MAX_OUTPUT = 1024 * 1024;
6
+
7
+ // Reserve the control namespace and JS protocol names. No site can
8
+ // override discovery or turn the namespace into a thenable.
9
+ const reservedNames=new Set(['tools','then','constructor','prototype','toString','toJSON','valueOf','inspect','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString']);
10
+ const isCallableToolName=name=>typeof name==='string'&&name.length>0&&name.length<=200&&
11
+ !name.startsWith('__')&&!reservedNames.has(name);
12
+
13
+ export function createWebMCPNamespace({list,read}){
14
+ const controls=Object.create(null);
15
+ Object.defineProperty(controls,'tools',{value:(options={})=>list(options),enumerable:true});
16
+ Object.freeze(controls);
17
+ return new Proxy(controls,{
18
+ get(target,name,receiver){
19
+ if(Reflect.has(target,name))return Reflect.get(target,name,receiver);
20
+ if(!isCallableToolName(name))return undefined;
21
+ return (input={},options={})=>read(name,input,options);
22
+ }
23
+ });
24
+ }
25
+
26
+ export function webmcpReadOptions(name, input = {}, options = {}) {
27
+ const { discovery_ms = 500, timeout_ms = 3000 } = options;
28
+ if (typeof name !== 'string' || !name.trim() || name.length > 200 ||
29
+ !input || typeof input !== 'object' || Array.isArray(input) ||
30
+ !Number.isInteger(discovery_ms) || discovery_ms < 0 || discovery_ms > 5000 ||
31
+ !Number.isInteger(timeout_ms) || timeout_ms < 1 || timeout_ms > 30000)
32
+ throw Error('invalid WebMCP read options');
33
+ return { name, input, discovery_ms, timeout_ms };
34
+ }
35
+
36
+ export function webmcpListOptions(options = {}) {
37
+ const { discovery_ms = 500 } = options;
38
+ if (!Number.isInteger(discovery_ms) || discovery_ms < 0 || discovery_ms > 5000)
39
+ throw Error('invalid WebMCP discovery options');
40
+ return { discovery_ms };
41
+ }
42
+
43
+ export function listWebMCPTools(browser, sessionId, options, isOwned) {
44
+ return withWebMCP(browser, sessionId, webmcpListOptions(options), isOwned);
45
+ }
46
+
47
+ export function readWebMCPTool(browser, sessionId, options, isOwned) {
48
+ return withWebMCP(browser, sessionId,
49
+ webmcpReadOptions(options.name,options.input,options), isOwned);
50
+ }
51
+
52
+ async function withWebMCP(browser, sessionId, {name,input,discovery_ms,timeout_ms}, isOwned) {
53
+ // WebMCP.enable/disable is scoped to an attachment. Serialize operations
54
+ // on that attachment, never unrelated tabs or Sessions.
55
+ let bySession=locks.get(browser);
56
+ if(!bySession){bySession=new Map();locks.set(browser,bySession);}
57
+ const previous=bySession.get(sessionId)||Promise.resolve();
58
+ let release;
59
+ const gate=new Promise(resolve=>{release=resolve;});
60
+ const tail=previous.then(()=>gate);
61
+ bySession.set(sessionId,tail);
62
+ await previous;
63
+ try{return await read();}
64
+ finally{release();if(bySession.get(sessionId)===tail)bySession.delete(sessionId);}
65
+
66
+ async function read(){
67
+ const active=()=>isOwned()&&!browser.closed;
68
+ if(!active())return null;
69
+ const off=[],tools=new Map(),responses=new Map();
70
+ let enabled=false, invalidated=false, invocationId, settled=false, notify=()=>{};
71
+ const on=(method,fn)=>off.push(browser.on(method,(p,owner)=>{
72
+ if(owner===sessionId&&active()&&!invalidated)fn(p);
73
+ }));
74
+ try{
75
+ const {frameTree}=await browser.send('Page.getFrameTree',{},sessionId);
76
+ const frameId=frameTree?.frame?.id;
77
+ if(!frameId||!active())return null;
78
+ on('Page.frameNavigated',p=>{if(p.frame?.id===frameId){invalidated=true;notify();}});
79
+ on('Page.navigatedWithinDocument',p=>{if(p.frameId===frameId){invalidated=true;notify();}});
80
+ on('WebMCP.toolsAdded',p=>{
81
+ for(const t of p.tools||[])if(t.frameId===frameId)tools.set(t.name,t);
82
+ notify();
83
+ });
84
+ on('WebMCP.toolsRemoved',p=>{
85
+ for(const t of p.tools||[])if(t.frameId===frameId)tools.delete(t.name);
86
+ notify();
87
+ });
88
+ on('WebMCP.toolResponded',p=>{
89
+ if(typeof p.invocationId==='string'&&responses.size<64)responses.set(p.invocationId,p);
90
+ notify();
91
+ });
92
+ // Subscribe before enabling: Chrome sends existing registrations as events.
93
+ enabled=true;
94
+ try {
95
+ await browser.send('WebMCP.enable',{},sessionId);
96
+ } catch(error) {
97
+ // Older Chrome reports an absent CDP domain as method not found.
98
+ // Do not disguise transport failures or revoked ownership as no tools.
99
+ const unsupported=/unknown (?:domain|method|command)|(?:method|command).*not found|(?:WebMCP\.enable).*wasn't found|not supported/i.test(error?.message||'');
100
+ if(unsupported){
101
+ enabled=false;
102
+ return name===undefined&&active()&&!invalidated?[]:null;
103
+ }
104
+ throw error;
105
+ }
106
+ async function waitUntil(condition,ms){
107
+ const end=Date.now()+ms;
108
+ while(active()&&!invalidated&&!condition()&&Date.now()<end){
109
+ await Promise.race([new Promise(resolve=>{notify=resolve;}),sleep(Math.min(50,Math.max(0,end-Date.now())))]);
110
+ notify=()=>{};
111
+ }
112
+ }
113
+ // Listing collects registrations throughout the discovery window.
114
+ // Reading can stop early when its exact tool is registered.
115
+ await waitUntil(()=>name!==undefined&&tools.has(name),discovery_ms);
116
+ if(!active()||invalidated)return null;
117
+ if(name===undefined){
118
+ const definitions=[...tools.values()].map(({name,description,inputSchema,annotations})=>({
119
+ name,description,inputSchema,annotations
120
+ }));
121
+ const serialized=JSON.stringify(definitions);
122
+ if(Buffer.byteLength(serialized)>MAX_OUTPUT)return null;
123
+ return JSON.parse(serialized);
124
+ }
125
+ // A readOnly annotation is a provider hint, not a security guarantee.
126
+ // Only a specifically requested, registered read tool may be invoked.
127
+ if(!active()||invalidated||tools.get(name)?.annotations?.readOnly!==true)return null;
128
+ ({invocationId}=await browser.send('WebMCP.invokeTool',{frameId,toolName:name,input},sessionId));
129
+ if(typeof invocationId!=='string')return null;
130
+ await waitUntil(()=>responses.has(invocationId),timeout_ms);
131
+ const response=responses.get(invocationId);
132
+ settled=!!response;
133
+ if(!active()||invalidated||response?.status!=='Completed'||!Object.hasOwn(response,'output'))return null;
134
+ const serialized=JSON.stringify(response.output);
135
+ if(serialized===undefined||Buffer.byteLength(serialized)>MAX_OUTPUT)return null;
136
+ return JSON.parse(serialized);
137
+ }catch{return null;}
138
+ finally{
139
+ for(const dispose of off)dispose();
140
+ // Retain the lease until cancellation/disable have settled.
141
+ if(invocationId&&!settled&&!browser.closed)
142
+ await browser.send('WebMCP.cancelInvocation',{invocationId},sessionId).catch(()=>{});
143
+ if(enabled&&!browser.closed)await browser.send('WebMCP.disable',{},sessionId).catch(()=>{});
144
+ }
145
+ }
146
+ }