browser-devtools-mcp 0.2.6 → 0.2.7

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.
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{a as me}from"../core-4DMVQUQB.js";import{A as se,B as re,C as ie,D as ae,E as le,F as B,G as ce,H as de,a as u,p as Y,q as z,r as Q,u as X,v as ee,x as oe,y as ne,z as te}from"../core-IV5QBQ2N.js";import{Command as pe,Option as E}from"commander";import{ZodFirstPartyTypeKind as _}from"zod";function ve(o){let i=o,l=!1,m;for(;;){let b=i._def.typeName;if(b===_.ZodOptional)l=!0,i=i._def.innerType;else if(b===_.ZodDefault)l=!0,m=i._def.defaultValue(),i=i._def.innerType;else if(b===_.ZodNullable)l=!0,i=i._def.innerType;else break}return{innerType:i,isOptional:l,defaultValue:m}}u(ve,"_unwrapZodType");function we(o){return o._def.description}u(we,"_getDescription");function Oe(o){return o.replace(/[-_]([a-z])/g,(i,l)=>l.toUpperCase())}u(Oe,"_toCamelCase");function Te(o){return o.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}u(Te,"_toKebabCase");function _e(o,i){let{innerType:l,isOptional:m,defaultValue:b}=ve(i),p=we(i)||`The ${o} value`,O=Te(o),R=l._def.typeName,y;switch(R){case _.ZodString:y=new E(`--${O} <string>`,p);break;case _.ZodNumber:y=new E(`--${O} <number>`,p),y.argParser(c=>{let d=Number(c);if(!Number.isFinite(d))throw new Error(`Invalid number: ${c}`);return d});break;case _.ZodBoolean:y=new E(`--${O}`,p);break;case _.ZodEnum:let P=l._def.values;y=new E(`--${O} <choice>`,p).choices(P);break;case _.ZodArray:y=new E(`--${O} <value...>`,p);break;case _.ZodObject:case _.ZodRecord:y=new E(`--${O} <json>`,p),y.argParser(c=>{try{return JSON.parse(c)}catch{throw new Error(`Invalid JSON: ${c}`)}});break;case _.ZodAny:case _.ZodUnknown:y=new E(`--${O} <value>`,p),y.argParser(c=>{try{return JSON.parse(c)}catch{return c}});break;case _.ZodLiteral:let n=l._def.value;typeof n=="boolean"?y=new E(`--${O}`,p):(y=new E(`--${O} <value>`,p),y.default(n));break;case _.ZodUnion:let s=l._def.options;if(s.every(c=>c._def.typeName===_.ZodLiteral)){let c=s.map(d=>String(d._def.value));y=new E(`--${O} <choice>`,p).choices(c)}else y=new E(`--${O} <value>`,p),y.argParser(c=>{try{return JSON.parse(c)}catch{return c}});break;default:y=new E(`--${O} <value>`,p);break}return b!==void 0&&y.default(b),!m&&b===void 0&&y.makeOptionMandatory(!0),y}u(_e,"_createOption");function Se(o){let i=[];for(let[l,m]of Object.entries(o)){let b=_e(l,m);b&&i.push(b)}return i}u(Se,"_generateOptionsFromSchema");function Ce(o){let i={};for(let[l,m]of Object.entries(o)){let b=Oe(l);m!==void 0&&(i[b]=m)}return i}u(Ce,"_parseOptionsToToolInput");function Ee(o){let i=o.indexOf("_");return i===-1?{domain:"default",commandName:o}:{domain:o.substring(0,i),commandName:o.substring(i+1)}}u(Ee,"_parseToolName");function W(o,i,l){let m=new Map;for(let b of i){let{domain:p,commandName:O}=Ee(b.name()),R=m.get(p);R||(R=new pe(p).description(`${p.charAt(0).toUpperCase()+p.slice(1)} commands`),m.set(p,R),o.addCommand(R));let y=new pe(O).description(b.description().trim()),P=Se(b.inputSchema());for(let n of P)y.addOption(n);y.action(async n=>{let s=Ce(n),r=o.opts();await l(b.name(),s,r)}),R.addCommand(y)}}u(W,"registerToolCommands");import{spawn as De,execSync as Re}from"node:child_process";import{createRequire as Ae}from"node:module";import*as q from"node:path";import*as K from"node:readline";import{fileURLToPath as Ne}from"node:url";import{Command as D,Option as x}from"commander";var F=Ae(import.meta.url),Pe=Ne(import.meta.url),Ie=q.dirname(Pe),h=me.cliInfo.cliProvider,N=h.tools,S=3e4,ge=!1,be=!1;function w(o,i){if(ge){let l=new Date().toISOString();i!==void 0?console.error(`[${l}] [DEBUG] ${o}`,i):console.error(`[${l}] [DEBUG] ${o}`)}}u(w,"_debug");function e(o){be||console.log(o)}u(e,"_output");function f(o){console.error(o)}u(f,"_error");async function C(o){w(`Checking if daemon is running on port ${o}`);try{let i=await fetch(`http://localhost:${o}/health`,{method:"GET",signal:AbortSignal.timeout(3e3)});if(i.ok){let m=(await i.json()).status==="ok";return w(`Daemon health check result: ${m?"running":"not running"}`),m}return w(`Daemon health check failed: HTTP ${i.status}`),!1}catch(i){return w(`Daemon health check error: ${i.message}`),!1}}u(C,"_isDaemonRunning");function ke(o){return h.buildEnv(o)}u(ke,"_buildDaemonEnv");function G(o){let i=q.join(Ie,"..","daemon-server.js"),l=ke(o);w(`Starting daemon server from: ${i}`),w(`Daemon port: ${o.port}`);let m=De(process.execPath,[i,"--port",String(o.port)],{detached:!0,stdio:"ignore",env:l});m.unref(),w(`Daemon process spawned with PID: ${m.pid}`),e(`Started daemon server as detached process (PID: ${m.pid})`)}u(G,"_startDaemonDetached");async function k(o){if(await C(o.port))w("Daemon is already running");else{e(`Daemon server is not running on port ${o.port}, starting...`),G(o);let l=10,m=500;w(`Waiting for daemon to be ready (max ${l} retries, ${m}ms delay)`);for(let b=0;b<l;b++)if(await new Promise(p=>setTimeout(p,m)),w(`Retry ${b+1}/${l}: checking daemon status...`),await C(o.port)){w("Daemon is now ready"),e("Daemon server is ready");return}throw new Error(`Daemon server failed to start within ${l*m/1e3} seconds`)}}u(k,"_ensureDaemonRunning");async function U(o,i){try{return(await fetch(`http://localhost:${o}/shutdown`,{method:"POST",signal:AbortSignal.timeout(i)})).ok}catch{return!1}}u(U,"_stopDaemon");async function ue(o,i,l,m,b){let p={"Content-Type":"application/json"};m&&(p["session-id"]=m);let O={toolName:i,toolInput:l};w(`Calling tool: ${i}`),w("Tool input:",l),w(`Session ID: ${m||"(default)"}`),w(`Timeout: ${b||"none"}`);let R=Date.now(),y=await fetch(`http://localhost:${o}/call`,{method:"POST",headers:p,body:JSON.stringify(O),signal:b?AbortSignal.timeout(b):void 0}),P=Date.now()-R;if(w(`Tool call completed in ${P}ms, status: ${y.status}`),!y.ok){let s=await y.json().catch(()=>({}));throw w("Tool call error:",s),new Error(s?.error?.message||`HTTP ${y.status}: ${y.statusText}`)}let n=await y.json();return w("Tool call result:",n.toolError?{error:n.toolError}:{success:!0}),n}u(ue,"_callTool");async function je(o,i,l){try{return(await fetch(`http://localhost:${o}/session`,{method:"DELETE",headers:{"session-id":i},signal:AbortSignal.timeout(l)})).ok}catch{return!1}}u(je,"_deleteSession");async function J(o,i){try{let l=await fetch(`http://localhost:${o}/info`,{method:"GET",signal:AbortSignal.timeout(i)});return l.ok?await l.json():null}catch{return null}}u(J,"_getDaemonInfo");async function fe(o,i){try{let l=await fetch(`http://localhost:${o}/sessions`,{method:"GET",signal:AbortSignal.timeout(i)});return l.ok?await l.json():null}catch{return null}}u(fe,"_listSessions");async function xe(o,i,l){try{let m=await fetch(`http://localhost:${o}/session`,{method:"GET",headers:{"session-id":i},signal:AbortSignal.timeout(l)});return m.ok?await m.json():null}catch{return null}}u(xe,"_getSessionInfo");function j(o){let i=Math.floor(o/86400),l=Math.floor(o%86400/3600),m=Math.floor(o%3600/60),b=o%60,p=[];return i>0&&p.push(`${i}d`),l>0&&p.push(`${l}h`),m>0&&p.push(`${m}m`),p.push(`${b}s`),p.join(" ")}u(j,"_formatUptime");function V(o){return new Date(o).toISOString()}u(V,"_formatTimestamp");function Z(o){let i=o._def.typeName;return i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault"?Z(o._def.innerType):i==="ZodArray"?`${Z(o._def.type)}[]`:i==="ZodEnum"?o._def.values.join(" | "):i==="ZodLiteral"?JSON.stringify(o._def.value):i==="ZodUnion"?o._def.options.map(m=>Z(m)).join(" | "):{ZodString:"string",ZodNumber:"number",ZodBoolean:"boolean",ZodObject:"object",ZodRecord:"Record<string, any>",ZodAny:"any"}[i]||i.replace("Zod","").toLowerCase()}u(Z,"_getZodTypeName");function H(o){if(o._def.description)return o._def.description;if(o._def.typeName==="ZodOptional"||o._def.typeName==="ZodNullable"||o._def.typeName==="ZodDefault")return H(o._def.innerType)}u(H,"_getZodDescription");function Ze(o){let i=o._def.typeName;return i==="ZodOptional"||i==="ZodNullable"}u(Ze,"_isZodOptional");function ye(o){return o._def.typeName==="ZodDefault"?!0:o._def.typeName==="ZodOptional"||o._def.typeName==="ZodNullable"?ye(o._def.innerType):!1}u(ye,"_hasZodDefault");function $e(o){if(o._def.typeName==="ZodDefault")return o._def.defaultValue();if(o._def.typeName==="ZodOptional"||o._def.typeName==="ZodNullable")return $e(o._def.innerType)}u($e,"_getZodDefault");function L(o,i=0){let l=" ".repeat(i);if(o==null)return`${l}(empty)`;if(typeof o=="string")return o.split(`
2
+ import{a as me}from"../core-ROCTQ3TM.js";import{A as se,B as re,C as ie,D as ae,E as le,F as B,G as ce,H as de,a as u,p as Y,q as z,r as Q,u as X,v as ee,x as oe,y as ne,z as te}from"../core-IV5QBQ2N.js";import{Command as pe,Option as E}from"commander";import{ZodFirstPartyTypeKind as _}from"zod";function ve(o){let i=o,l=!1,m;for(;;){let b=i._def.typeName;if(b===_.ZodOptional)l=!0,i=i._def.innerType;else if(b===_.ZodDefault)l=!0,m=i._def.defaultValue(),i=i._def.innerType;else if(b===_.ZodNullable)l=!0,i=i._def.innerType;else break}return{innerType:i,isOptional:l,defaultValue:m}}u(ve,"_unwrapZodType");function we(o){return o._def.description}u(we,"_getDescription");function Oe(o){return o.replace(/[-_]([a-z])/g,(i,l)=>l.toUpperCase())}u(Oe,"_toCamelCase");function Te(o){return o.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}u(Te,"_toKebabCase");function _e(o,i){let{innerType:l,isOptional:m,defaultValue:b}=ve(i),p=we(i)||`The ${o} value`,O=Te(o),R=l._def.typeName,y;switch(R){case _.ZodString:y=new E(`--${O} <string>`,p);break;case _.ZodNumber:y=new E(`--${O} <number>`,p),y.argParser(c=>{let d=Number(c);if(!Number.isFinite(d))throw new Error(`Invalid number: ${c}`);return d});break;case _.ZodBoolean:y=new E(`--${O}`,p);break;case _.ZodEnum:let P=l._def.values;y=new E(`--${O} <choice>`,p).choices(P);break;case _.ZodArray:y=new E(`--${O} <value...>`,p);break;case _.ZodObject:case _.ZodRecord:y=new E(`--${O} <json>`,p),y.argParser(c=>{try{return JSON.parse(c)}catch{throw new Error(`Invalid JSON: ${c}`)}});break;case _.ZodAny:case _.ZodUnknown:y=new E(`--${O} <value>`,p),y.argParser(c=>{try{return JSON.parse(c)}catch{return c}});break;case _.ZodLiteral:let n=l._def.value;typeof n=="boolean"?y=new E(`--${O}`,p):(y=new E(`--${O} <value>`,p),y.default(n));break;case _.ZodUnion:let s=l._def.options;if(s.every(c=>c._def.typeName===_.ZodLiteral)){let c=s.map(d=>String(d._def.value));y=new E(`--${O} <choice>`,p).choices(c)}else y=new E(`--${O} <value>`,p),y.argParser(c=>{try{return JSON.parse(c)}catch{return c}});break;default:y=new E(`--${O} <value>`,p);break}return b!==void 0&&y.default(b),!m&&b===void 0&&y.makeOptionMandatory(!0),y}u(_e,"_createOption");function Se(o){let i=[];for(let[l,m]of Object.entries(o)){let b=_e(l,m);b&&i.push(b)}return i}u(Se,"_generateOptionsFromSchema");function Ce(o){let i={};for(let[l,m]of Object.entries(o)){let b=Oe(l);m!==void 0&&(i[b]=m)}return i}u(Ce,"_parseOptionsToToolInput");function Ee(o){let i=o.indexOf("_");return i===-1?{domain:"default",commandName:o}:{domain:o.substring(0,i),commandName:o.substring(i+1)}}u(Ee,"_parseToolName");function W(o,i,l){let m=new Map;for(let b of i){let{domain:p,commandName:O}=Ee(b.name()),R=m.get(p);R||(R=new pe(p).description(`${p.charAt(0).toUpperCase()+p.slice(1)} commands`),m.set(p,R),o.addCommand(R));let y=new pe(O).description(b.description().trim()),P=Se(b.inputSchema());for(let n of P)y.addOption(n);y.action(async n=>{let s=Ce(n),r=o.opts();await l(b.name(),s,r)}),R.addCommand(y)}}u(W,"registerToolCommands");import{spawn as De,execSync as Re}from"node:child_process";import{createRequire as Ae}from"node:module";import*as q from"node:path";import*as K from"node:readline";import{fileURLToPath as Ne}from"node:url";import{Command as D,Option as x}from"commander";var F=Ae(import.meta.url),Pe=Ne(import.meta.url),Ie=q.dirname(Pe),h=me.cliInfo.cliProvider,N=h.tools,S=3e4,ge=!1,be=!1;function w(o,i){if(ge){let l=new Date().toISOString();i!==void 0?console.error(`[${l}] [DEBUG] ${o}`,i):console.error(`[${l}] [DEBUG] ${o}`)}}u(w,"_debug");function e(o){be||console.log(o)}u(e,"_output");function f(o){console.error(o)}u(f,"_error");async function C(o){w(`Checking if daemon is running on port ${o}`);try{let i=await fetch(`http://localhost:${o}/health`,{method:"GET",signal:AbortSignal.timeout(3e3)});if(i.ok){let m=(await i.json()).status==="ok";return w(`Daemon health check result: ${m?"running":"not running"}`),m}return w(`Daemon health check failed: HTTP ${i.status}`),!1}catch(i){return w(`Daemon health check error: ${i.message}`),!1}}u(C,"_isDaemonRunning");function ke(o){return h.buildEnv(o)}u(ke,"_buildDaemonEnv");function G(o){let i=q.join(Ie,"..","daemon-server.js"),l=ke(o);w(`Starting daemon server from: ${i}`),w(`Daemon port: ${o.port}`);let m=De(process.execPath,[i,"--port",String(o.port)],{detached:!0,stdio:"ignore",env:l});m.unref(),w(`Daemon process spawned with PID: ${m.pid}`),e(`Started daemon server as detached process (PID: ${m.pid})`)}u(G,"_startDaemonDetached");async function k(o){if(await C(o.port))w("Daemon is already running");else{e(`Daemon server is not running on port ${o.port}, starting...`),G(o);let l=10,m=500;w(`Waiting for daemon to be ready (max ${l} retries, ${m}ms delay)`);for(let b=0;b<l;b++)if(await new Promise(p=>setTimeout(p,m)),w(`Retry ${b+1}/${l}: checking daemon status...`),await C(o.port)){w("Daemon is now ready"),e("Daemon server is ready");return}throw new Error(`Daemon server failed to start within ${l*m/1e3} seconds`)}}u(k,"_ensureDaemonRunning");async function U(o,i){try{return(await fetch(`http://localhost:${o}/shutdown`,{method:"POST",signal:AbortSignal.timeout(i)})).ok}catch{return!1}}u(U,"_stopDaemon");async function ue(o,i,l,m,b){let p={"Content-Type":"application/json"};m&&(p["session-id"]=m);let O={toolName:i,toolInput:l};w(`Calling tool: ${i}`),w("Tool input:",l),w(`Session ID: ${m||"(default)"}`),w(`Timeout: ${b||"none"}`);let R=Date.now(),y=await fetch(`http://localhost:${o}/call`,{method:"POST",headers:p,body:JSON.stringify(O),signal:b?AbortSignal.timeout(b):void 0}),P=Date.now()-R;if(w(`Tool call completed in ${P}ms, status: ${y.status}`),!y.ok){let s=await y.json().catch(()=>({}));throw w("Tool call error:",s),new Error(s?.error?.message||`HTTP ${y.status}: ${y.statusText}`)}let n=await y.json();return w("Tool call result:",n.toolError?{error:n.toolError}:{success:!0}),n}u(ue,"_callTool");async function je(o,i,l){try{return(await fetch(`http://localhost:${o}/session`,{method:"DELETE",headers:{"session-id":i},signal:AbortSignal.timeout(l)})).ok}catch{return!1}}u(je,"_deleteSession");async function J(o,i){try{let l=await fetch(`http://localhost:${o}/info`,{method:"GET",signal:AbortSignal.timeout(i)});return l.ok?await l.json():null}catch{return null}}u(J,"_getDaemonInfo");async function fe(o,i){try{let l=await fetch(`http://localhost:${o}/sessions`,{method:"GET",signal:AbortSignal.timeout(i)});return l.ok?await l.json():null}catch{return null}}u(fe,"_listSessions");async function xe(o,i,l){try{let m=await fetch(`http://localhost:${o}/session`,{method:"GET",headers:{"session-id":i},signal:AbortSignal.timeout(l)});return m.ok?await m.json():null}catch{return null}}u(xe,"_getSessionInfo");function j(o){let i=Math.floor(o/86400),l=Math.floor(o%86400/3600),m=Math.floor(o%3600/60),b=o%60,p=[];return i>0&&p.push(`${i}d`),l>0&&p.push(`${l}h`),m>0&&p.push(`${m}m`),p.push(`${b}s`),p.join(" ")}u(j,"_formatUptime");function V(o){return new Date(o).toISOString()}u(V,"_formatTimestamp");function Z(o){let i=o._def.typeName;return i==="ZodOptional"||i==="ZodNullable"||i==="ZodDefault"?Z(o._def.innerType):i==="ZodArray"?`${Z(o._def.type)}[]`:i==="ZodEnum"?o._def.values.join(" | "):i==="ZodLiteral"?JSON.stringify(o._def.value):i==="ZodUnion"?o._def.options.map(m=>Z(m)).join(" | "):{ZodString:"string",ZodNumber:"number",ZodBoolean:"boolean",ZodObject:"object",ZodRecord:"Record<string, any>",ZodAny:"any"}[i]||i.replace("Zod","").toLowerCase()}u(Z,"_getZodTypeName");function H(o){if(o._def.description)return o._def.description;if(o._def.typeName==="ZodOptional"||o._def.typeName==="ZodNullable"||o._def.typeName==="ZodDefault")return H(o._def.innerType)}u(H,"_getZodDescription");function Ze(o){let i=o._def.typeName;return i==="ZodOptional"||i==="ZodNullable"}u(Ze,"_isZodOptional");function ye(o){return o._def.typeName==="ZodDefault"?!0:o._def.typeName==="ZodOptional"||o._def.typeName==="ZodNullable"?ye(o._def.innerType):!1}u(ye,"_hasZodDefault");function $e(o){if(o._def.typeName==="ZodDefault")return o._def.defaultValue();if(o._def.typeName==="ZodOptional"||o._def.typeName==="ZodNullable")return $e(o._def.innerType)}u($e,"_getZodDefault");function L(o,i=0){let l=" ".repeat(i);if(o==null)return`${l}(empty)`;if(typeof o=="string")return o.split(`
3
3
  `).map(m=>`${l}${m}`).join(`
4
4
  `);if(typeof o=="number"||typeof o=="boolean")return`${l}${o}`;if(Array.isArray(o))return o.length===0?`${l}[]`:o.map(m=>L(m,i)).join(`
5
5
  `);if(typeof o=="object"){let m=[];for(let[b,p]of Object.entries(o))p!==void 0&&(typeof p=="object"&&p!==null&&!Array.isArray(p)?(m.push(`${l}${b}:`),m.push(L(p,i+1))):Array.isArray(p)?(m.push(`${l}${b}:`),m.push(L(p,i+1))):m.push(`${l}${b}: ${p}`));return m.join(`
@@ -1,4 +1,4 @@
1
- import{$ as ii,A as Js,B as Qs,C as Zs,D as ei,E as ti,L as K,N as rs,P as hn,Q as ni,R as oi,S as pt,T as Yt,U as ss,V as Jt,Y as ri,Z as si,a as s,aa as ai,c as zs,ca as li,ea as ui,fa as Dn,g as zt,ga as Bn,h as Vt,ha as gn,i as Gt,ia as dt,j as Kt,k as Nn,ka as An,l as Pn,la as ci,m as pn,n as dn,o as Rn,oa as mi,p as Vs,pa as pi,q as Gs,qa as di,r as Ks,ra as bi,s as os,sa as Ln,t as Xs,ta as hi,u as bn,v as kn,va as gi,w as Ys,x as Xt,y as _n,ya as fi,z as Mn}from"./core-IV5QBQ2N.js";import{z as yi}from"zod";var Fn=class{static{s(this,"TakeAriaSnapshot")}name(){return"a11y_take-aria-snapshot"}description(){return`
1
+ import{$ as ii,A as Js,B as Qs,C as Zs,D as ei,E as ti,L as K,N as rs,P as hn,Q as ni,R as oi,S as pt,T as Yt,U as ss,V as Jt,Y as ri,Z as si,a as s,aa as ai,c as zs,ca as li,ea as ui,fa as Dn,g as zt,ga as Bn,h as Vt,ha as gn,i as Gt,ia as dt,j as Kt,k as Nn,ka as An,l as Pn,la as ci,m as pn,n as dn,o as kn,oa as mi,p as Vs,pa as pi,q as Gs,qa as di,r as Ks,ra as bi,s as os,sa as Ln,t as Xs,ta as hi,u as bn,v as Rn,va as gi,w as Ys,x as Xt,y as _n,ya as fi,z as Mn}from"./core-IV5QBQ2N.js";import{z as yi}from"zod";var Fn=class{static{s(this,"TakeAriaSnapshot")}name(){return"a11y_take-aria-snapshot"}description(){return`
2
2
  Captures an ARIA (accessibility) snapshot of the current page or a specific element.
3
3
  If a selector is provided, the snapshot is scoped to that element; otherwise, the entire page is captured.
4
4
  The output includes the page URL, title, and a YAML-formatted accessibility tree.
@@ -265,18 +265,18 @@ By default, all <script> tags are removed from the output unless "removeScripts"
265
265
  `}inputSchema(){return{selector:bt.string().describe("CSS selector to limit the HTML content to a specific container.").optional(),removeScripts:bt.boolean().describe('Remove all script tags from the HTML (default: "true").').optional().default(!0),removeComments:bt.boolean().describe('Remove all HTML comments (default: "false").').optional().default(!1),removeStyles:bt.boolean().describe('Remove all style tags from the HTML (default: "false").').optional().default(!1),removeMeta:bt.boolean().describe('Remove all meta tags from the HTML (default: "false").').optional().default(!1),cleanHtml:bt.boolean().describe('Perform comprehensive HTML cleaning (default: "false").').optional().default(!1),minify:bt.boolean().describe('Minify the HTML output (default: "false").').optional().default(!1),maxLength:bt.number().int().positive().describe(`Maximum number of characters to return (default: "${Ni}").`).optional().default(Ni)}}outputSchema(){return{output:bt.string().describe("The requested HTML content of the page.")}}async handle(e,t){let{selector:n,removeScripts:r,removeComments:i,removeStyles:a,removeMeta:l,minify:u,cleanHtml:m,maxLength:c}=t,p;if(n){let U=await e.page.$(n);if(!U)throw new Error(`Element with selector "${n}" not found`);p=await U.evaluate(D=>D.outerHTML)}else p=await e.page.content();let b=r||m,f=i||m,x=a||m,B=l||m;(b||f||x||B||u)&&(p=await e.page.evaluate(U=>{let D=U.html,H=U.removeScripts,Q=U.removeComments,$=U.removeStyles,P=U.removeMeta,W=U.minify,G=document.createElement("template");G.innerHTML=D;let _=G.content;if(H&&_.querySelectorAll("script").forEach(M=>M.remove()),$&&_.querySelectorAll("style").forEach(M=>M.remove()),P&&_.querySelectorAll("meta").forEach(M=>M.remove()),Q){let Y=s(M=>{let ee=M.childNodes;for(let ue=ee.length-1;ue>=0;ue--){let ce=ee[ue];ce.nodeType===8?M.removeChild(ce):ce.nodeType===1&&Y(ce)}},"removeComments");Y(_)}let oe=G.innerHTML;return W&&(oe=oe.replace(/>\s+</g,"><").trim()),oe},{html:p,removeScripts:b,removeComments:f,removeStyles:x,removeMeta:B,minify:u}));let w=p;return w.length>c&&(w=w.slice(0,c)+`
266
266
  <!-- Output truncated due to size limits -->`),{output:w}}};import{z as is}from"zod";var Pi=5e4,Wn=class{static{s(this,"GetAsText")}name(){return"content_get-as-text"}description(){return"Gets the visible text content of the current page."}inputSchema(){return{selector:is.string().describe("CSS selector to limit the text content to a specific container.").optional(),maxLength:is.number().int().positive().describe(`Maximum number of characters to return (default: "${Pi}").`).optional().default(Pi)}}outputSchema(){return{output:is.string().describe("The requested text content of the page.")}}async handle(e,t){let{selector:n,maxLength:r}=t,a=await e.page.evaluate(l=>{let u=l.selector,m=u?document.querySelector(u):document.body;if(!m)throw new Error(`Element with selector "${u}" not found`);let c=document.createTreeWalker(m,NodeFilter.SHOW_TEXT,{acceptNode:s(f=>{let x=window.getComputedStyle(f.parentElement);return x.display!=="none"&&x.visibility!=="hidden"?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_REJECT},"acceptNode")}),p="",b;for(;b=c.nextNode();){let f=b.textContent?.trim();f&&(p+=f+`
267
267
  `)}return p.trim()},{selector:n});return a.length>r&&(a=a.slice(0,r)+`
268
- [Output truncated due to size limits]`),{output:a}}};function xe(o){let e=Object.keys(o).filter(t=>isNaN(Number(t))).map(t=>o[t]);if(e.length===0)throw new Error("Enum has no values");return e}s(xe,"getEnumKeyTuples");function rt(o,e){let t=Object.keys(o).filter(i=>isNaN(Number(i))).map(i=>o[i]),n=e?.caseInsensitive??!0,r=new Map(t.map(i=>[n?i.toLowerCase():i,i]));return i=>{let a=n?i.toLowerCase():i,l=r.get(a);if(l===void 0)throw new Error(`Invalid enum value: "${i}"`);return l}}s(rt,"createEnumTransformer");function qn(o=new Date){let e=s(t=>String(t).padStart(2,"0"),"pad");return o.getFullYear()+e(o.getMonth()+1)+e(o.getDate())+"-"+e(o.getHours())+e(o.getMinutes())+e(o.getSeconds())}s(qn,"formattedTimeForFilename");import Fl from"node:os";import Ul from"node:path";import{z as st}from"zod";var Ri=(r=>(r.PIXEL="px",r.INCH="in",r.CENTIMETER="cm",r.MILLIMETER="mm",r))(Ri||{}),$n=(p=>(p.LETTER="Letter",p.LEGAL="Legal",p.TABLOID="Tabloid",p.LEDGER="Ledger",p.A0="A0",p.A1="A1",p.A2="A2",p.A3="A3",p.A4="A4",p.A5="A5",p.A6="A6",p))($n||{}),as="page",Tt="1cm",Hl="A4",Wl={top:Tt,right:Tt,bottom:Tt,left:Tt},jn=class{static{s(this,"SaveAsPdf")}name(){return"content_save-as-pdf"}description(){return"Saves the current page as a PDF file."}inputSchema(){return{outputPath:st.string().describe("Directory path where PDF will be saved. By default OS tmp directory is used.").optional().default(Fl.tmpdir()),name:st.string().describe(`Name of the save/export. Default value is "${as}". Note that final saved/exported file name is in the "{name}-{time}.pdf" format in which "{time}" is in the "YYYYMMDD-HHmmss" format.`).optional().default(as),format:st.enum(xe($n)).transform(rt($n)).describe(`Page format. Valid values are: ${xe($n)}.`).optional().default(Hl),printBackground:st.boolean().describe('Whether to print background graphics (default: "false").').optional().default(!1),margin:st.object({top:st.string().describe("Top margin.").default(Tt),right:st.string().describe("Right margin.").default(Tt),bottom:st.string().describe("Bottom margin.").default(Tt),left:st.string().describe("Left margin.").default(Tt)}).describe(`Page margins. Numeric margin values labeled with units ("100px", "10cm", etc ...). Unlabeled values are treated as pixels. Valid units are: ${xe(Ri)}.`).optional()}}outputSchema(){return{filePath:st.string().describe("Full path of the saved PDF file.")}}async handle(e,t){let n=`${t.name||as}-${qn()}.pdf`,r=Ul.resolve(t.outputPath,n),i={path:r,format:t.format,printBackground:t.printBackground,margin:t.margin||Wl};return await e.page.pdf(i),{filePath:r}}};import ql from"node:os";import $l from"node:path";import zn from"jpeg-js";import{PNG as jl}from"pngjs";import{z as Xe}from"zod";var Vn=(t=>(t.PNG="png",t.JPEG="jpeg",t))(Vn||{}),ls="screenshot",ki="png",_i=100,Gn=class{static{s(this,"TakeScreenshot")}name(){return"content_take-screenshot"}description(){return`Takes a screenshot of the current page or a specific element.
268
+ [Output truncated due to size limits]`),{output:a}}};function xe(o){let e=Object.keys(o).filter(t=>isNaN(Number(t))).map(t=>o[t]);if(e.length===0)throw new Error("Enum has no values");return e}s(xe,"getEnumKeyTuples");function rt(o,e){let t=Object.keys(o).filter(i=>isNaN(Number(i))).map(i=>o[i]),n=e?.caseInsensitive??!0,r=new Map(t.map(i=>[n?i.toLowerCase():i,i]));return i=>{let a=n?i.toLowerCase():i,l=r.get(a);if(l===void 0)throw new Error(`Invalid enum value: "${i}"`);return l}}s(rt,"createEnumTransformer");function qn(o=new Date){let e=s(t=>String(t).padStart(2,"0"),"pad");return o.getFullYear()+e(o.getMonth()+1)+e(o.getDate())+"-"+e(o.getHours())+e(o.getMinutes())+e(o.getSeconds())}s(qn,"formattedTimeForFilename");import Fl from"node:os";import Ul from"node:path";import{z as st}from"zod";var ki=(r=>(r.PIXEL="px",r.INCH="in",r.CENTIMETER="cm",r.MILLIMETER="mm",r))(ki||{}),$n=(p=>(p.LETTER="Letter",p.LEGAL="Legal",p.TABLOID="Tabloid",p.LEDGER="Ledger",p.A0="A0",p.A1="A1",p.A2="A2",p.A3="A3",p.A4="A4",p.A5="A5",p.A6="A6",p))($n||{}),as="page",Tt="1cm",Hl="A4",Wl={top:Tt,right:Tt,bottom:Tt,left:Tt},jn=class{static{s(this,"SaveAsPdf")}name(){return"content_save-as-pdf"}description(){return"Saves the current page as a PDF file."}inputSchema(){return{outputPath:st.string().describe("Directory path where PDF will be saved. By default OS tmp directory is used.").optional().default(Fl.tmpdir()),name:st.string().describe(`Name of the save/export. Default value is "${as}". Note that final saved/exported file name is in the "{name}-{time}.pdf" format in which "{time}" is in the "YYYYMMDD-HHmmss" format.`).optional().default(as),format:st.enum(xe($n)).transform(rt($n)).describe(`Page format. Valid values are: ${xe($n)}.`).optional().default(Hl),printBackground:st.boolean().describe('Whether to print background graphics (default: "false").').optional().default(!1),margin:st.object({top:st.string().describe("Top margin.").default(Tt),right:st.string().describe("Right margin.").default(Tt),bottom:st.string().describe("Bottom margin.").default(Tt),left:st.string().describe("Left margin.").default(Tt)}).describe(`Page margins. Numeric margin values labeled with units ("100px", "10cm", etc ...). Unlabeled values are treated as pixels. Valid units are: ${xe(ki)}.`).optional()}}outputSchema(){return{filePath:st.string().describe("Full path of the saved PDF file.")}}async handle(e,t){let n=`${t.name||as}-${qn()}.pdf`,r=Ul.resolve(t.outputPath,n),i={path:r,format:t.format,printBackground:t.printBackground,margin:t.margin||Wl};return await e.page.pdf(i),{filePath:r}}};import ql from"node:os";import $l from"node:path";import zn from"jpeg-js";import{PNG as jl}from"pngjs";import{z as Xe}from"zod";var Vn=(t=>(t.PNG="png",t.JPEG="jpeg",t))(Vn||{}),ls="screenshot",Ri="png",_i=100,Gn=class{static{s(this,"TakeScreenshot")}name(){return"content_take-screenshot"}description(){return`Takes a screenshot of the current page or a specific element.
269
269
  The screenshot is ALWAYS saved to the file system; the file path is returned.
270
270
  By default, image data is NOT included in the response (includeBase64 defaults to false).
271
271
  **Prefer ARIA or AX tree snapshots for structure/layout/accessibility; use this tool only when you truly need to see the visual appearance of the UI.**
272
- Do NOT set includeBase64 to true unless the assistant cannot read the file from the returned path (e.g. remote server, container). When in doubt, omit includeBase64 or set it to false.`}inputSchema(){return{outputPath:Xe.string().describe("Directory path where screenshot will be saved. By default OS tmp directory is used.").optional().default(ql.tmpdir()),name:Xe.string().describe(`Name of the screenshot. Default value is "${ls}". Note that final saved/exported file name is in the "{name}-{time}.{type}" format in which "{time}" is in the "YYYYMMDD-HHmmss" format.`).optional().default(ls),selector:Xe.string().describe("CSS selector for element to take screenshot.").optional(),fullPage:Xe.boolean().describe('Whether to take a screenshot of the full scrollable page, instead of the currently visible viewport (default: "false").').optional().default(!1),type:Xe.enum(xe(Vn)).transform(rt(Vn)).describe(`Page format. Valid values are: ${xe(Vn)}`).optional().default(ki),quality:Xe.number().int().min(0).max(_i).describe("The quality of the image, between 0-100. Not applicable to png images.").optional(),includeBase64:Xe.boolean().describe("If true, includes base64 image data in the response (increases payload size). Default is false. The screenshot is always saved to disk; use the returned file path to read it. Set to true ONLY when the assistant cannot access the MCP server file system (e.g. remote/container). Avoid setting to true otherwise.").optional().default(!1)}}outputSchema(){return{filePath:Xe.string().describe("Full path of the saved screenshot file."),image:Xe.object({data:Xe.any().describe("Base64-encoded image data."),mimeType:Xe.string().describe("MIME type of the image.")}).optional().describe('Image data included only when "includeBase64" input parameter is set to true.')}}_scaleImageToSize(e,t){let{data:n,width:r,height:i}=e,a=Math.max(1,Math.floor(t.width)),l=Math.max(1,Math.floor(t.height));if(r===a&&i===l)return e;if(r<=0||i<=0)throw new Error("Invalid input image");if(t.width<=0||t.height<=0||!isFinite(t.width)||!isFinite(t.height))throw new Error("Invalid output dimensions");let u=s(($,P,W)=>$<P?P:$>W?W:$,"clamp"),m=s(($,P)=>{let W=$*$,G=W*$;P[0]=-.5*$+1*W-.5*G,P[1]=1-2.5*W+1.5*G,P[2]=.5*$+2*W-1.5*G,P[3]=-.5*W+.5*G},"weights"),c=r*4,p=a*4,b=new Int32Array(a*4),f=new Float32Array(a*4),x=new Float32Array(4),B=r/a;for(let $=0;$<a;$++){let P=($+.5)*B-.5,W=Math.floor(P),G=P-W;m(G,x);let _=$*4,oe=u(W-1,0,r-1),Y=u(W+0,0,r-1),M=u(W+1,0,r-1),ee=u(W+2,0,r-1);b[_+0]=oe<<2,b[_+1]=Y<<2,b[_+2]=M<<2,b[_+3]=ee<<2,f[_+0]=x[0],f[_+1]=x[1],f[_+2]=x[2],f[_+3]=x[3]}let w=new Int32Array(l*4),U=new Float32Array(l*4),D=new Float32Array(4),H=i/l;for(let $=0;$<l;$++){let P=($+.5)*H-.5,W=Math.floor(P),G=P-W;m(G,D);let _=$*4,oe=u(W-1,0,i-1),Y=u(W+0,0,i-1),M=u(W+1,0,i-1),ee=u(W+2,0,i-1);w[_+0]=oe*c,w[_+1]=Y*c,w[_+2]=M*c,w[_+3]=ee*c,U[_+0]=D[0],U[_+1]=D[1],U[_+2]=D[2],U[_+3]=D[3]}let Q=new Uint8Array(a*l*4);for(let $=0;$<l;$++){let P=$*4,W=w[P+0],G=w[P+1],_=w[P+2],oe=w[P+3],Y=U[P+0],M=U[P+1],ee=U[P+2],ue=U[P+3],ce=$*p;for(let fe=0;fe<a;fe++){let te=fe*4,me=b[te+0],v=b[te+1],pe=b[te+2],V=b[te+3],q=f[te+0],X=f[te+1],Pe=f[te+2],Ie=f[te+3],ft=ce+(fe<<2);for(let J=0;J<4;J++){let Ce=n[W+me+J]*q+n[W+v+J]*X+n[W+pe+J]*Pe+n[W+V+J]*Ie,We=n[G+me+J]*q+n[G+v+J]*X+n[G+pe+J]*Pe+n[G+V+J]*Ie,Le=n[_+me+J]*q+n[_+v+J]*X+n[_+pe+J]*Pe+n[_+V+J]*Ie,un=n[oe+me+J]*q+n[oe+v+J]*X+n[oe+pe+J]*Pe+n[oe+V+J]*Ie,qe=Ce*Y+We*M+Le*ee+un*ue;Q[ft+J]=qe<0?0:qe>255?255:qe|0}}}return{data:Buffer.from(Q.buffer),width:a,height:l}}_scaleImageToFitMessage(e,t){let r=12058624e-1,i=1568,a=t==="png"?jl.sync.read(e):zn.decode(e,{maxMemoryUsageInMB:512}),l=a.width*a.height,u=Math.min(i/a.width,i/a.height,Math.sqrt(r/l));u>1&&(u=1);let m=a.width*u|0,c=a.height*u|0,p=this._scaleImageToSize(a,{width:m,height:c}),b,f=t,x=t==="png"?75:70;t==="png"?(b=zn.encode(p,x).data,f="jpeg"):b=zn.encode(p,x).data;let B=0,w=5;for(;b.length>819200&&B<w;)x=Math.max(50,x-10),x<=50&&b.length>819200&&(u*=.85,m=Math.max(200,a.width*u|0),c=Math.max(200,a.height*u|0),p=this._scaleImageToSize(a,{width:m,height:c})),b=zn.encode(p,x).data,B++;return b}async handle(e,t){let n=t.type||ki,r=`${t.name||ls}-${qn()}.${n}`,i=$l.resolve(t.outputPath,r),a=n==="png"?void 0:t.quality??_i,l={path:i,type:n,fullPage:!!t.fullPage,quality:a};if(t.selector){let c=await e.page.$(t.selector);if(!c)throw new Error(`Element not found: ${t.selector}`);l.element=c}let u=await e.page.screenshot(l),m={filePath:i};return t.includeBase64&&(m.image={data:this._scaleImageToFitMessage(u,n),mimeType:`image/${n}`}),m}};var Mi=[new Hn,new Wn,new jn,new Gn];import{z as Re}from"zod";var us={maxSnapshots:1e3,maxCallStackDepth:20,maxFramesWithScopes:5,maxAsyncStackSegments:10,maxFramesPerAsyncSegment:10,maxDOMMutations:100,maxDOMHtmlSnippetLength:200,maxPendingRequests:1e3,maxResponseBodyLength:1e4,networkCleanupTimeoutMs:5e3},cs=new WeakMap;function Ft(){let o=Date.now(),e=Math.floor(Math.random()*1e6);return`${o.toString(36)}-${e.toString(36)}`}s(Ft,"_generateId");function zl(o,e){try{let t=o.trim();return/^[=<>!%]/.test(t)&&(t=`hitCount ${t}`),!!new Function("hitCount",`return (${t});`)(e)}catch{return!1}}s(zl,"_evaluateHitCondition");async function Vl(o,e,t){let n={};for(let r of t.values())try{let i=await o.evaluateOnCallFrame(e,r.expression);if(i.exceptionDetails)n[r.expression]=`[Error: ${i.exceptionDetails.text||"Evaluation failed"}]`;else{let a=await o.extractValueDeep(i.result,2);n[r.expression]=a}}catch(i){n[r.expression]=`[Error: ${i.message||"Unknown error"}]`}return n}s(Vl,"_evaluateWatchExpressionsOnFrame");function Bi(o,e,t,n){let r=cs.get(o);if(r)return r;let i=new ni(e,t),a=new oi(e),l={...us,...n},u={v8Api:i,sourceMapResolver:a,probes:new Map,watchExpressions:new Map,domBreakpoints:new Map,networkBreakpoints:new Map,snapshots:[],snapshotSequence:0,config:l,enabled:!1,sourceMapsLoaded:!1,exceptionBreakpoint:"none",networkInterceptionEnabled:!1,recentDOMMutations:[]};return cs.set(o,u),u}s(Bi,"_ensureStore");function ge(o){return cs.get(o)}s(ge,"_getStore");async function Gl(o,e,t=3){let n=[];for(let r of e.scopeChain)if(!(r.type==="global"||r.type==="script"||r.type==="with"||r.type==="eval"||r.type==="wasm-expression-stack")){if(n.length>=t)break;try{let i=await o.getScopeVariables(r),a=[];for(let[l,u]of Object.entries(i))a.push({name:l,value:u,type:typeof u});n.push({type:r.type,name:r.name,variables:a})}catch{}}return n}s(Gl,"_captureScopes");async function Kl(o,e,t,n){let r=[];t&&(r=await Gl(o,e));let i;if(n){let a=n.generatedToOriginal(e.location.scriptId,e.location.lineNumber,e.location.columnNumber??0);a&&(i={source:a.source,line:a.line+1,column:a.column!==void 0?a.column+1:void 0,name:a.name})}return{functionName:e.functionName||"(anonymous)",url:e.url||"",lineNumber:e.location.lineNumber+1,columnNumber:e.location.columnNumber!==void 0?e.location.columnNumber+1:void 0,scriptId:e.location.scriptId,scopes:r,originalLocation:i}}s(Kl,"_callFrameToSnapshot");function Xl(o,e,t,n){if(!o)return;let r=t??us.maxAsyncStackSegments,i=n??us.maxFramesPerAsyncSegment,a=[],l=o,u=0;for(;l&&u<r;){let m=[];for(let c of l.callFrames.slice(0,i)){let p;if(e){let b=e.generatedToOriginal(c.location.scriptId,c.location.lineNumber,c.location.columnNumber??0);b&&(p={source:b.source,line:b.line+1,column:b.column!==void 0?b.column+1:void 0,name:b.name})}m.push({functionName:c.functionName||"(anonymous)",url:c.url||"",lineNumber:c.location.lineNumber+1,columnNumber:c.location.columnNumber!==void 0?c.location.columnNumber+1:void 0,originalLocation:p})}m.length>0&&a.push({description:l.description,callFrames:m}),l=l.parent,u++}if(a.length!==0)return{segments:a}}s(Xl,"_convertAsyncStackTrace");async function Ue(o,e,t){let n=Bi(o,e,t?.v8Options,t?.config);if(!n.enabled){await n.v8Api.enable(),n.v8Api.on("scriptParsed",r=>{n.sourceMapResolver.registerScript(r)});for(let r of n.v8Api.getScripts())n.sourceMapResolver.registerScript(r);n.v8Api.on("paused",async r=>{let i=Date.now();try{let a=r.reason==="exception"||r.reason==="promiseRejection",l=r.reason==="DOM",u=r.hitBreakpoints||[],m,c=!0,p,b;if(l&&r.data){let w=r.data;for(let U of n.domBreakpoints.values())if(U.enabled&&(U.nodeId===w.nodeId||!w.nodeId)){p=U,b={type:U.type,selector:U.selector,targetNode:w.targetNode?`<${w.targetNode.nodeName?.toLowerCase()||"unknown"}>`:void 0,attributeName:w.attributeName||U.attributeName};break}}if(p&&b)try{let w=await e.evaluate(U=>{let D=window;if(!D.__domBreakpointMutations)return null;let H=D.__domBreakpointMutations;for(let Q=H.length-1;Q>=0;Q--)if(H[Q].breakpointId===U)return H[Q];return null},p.id);w&&(b.oldValue=w.oldValue,b.newValue=w.newValue,b.targetNode=w.targetOuterHTML,w.attributeName&&(b.attributeName=w.attributeName))}catch{}for(let w of n.probes.values()){if(!w.enabled)continue;if(w.v8BreakpointIds.some(D=>u.includes(D))){m=w,w.hitCondition&&(c=zl(w.hitCondition,w.hitCount+1));break}}let f=m!==void 0&&c,x=a&&n.exceptionBreakpoint!=="none",B=p!==void 0;if(m&&(m.hitCount++,m.lastHitAt=Date.now()),p&&(p.hitCount++,p.lastHitAt=Date.now()),(f||x||B)&&r.callFrames.length>0){let w=r.callFrames[0],U;if(m&&m.kind==="logpoint"&&m.logExpression)try{let Y=await n.v8Api.evaluateOnCallFrame(w.callFrameId,m.logExpression,{returnByValue:!0,generatePreview:!0});U=n.v8Api.extractValue(Y.result)}catch{U="[evaluation error]"}let D;if(a&&r.data){let Y=r.data;D={type:r.reason==="promiseRejection"?"promiseRejection":"exception",message:Y.description||Y.value||String(Y),name:Y.className,stack:Y.description}}let H,Q=n.sourceMapResolver.generatedToOriginal(w.location.scriptId,w.location.lineNumber,w.location.columnNumber??0);Q&&(H={source:Q.source,line:Q.line+1,column:Q.column!==void 0?Q.column+1:void 0,name:Q.name});let $=m?.id??p?.id??"__exception__",P=m?.kind==="logpoint",W=[];if(!P){let Y=r.callFrames.slice(0,n.config.maxCallStackDepth);for(let M=0;M<Y.length;M++){let ee=Y[M],ue=M<n.config.maxFramesWithScopes,ce=await Kl(n.v8Api,ee,ue,n.sourceMapResolver);W.push(ce)}}let G;P||(G=Xl(r.asyncStackTrace,n.sourceMapResolver,n.config.maxAsyncStackSegments,n.config.maxFramesPerAsyncSegment));let _;!P&&n.watchExpressions.size>0&&(_=await Vl(n.v8Api,w.callFrameId,n.watchExpressions));let oe={id:Ft(),probeId:$,timestamp:Date.now(),sequenceNumber:++n.snapshotSequence,url:w.url||"",lineNumber:w.location.lineNumber+1,columnNumber:w.location.columnNumber!==void 0?w.location.columnNumber+1:void 0,originalLocation:H,exception:D,domChange:b,callStack:W,asyncStackTrace:G,logResult:U,watchResults:_,captureTimeMs:Date.now()-i};n.snapshots.push(oe),n.snapshots.length>n.config.maxSnapshots&&n.snapshots.splice(0,n.snapshots.length-n.config.maxSnapshots)}}finally{await n.v8Api.resume()}}),n.enabled=!0,n.sourceMapResolver.loadAllSourceMaps().then(()=>{n.sourceMapsLoaded=!0}).catch(()=>{})}}s(Ue,"enableDebugging");function N(o){return ge(o)?.enabled??!1}s(N,"isDebuggingEnabled");async function Ai(o,e,t,n,r=1){let i=Bi(o,e);i.enabled||await Ue(o,e);let a=await i.sourceMapResolver.resolveLocationByUrl(t,n,r);return a?{source:a.source,line:a.line+1,column:a.column+1,name:a.name}:null}s(Ai,"resolveSourceLocation");async function Li(o,e){let t=ge(o);if(!t||!t.enabled)throw new Error("Debugging is not enabled");await t.v8Api.setPauseOnExceptions(e),t.exceptionBreakpoint=e}s(Li,"setExceptionBreakpoint");function fn(o){return ge(o)?.exceptionBreakpoint??"none"}s(fn,"getExceptionBreakpoint");function Fi(o){return ge(o)?.sourceMapResolver.hasSourceMaps()??!1}s(Fi,"hasSourceMaps");async function Kn(o,e){let t=ge(o);if(!t||!t.enabled)throw new Error("Debugging is not enabled");let n=Ft(),r;e.condition?r=`(${e.condition})`:r="true";let i=e.lineNumber-1,a=(e.columnNumber??1)-1,l=t.sourceMapResolver.originalToGenerated(e.urlPattern,i,a),u,m=0;if(l)u=(await t.v8Api.setBreakpoint({scriptId:l.scriptId,lineNumber:l.location.line,columnNumber:l.location.column},r)).breakpointId,m=1;else{let b=e.urlPattern.replace(/\\([.*+?^${}()|[\]\\/-])/g,"$1").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*").replace(/\\\?/g,"."),f=await t.v8Api.setBreakpointByUrl({urlRegex:b,lineNumber:e.lineNumber-1,columnNumber:e.columnNumber?e.columnNumber-1:void 0,condition:r});u=f.breakpointId,m=f.locations.length}let c={id:n,kind:e.kind,enabled:!0,urlPattern:e.urlPattern,lineNumber:e.lineNumber,columnNumber:e.columnNumber,condition:e.condition,logExpression:e.logExpression,hitCondition:e.hitCondition,v8BreakpointIds:[u],resolvedLocations:m,hitCount:0,createdAt:Date.now()};return t.probes.set(n,c),c}s(Kn,"createProbe");async function St(o,e){let t=ge(o);if(!t)return!1;let n=t.probes.get(e);if(!n)return!1;for(let r of n.v8BreakpointIds)try{await t.v8Api.removeBreakpoint(r)}catch{}return t.probes.delete(e),!0}s(St,"removeProbe");function ve(o){let e=ge(o);return e?Array.from(e.probes.values()):[]}s(ve,"listProbes");function Xn(o,e){let t=ge(o);if(t)return t.probes.get(e)}s(Xn,"getProbe");function xt(o){let e=ge(o);return e?[...e.snapshots]:[]}s(xt,"getSnapshots");function it(o,e){let t=ge(o);return t?t.snapshots.filter(n=>n.probeId===e):[]}s(it,"getSnapshotsByProbe");function De(o,e){let t=ge(o);if(!t)return 0;let n=t.snapshots.length;return t.snapshots=t.snapshots.filter(r=>r.probeId!==e),n-t.snapshots.length}s(De,"clearSnapshotsByProbe");function Ui(o){let e=ge(o);if(!e||e.snapshots.length===0)return{totalSnapshots:0,snapshotsByProbe:{},averageCaptureTimeMs:0};let t={},n=0;for(let r of e.snapshots)t[r.probeId]=(t[r.probeId]||0)+1,n+=r.captureTimeMs;return{totalSnapshots:e.snapshots.length,snapshotsByProbe:t,oldestTimestamp:e.snapshots[0].timestamp,newestTimestamp:e.snapshots[e.snapshots.length-1].timestamp,averageCaptureTimeMs:n/e.snapshots.length}}s(Ui,"getSnapshotStats");function Hi(o,e){let t=ge(o);if(!t)throw new Error("Debug store not initialized");let n=Ft(),r={id:n,expression:e,createdAt:Date.now()};return t.watchExpressions.set(n,r),r}s(Hi,"addWatchExpression");function Wi(o,e){let t=ge(o);return t?t.watchExpressions.delete(e):!1}s(Wi,"removeWatchExpression");function Yn(o){let e=ge(o);return e?Array.from(e.watchExpressions.values()):[]}s(Yn,"listWatchExpressions");function qi(o){let e=ge(o);if(!e)return 0;let t=e.watchExpressions.size;return e.watchExpressions.clear(),t}s(qi,"clearWatchExpressions");async function $i(o,e,t){let n=ge(o);if(!n||!n.enabled)throw new Error("Debugging is not enabled");let r=await n.v8Api.getCdp();await r.send("DOM.enable");let{root:i}=await r.send("DOM.getDocument",{depth:0}),{nodeId:a}=await r.send("DOM.querySelector",{nodeId:i.nodeId,selector:t.selector});if(!a||a===0)throw new Error(`Element not found: ${t.selector}`);let l=t.type==="subtree-modified"?"subtree-modified":t.type==="attribute-modified"?"attribute-modified":"node-removed";await r.send("DOMDebugger.setDOMBreakpoint",{nodeId:a,type:l});let u=Ft(),m={id:u,selector:t.selector,type:t.type,attributeName:t.attributeName,enabled:!0,nodeId:a,hitCount:0,createdAt:Date.now()};return n.domBreakpoints.set(u,m),await e.evaluate(c=>{let p=c.selector,b=c.breakpointId,f=c.type,x=c.attrName,B=c.maxMutations,w=c.maxHtmlSnippetLength,U=document.querySelector(p);if(!U)return;let D=window;D.__domBreakpointData=D.__domBreakpointData||{},D.__domBreakpointMutations=D.__domBreakpointMutations||[],D.__domBreakpointData[b]={selector:p,type:f,attrName:x,currentAttrs:{}};for(let $ of U.attributes)D.__domBreakpointData[b].currentAttrs[$.name]=$.value;let H=new MutationObserver($=>{for(let P of $){let W=P.target;if(P.type==="attributes"){let G=P.attributeName||"";if(x&&x!==G)continue;let _={breakpointId:b,selector:p,type:"attribute-modified",attributeName:G,oldValue:P.oldValue,newValue:W.getAttribute(G),targetOuterHTML:W.outerHTML.substring(0,w),timestamp:Date.now()};D.__domBreakpointMutations.push(_),D.__domBreakpointMutations.length>B&&D.__domBreakpointMutations.shift(),D.__domBreakpointData[b].currentAttrs[G]=W.getAttribute(G)}else if(P.type==="childList"){let G={breakpointId:b,selector:p,type:"subtree-modified",addedNodes:P.addedNodes.length,removedNodes:P.removedNodes.length,targetOuterHTML:W.outerHTML.substring(0,w),timestamp:Date.now()};D.__domBreakpointMutations.push(G),D.__domBreakpointMutations.length>B&&D.__domBreakpointMutations.shift()}}}),Q={attributes:f==="attribute-modified",attributeOldValue:f==="attribute-modified",childList:f==="subtree-modified"||f==="node-removed",subtree:f==="subtree-modified"};x&&(Q.attributeFilter=[x]),H.observe(U,Q),D.__domBreakpointObservers=D.__domBreakpointObservers||{},D.__domBreakpointObservers[b]=H},{selector:t.selector,breakpointId:u,type:t.type,attrName:t.attributeName,maxMutations:n.config.maxDOMMutations,maxHtmlSnippetLength:n.config.maxDOMHtmlSnippetLength}),m}s($i,"setDOMBreakpoint");async function ms(o,e,t){let n=ge(o);if(!n)return!1;let r=n.domBreakpoints.get(e);if(!r||!r.nodeId)return!1;try{let i=await n.v8Api.getCdp(),a=r.type==="subtree-modified"?"subtree-modified":r.type==="attribute-modified"?"attribute-modified":"node-removed";await i.send("DOMDebugger.removeDOMBreakpoint",{nodeId:r.nodeId,type:a})}catch{}if(t)try{await t.evaluate(i=>{let a=window;a.__domBreakpointObservers&&a.__domBreakpointObservers[i]&&(a.__domBreakpointObservers[i].disconnect(),delete a.__domBreakpointObservers[i]),a.__domBreakpointData&&delete a.__domBreakpointData[i],a.__domBreakpointMutations&&(a.__domBreakpointMutations=a.__domBreakpointMutations.filter(l=>l.breakpointId!==i))},e)}catch{}return n.domBreakpoints.delete(e)}s(ms,"removeDOMBreakpoint");function vt(o){let e=ge(o);return e?Array.from(e.domBreakpoints.values()):[]}s(vt,"listDOMBreakpoints");async function ji(o,e){let t=ge(o);if(!t)return 0;let n=Array.from(t.domBreakpoints.keys());for(let r of n)await ms(o,r,e);return n.length}s(ji,"clearDOMBreakpoints");async function Yl(o,e){if(o.networkInterceptionEnabled)return;let t=await o.v8Api.getCdp();await t.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]}),t.on("Fetch.requestPaused",async r=>{let i=r.requestId,a=r.request.url,l=r.request.method;try{let u;for(let m of o.networkBreakpoints.values()){if(!m.enabled)continue;let c=m.urlPattern.replace(/\\([.*+?^${}()|[\]\\/-])/g,"$1");if(new RegExp(c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")).test(a)&&!(m.method&&m.method.toUpperCase()!==l.toUpperCase())&&m.timing==="request"){u=m;break}}if(u&&u.timing==="request"){let m={url:a,method:l,requestHeaders:r.request.headers,requestBody:r.request.postData,resourceType:r.resourceType,timing:"request"},c={id:Ft(),probeId:u.id,timestamp:Date.now(),sequenceNumber:++o.snapshotSequence,url:a,lineNumber:0,networkRequest:m,callStack:[],captureTimeMs:0};o.watchExpressions.size>0&&(c.watchResults=await Di(o,e)),o.snapshots.push(c),o.snapshots.length>o.config.maxSnapshots&&o.snapshots.splice(0,o.snapshots.length-o.config.maxSnapshots),u.hitCount++,u.lastHitAt=Date.now()}await t.send("Fetch.continueRequest",{requestId:i})}catch{try{await t.send("Fetch.continueRequest",{requestId:i})}catch{}}}),await t.send("Network.enable");let n=new Map;t.on("Network.requestWillBeSent",r=>{if(n.set(r.requestId,{method:r.request.method,postData:r.request.postData}),n.size>o.config.maxPendingRequests){let i=n.keys().next().value;i&&n.delete(i)}}),t.on("Network.responseReceived",async r=>{let i=r.requestId,a=r.response.url,l=n.get(i),u=l?.method||r.type||"GET",m=r.response.status;for(let c of o.networkBreakpoints.values()){if(!c.enabled||c.timing!=="response")continue;let p=c.urlPattern.replace(/\\([.*+?^${}()|[\]\\/-])/g,"$1");if(!new RegExp(p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")).test(a)||c.method&&c.method.toUpperCase()!==u.toUpperCase()||c.onError&&m<400)continue;let f;try{let w=await t.send("Network.getResponseBody",{requestId:i});w.base64Encoded?f=Buffer.from(w.body,"base64").toString("utf-8"):f=w.body,f&&f.length>o.config.maxResponseBodyLength&&(f=f.substring(0,o.config.maxResponseBodyLength)+"... [truncated]")}catch{}let x={url:a,method:u,requestBody:l?.postData,status:m,statusText:r.response.statusText,responseHeaders:r.response.headers,responseBody:f,resourceType:r.type,timing:"response"},B={id:Ft(),probeId:c.id,timestamp:Date.now(),sequenceNumber:++o.snapshotSequence,url:a,lineNumber:0,networkRequest:x,callStack:[],captureTimeMs:0};o.watchExpressions.size>0&&(B.watchResults=await Di(o,e)),o.snapshots.push(B),o.snapshots.length>o.config.maxSnapshots&&o.snapshots.splice(0,o.snapshots.length-o.config.maxSnapshots),c.hitCount++,c.lastHitAt=Date.now(),n.delete(i);break}}),t.on("Network.loadingFinished",r=>{setTimeout(()=>{n.delete(r.requestId)},o.config.networkCleanupTimeoutMs)}),o.networkInterceptionEnabled=!0}s(Yl,"_enableNetworkInterception");async function Di(o,e){let t={};for(let n of o.watchExpressions.values())try{let r=await e.evaluate(i=>{try{return(0,eval)(i)}catch(a){return`[Error: ${a.message}]`}},n.expression);t[n.expression]=r}catch(r){t[n.expression]=`[Error: ${r.message}]`}return t}s(Di,"_evaluateWatchExpressions");async function zi(o,e,t){let n=ge(o);if(!n||!n.enabled)throw new Error("Debugging is not enabled");await Yl(n,e);let r=Ft(),i={id:r,urlPattern:t.urlPattern,method:t.method,timing:t.timing||"request",onError:t.onError,enabled:!0,hitCount:0,createdAt:Date.now()};return n.networkBreakpoints.set(r,i),i}s(zi,"setNetworkBreakpoint");function Vi(o,e){let t=ge(o);return t?t.networkBreakpoints.delete(e):!1}s(Vi,"removeNetworkBreakpoint");function It(o){let e=ge(o);return e?Array.from(e.networkBreakpoints.values()):[]}s(It,"listNetworkBreakpoints");function Gi(o){let e=ge(o);if(!e)return 0;let t=e.networkBreakpoints.size;return e.networkBreakpoints.clear(),t}s(Gi,"clearNetworkBreakpoints");var Jn=class{static{s(this,"Status")}name(){return"debug_status"}description(){return`
272
+ Do NOT set includeBase64 to true unless the assistant cannot read the file from the returned path (e.g. remote server, container). When in doubt, omit includeBase64 or set it to false.`}inputSchema(){return{outputPath:Xe.string().describe("Directory path where screenshot will be saved. By default OS tmp directory is used.").optional().default(ql.tmpdir()),name:Xe.string().describe(`Name of the screenshot. Default value is "${ls}". Note that final saved/exported file name is in the "{name}-{time}.{type}" format in which "{time}" is in the "YYYYMMDD-HHmmss" format.`).optional().default(ls),selector:Xe.string().describe("CSS selector for element to take screenshot.").optional(),fullPage:Xe.boolean().describe('Whether to take a screenshot of the full scrollable page, instead of the currently visible viewport (default: "false").').optional().default(!1),type:Xe.enum(xe(Vn)).transform(rt(Vn)).describe(`Page format. Valid values are: ${xe(Vn)}`).optional().default(Ri),quality:Xe.number().int().min(0).max(_i).describe("The quality of the image, between 0-100. Not applicable to png images.").optional(),includeBase64:Xe.boolean().describe("If true, includes base64 image data in the response (increases payload size). Default is false. The screenshot is always saved to disk; use the returned file path to read it. Set to true ONLY when the assistant cannot access the MCP server file system (e.g. remote/container). Avoid setting to true otherwise.").optional().default(!1)}}outputSchema(){return{filePath:Xe.string().describe("Full path of the saved screenshot file."),image:Xe.object({data:Xe.any().describe("Base64-encoded image data."),mimeType:Xe.string().describe("MIME type of the image.")}).optional().describe('Image data included only when "includeBase64" input parameter is set to true.')}}_scaleImageToSize(e,t){let{data:n,width:r,height:i}=e,a=Math.max(1,Math.floor(t.width)),l=Math.max(1,Math.floor(t.height));if(r===a&&i===l)return e;if(r<=0||i<=0)throw new Error("Invalid input image");if(t.width<=0||t.height<=0||!isFinite(t.width)||!isFinite(t.height))throw new Error("Invalid output dimensions");let u=s(($,P,W)=>$<P?P:$>W?W:$,"clamp"),m=s(($,P)=>{let W=$*$,G=W*$;P[0]=-.5*$+1*W-.5*G,P[1]=1-2.5*W+1.5*G,P[2]=.5*$+2*W-1.5*G,P[3]=-.5*W+.5*G},"weights"),c=r*4,p=a*4,b=new Int32Array(a*4),f=new Float32Array(a*4),x=new Float32Array(4),B=r/a;for(let $=0;$<a;$++){let P=($+.5)*B-.5,W=Math.floor(P),G=P-W;m(G,x);let _=$*4,oe=u(W-1,0,r-1),Y=u(W+0,0,r-1),M=u(W+1,0,r-1),ee=u(W+2,0,r-1);b[_+0]=oe<<2,b[_+1]=Y<<2,b[_+2]=M<<2,b[_+3]=ee<<2,f[_+0]=x[0],f[_+1]=x[1],f[_+2]=x[2],f[_+3]=x[3]}let w=new Int32Array(l*4),U=new Float32Array(l*4),D=new Float32Array(4),H=i/l;for(let $=0;$<l;$++){let P=($+.5)*H-.5,W=Math.floor(P),G=P-W;m(G,D);let _=$*4,oe=u(W-1,0,i-1),Y=u(W+0,0,i-1),M=u(W+1,0,i-1),ee=u(W+2,0,i-1);w[_+0]=oe*c,w[_+1]=Y*c,w[_+2]=M*c,w[_+3]=ee*c,U[_+0]=D[0],U[_+1]=D[1],U[_+2]=D[2],U[_+3]=D[3]}let Q=new Uint8Array(a*l*4);for(let $=0;$<l;$++){let P=$*4,W=w[P+0],G=w[P+1],_=w[P+2],oe=w[P+3],Y=U[P+0],M=U[P+1],ee=U[P+2],ue=U[P+3],ce=$*p;for(let fe=0;fe<a;fe++){let te=fe*4,me=b[te+0],v=b[te+1],pe=b[te+2],V=b[te+3],q=f[te+0],X=f[te+1],Pe=f[te+2],Ie=f[te+3],ft=ce+(fe<<2);for(let J=0;J<4;J++){let Ce=n[W+me+J]*q+n[W+v+J]*X+n[W+pe+J]*Pe+n[W+V+J]*Ie,We=n[G+me+J]*q+n[G+v+J]*X+n[G+pe+J]*Pe+n[G+V+J]*Ie,Le=n[_+me+J]*q+n[_+v+J]*X+n[_+pe+J]*Pe+n[_+V+J]*Ie,un=n[oe+me+J]*q+n[oe+v+J]*X+n[oe+pe+J]*Pe+n[oe+V+J]*Ie,qe=Ce*Y+We*M+Le*ee+un*ue;Q[ft+J]=qe<0?0:qe>255?255:qe|0}}}return{data:Buffer.from(Q.buffer),width:a,height:l}}_scaleImageToFitMessage(e,t){let r=12058624e-1,i=1568,a=t==="png"?jl.sync.read(e):zn.decode(e,{maxMemoryUsageInMB:512}),l=a.width*a.height,u=Math.min(i/a.width,i/a.height,Math.sqrt(r/l));u>1&&(u=1);let m=a.width*u|0,c=a.height*u|0,p=this._scaleImageToSize(a,{width:m,height:c}),b,f=t,x=t==="png"?75:70;t==="png"?(b=zn.encode(p,x).data,f="jpeg"):b=zn.encode(p,x).data;let B=0,w=5;for(;b.length>819200&&B<w;)x=Math.max(50,x-10),x<=50&&b.length>819200&&(u*=.85,m=Math.max(200,a.width*u|0),c=Math.max(200,a.height*u|0),p=this._scaleImageToSize(a,{width:m,height:c})),b=zn.encode(p,x).data,B++;return b}async handle(e,t){let n=t.type||Ri,r=`${t.name||ls}-${qn()}.${n}`,i=$l.resolve(t.outputPath,r),a=n==="png"?void 0:t.quality??_i,l={path:i,type:n,fullPage:!!t.fullPage,quality:a};if(t.selector){let c=await e.page.$(t.selector);if(!c)throw new Error(`Element not found: ${t.selector}`);l.element=c}let u=await e.page.screenshot(l),m={filePath:i};return t.includeBase64&&(m.image={data:this._scaleImageToFitMessage(u,n),mimeType:`image/${n}`}),m}};var Mi=[new Hn,new Wn,new jn,new Gn];import{z as ke}from"zod";var us={maxSnapshots:1e3,maxCallStackDepth:20,maxFramesWithScopes:5,maxAsyncStackSegments:10,maxFramesPerAsyncSegment:10,maxDOMMutations:100,maxDOMHtmlSnippetLength:200,maxPendingRequests:1e3,maxResponseBodyLength:1e4,networkCleanupTimeoutMs:5e3},cs=new WeakMap;function Ft(){let o=Date.now(),e=Math.floor(Math.random()*1e6);return`${o.toString(36)}-${e.toString(36)}`}s(Ft,"_generateId");function zl(o,e){try{let t=o.trim();return/^[=<>!%]/.test(t)&&(t=`hitCount ${t}`),!!new Function("hitCount",`return (${t});`)(e)}catch{return!1}}s(zl,"_evaluateHitCondition");async function Vl(o,e,t){let n={};for(let r of t.values())try{let i=await o.evaluateOnCallFrame(e,r.expression);if(i.exceptionDetails)n[r.expression]=`[Error: ${i.exceptionDetails.text||"Evaluation failed"}]`;else{let a=await o.extractValueDeep(i.result,2);n[r.expression]=a}}catch(i){n[r.expression]=`[Error: ${i.message||"Unknown error"}]`}return n}s(Vl,"_evaluateWatchExpressionsOnFrame");function Bi(o,e,t,n){let r=cs.get(o);if(r)return r;let i=new ni(e,t),a=new oi(e),l={...us,...n},u={v8Api:i,sourceMapResolver:a,probes:new Map,watchExpressions:new Map,domBreakpoints:new Map,networkBreakpoints:new Map,snapshots:[],snapshotSequence:0,config:l,enabled:!1,sourceMapsLoaded:!1,exceptionBreakpoint:"none",networkInterceptionEnabled:!1,recentDOMMutations:[]};return cs.set(o,u),u}s(Bi,"_ensureStore");function ge(o){return cs.get(o)}s(ge,"_getStore");async function Gl(o,e,t=3){let n=[];for(let r of e.scopeChain)if(!(r.type==="global"||r.type==="script"||r.type==="with"||r.type==="eval"||r.type==="wasm-expression-stack")){if(n.length>=t)break;try{let i=await o.getScopeVariables(r),a=[];for(let[l,u]of Object.entries(i))a.push({name:l,value:u,type:typeof u});n.push({type:r.type,name:r.name,variables:a})}catch{}}return n}s(Gl,"_captureScopes");async function Kl(o,e,t,n){let r=[];t&&(r=await Gl(o,e));let i;if(n){let a=n.generatedToOriginal(e.location.scriptId,e.location.lineNumber,e.location.columnNumber??0);a&&(i={source:a.source,line:a.line+1,column:a.column!==void 0?a.column+1:void 0,name:a.name})}return{functionName:e.functionName||"(anonymous)",url:e.url||"",lineNumber:e.location.lineNumber+1,columnNumber:e.location.columnNumber!==void 0?e.location.columnNumber+1:void 0,scriptId:e.location.scriptId,scopes:r,originalLocation:i}}s(Kl,"_callFrameToSnapshot");function Xl(o,e,t,n){if(!o)return;let r=t??us.maxAsyncStackSegments,i=n??us.maxFramesPerAsyncSegment,a=[],l=o,u=0;for(;l&&u<r;){let m=[];for(let c of l.callFrames.slice(0,i)){let p;if(e){let b=e.generatedToOriginal(c.location.scriptId,c.location.lineNumber,c.location.columnNumber??0);b&&(p={source:b.source,line:b.line+1,column:b.column!==void 0?b.column+1:void 0,name:b.name})}m.push({functionName:c.functionName||"(anonymous)",url:c.url||"",lineNumber:c.location.lineNumber+1,columnNumber:c.location.columnNumber!==void 0?c.location.columnNumber+1:void 0,originalLocation:p})}m.length>0&&a.push({description:l.description,callFrames:m}),l=l.parent,u++}if(a.length!==0)return{segments:a}}s(Xl,"_convertAsyncStackTrace");async function Ue(o,e,t){let n=Bi(o,e,t?.v8Options,t?.config);if(!n.enabled){await n.v8Api.enable(),n.v8Api.on("scriptParsed",r=>{n.sourceMapResolver.registerScript(r)});for(let r of n.v8Api.getScripts())n.sourceMapResolver.registerScript(r);n.v8Api.on("paused",async r=>{let i=Date.now();try{let a=r.reason==="exception"||r.reason==="promiseRejection",l=r.reason==="DOM",u=r.hitBreakpoints||[],m,c=!0,p,b;if(l&&r.data){let w=r.data;for(let U of n.domBreakpoints.values())if(U.enabled&&(U.nodeId===w.nodeId||!w.nodeId)){p=U,b={type:U.type,selector:U.selector,targetNode:w.targetNode?`<${w.targetNode.nodeName?.toLowerCase()||"unknown"}>`:void 0,attributeName:w.attributeName||U.attributeName};break}}if(p&&b)try{let w=await e.evaluate(U=>{let D=window;if(!D.__domBreakpointMutations)return null;let H=D.__domBreakpointMutations;for(let Q=H.length-1;Q>=0;Q--)if(H[Q].breakpointId===U)return H[Q];return null},p.id);w&&(b.oldValue=w.oldValue,b.newValue=w.newValue,b.targetNode=w.targetOuterHTML,w.attributeName&&(b.attributeName=w.attributeName))}catch{}for(let w of n.probes.values()){if(!w.enabled)continue;if(w.v8BreakpointIds.some(D=>u.includes(D))){m=w,w.hitCondition&&(c=zl(w.hitCondition,w.hitCount+1));break}}let f=m!==void 0&&c,x=a&&n.exceptionBreakpoint!=="none",B=p!==void 0;if(m&&(m.hitCount++,m.lastHitAt=Date.now()),p&&(p.hitCount++,p.lastHitAt=Date.now()),(f||x||B)&&r.callFrames.length>0){let w=r.callFrames[0],U;if(m&&m.kind==="logpoint"&&m.logExpression)try{let Y=await n.v8Api.evaluateOnCallFrame(w.callFrameId,m.logExpression,{returnByValue:!0,generatePreview:!0});U=n.v8Api.extractValue(Y.result)}catch{U="[evaluation error]"}let D;if(a&&r.data){let Y=r.data;D={type:r.reason==="promiseRejection"?"promiseRejection":"exception",message:Y.description||Y.value||String(Y),name:Y.className,stack:Y.description}}let H,Q=n.sourceMapResolver.generatedToOriginal(w.location.scriptId,w.location.lineNumber,w.location.columnNumber??0);Q&&(H={source:Q.source,line:Q.line+1,column:Q.column!==void 0?Q.column+1:void 0,name:Q.name});let $=m?.id??p?.id??"__exception__",P=m?.kind==="logpoint",W=[];if(!P){let Y=r.callFrames.slice(0,n.config.maxCallStackDepth);for(let M=0;M<Y.length;M++){let ee=Y[M],ue=M<n.config.maxFramesWithScopes,ce=await Kl(n.v8Api,ee,ue,n.sourceMapResolver);W.push(ce)}}let G;P||(G=Xl(r.asyncStackTrace,n.sourceMapResolver,n.config.maxAsyncStackSegments,n.config.maxFramesPerAsyncSegment));let _;!P&&n.watchExpressions.size>0&&(_=await Vl(n.v8Api,w.callFrameId,n.watchExpressions));let oe={id:Ft(),probeId:$,timestamp:Date.now(),sequenceNumber:++n.snapshotSequence,url:w.url||"",lineNumber:w.location.lineNumber+1,columnNumber:w.location.columnNumber!==void 0?w.location.columnNumber+1:void 0,originalLocation:H,exception:D,domChange:b,callStack:W,asyncStackTrace:G,logResult:U,watchResults:_,captureTimeMs:Date.now()-i};n.snapshots.push(oe),n.snapshots.length>n.config.maxSnapshots&&n.snapshots.splice(0,n.snapshots.length-n.config.maxSnapshots)}}finally{await n.v8Api.resume()}}),n.enabled=!0,n.sourceMapResolver.loadAllSourceMaps().then(()=>{n.sourceMapsLoaded=!0}).catch(()=>{})}}s(Ue,"enableDebugging");function N(o){return ge(o)?.enabled??!1}s(N,"isDebuggingEnabled");async function Ai(o,e,t,n,r=1){let i=Bi(o,e);i.enabled||await Ue(o,e);let a=await i.sourceMapResolver.resolveLocationByUrl(t,n,r);return a?{source:a.source,line:a.line+1,column:a.column+1,name:a.name}:null}s(Ai,"resolveSourceLocation");async function Li(o,e){let t=ge(o);if(!t||!t.enabled)throw new Error("Debugging is not enabled");await t.v8Api.setPauseOnExceptions(e),t.exceptionBreakpoint=e}s(Li,"setExceptionBreakpoint");function fn(o){return ge(o)?.exceptionBreakpoint??"none"}s(fn,"getExceptionBreakpoint");function Fi(o){return ge(o)?.sourceMapResolver.hasSourceMaps()??!1}s(Fi,"hasSourceMaps");async function Kn(o,e){let t=ge(o);if(!t||!t.enabled)throw new Error("Debugging is not enabled");let n=Ft(),r;e.condition?r=`(${e.condition})`:r="true";let i=e.lineNumber-1,a=(e.columnNumber??1)-1,l=t.sourceMapResolver.originalToGenerated(e.urlPattern,i,a),u,m=0;if(l)u=(await t.v8Api.setBreakpoint({scriptId:l.scriptId,lineNumber:l.location.line,columnNumber:l.location.column},r)).breakpointId,m=1;else{let b=e.urlPattern.replace(/\\([.*+?^${}()|[\]\\/-])/g,"$1").replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*").replace(/\\\?/g,"."),f=await t.v8Api.setBreakpointByUrl({urlRegex:b,lineNumber:e.lineNumber-1,columnNumber:e.columnNumber?e.columnNumber-1:void 0,condition:r});u=f.breakpointId,m=f.locations.length}let c={id:n,kind:e.kind,enabled:!0,urlPattern:e.urlPattern,lineNumber:e.lineNumber,columnNumber:e.columnNumber,condition:e.condition,logExpression:e.logExpression,hitCondition:e.hitCondition,v8BreakpointIds:[u],resolvedLocations:m,hitCount:0,createdAt:Date.now()};return t.probes.set(n,c),c}s(Kn,"createProbe");async function St(o,e){let t=ge(o);if(!t)return!1;let n=t.probes.get(e);if(!n)return!1;for(let r of n.v8BreakpointIds)try{await t.v8Api.removeBreakpoint(r)}catch{}return t.probes.delete(e),!0}s(St,"removeProbe");function ve(o){let e=ge(o);return e?Array.from(e.probes.values()):[]}s(ve,"listProbes");function Xn(o,e){let t=ge(o);if(t)return t.probes.get(e)}s(Xn,"getProbe");function xt(o){let e=ge(o);return e?[...e.snapshots]:[]}s(xt,"getSnapshots");function it(o,e){let t=ge(o);return t?t.snapshots.filter(n=>n.probeId===e):[]}s(it,"getSnapshotsByProbe");function De(o,e){let t=ge(o);if(!t)return 0;let n=t.snapshots.length;return t.snapshots=t.snapshots.filter(r=>r.probeId!==e),n-t.snapshots.length}s(De,"clearSnapshotsByProbe");function Ui(o){let e=ge(o);if(!e||e.snapshots.length===0)return{totalSnapshots:0,snapshotsByProbe:{},averageCaptureTimeMs:0};let t={},n=0;for(let r of e.snapshots)t[r.probeId]=(t[r.probeId]||0)+1,n+=r.captureTimeMs;return{totalSnapshots:e.snapshots.length,snapshotsByProbe:t,oldestTimestamp:e.snapshots[0].timestamp,newestTimestamp:e.snapshots[e.snapshots.length-1].timestamp,averageCaptureTimeMs:n/e.snapshots.length}}s(Ui,"getSnapshotStats");function Hi(o,e){let t=ge(o);if(!t)throw new Error("Debug store not initialized");let n=Ft(),r={id:n,expression:e,createdAt:Date.now()};return t.watchExpressions.set(n,r),r}s(Hi,"addWatchExpression");function Wi(o,e){let t=ge(o);return t?t.watchExpressions.delete(e):!1}s(Wi,"removeWatchExpression");function Yn(o){let e=ge(o);return e?Array.from(e.watchExpressions.values()):[]}s(Yn,"listWatchExpressions");function qi(o){let e=ge(o);if(!e)return 0;let t=e.watchExpressions.size;return e.watchExpressions.clear(),t}s(qi,"clearWatchExpressions");async function $i(o,e,t){let n=ge(o);if(!n||!n.enabled)throw new Error("Debugging is not enabled");let r=await n.v8Api.getCdp();await r.send("DOM.enable");let{root:i}=await r.send("DOM.getDocument",{depth:0}),{nodeId:a}=await r.send("DOM.querySelector",{nodeId:i.nodeId,selector:t.selector});if(!a||a===0)throw new Error(`Element not found: ${t.selector}`);let l=t.type==="subtree-modified"?"subtree-modified":t.type==="attribute-modified"?"attribute-modified":"node-removed";await r.send("DOMDebugger.setDOMBreakpoint",{nodeId:a,type:l});let u=Ft(),m={id:u,selector:t.selector,type:t.type,attributeName:t.attributeName,enabled:!0,nodeId:a,hitCount:0,createdAt:Date.now()};return n.domBreakpoints.set(u,m),await e.evaluate(c=>{let p=c.selector,b=c.breakpointId,f=c.type,x=c.attrName,B=c.maxMutations,w=c.maxHtmlSnippetLength,U=document.querySelector(p);if(!U)return;let D=window;D.__domBreakpointData=D.__domBreakpointData||{},D.__domBreakpointMutations=D.__domBreakpointMutations||[],D.__domBreakpointData[b]={selector:p,type:f,attrName:x,currentAttrs:{}};for(let $ of U.attributes)D.__domBreakpointData[b].currentAttrs[$.name]=$.value;let H=new MutationObserver($=>{for(let P of $){let W=P.target;if(P.type==="attributes"){let G=P.attributeName||"";if(x&&x!==G)continue;let _={breakpointId:b,selector:p,type:"attribute-modified",attributeName:G,oldValue:P.oldValue,newValue:W.getAttribute(G),targetOuterHTML:W.outerHTML.substring(0,w),timestamp:Date.now()};D.__domBreakpointMutations.push(_),D.__domBreakpointMutations.length>B&&D.__domBreakpointMutations.shift(),D.__domBreakpointData[b].currentAttrs[G]=W.getAttribute(G)}else if(P.type==="childList"){let G={breakpointId:b,selector:p,type:"subtree-modified",addedNodes:P.addedNodes.length,removedNodes:P.removedNodes.length,targetOuterHTML:W.outerHTML.substring(0,w),timestamp:Date.now()};D.__domBreakpointMutations.push(G),D.__domBreakpointMutations.length>B&&D.__domBreakpointMutations.shift()}}}),Q={attributes:f==="attribute-modified",attributeOldValue:f==="attribute-modified",childList:f==="subtree-modified"||f==="node-removed",subtree:f==="subtree-modified"};x&&(Q.attributeFilter=[x]),H.observe(U,Q),D.__domBreakpointObservers=D.__domBreakpointObservers||{},D.__domBreakpointObservers[b]=H},{selector:t.selector,breakpointId:u,type:t.type,attrName:t.attributeName,maxMutations:n.config.maxDOMMutations,maxHtmlSnippetLength:n.config.maxDOMHtmlSnippetLength}),m}s($i,"setDOMBreakpoint");async function ms(o,e,t){let n=ge(o);if(!n)return!1;let r=n.domBreakpoints.get(e);if(!r||!r.nodeId)return!1;try{let i=await n.v8Api.getCdp(),a=r.type==="subtree-modified"?"subtree-modified":r.type==="attribute-modified"?"attribute-modified":"node-removed";await i.send("DOMDebugger.removeDOMBreakpoint",{nodeId:r.nodeId,type:a})}catch{}if(t)try{await t.evaluate(i=>{let a=window;a.__domBreakpointObservers&&a.__domBreakpointObservers[i]&&(a.__domBreakpointObservers[i].disconnect(),delete a.__domBreakpointObservers[i]),a.__domBreakpointData&&delete a.__domBreakpointData[i],a.__domBreakpointMutations&&(a.__domBreakpointMutations=a.__domBreakpointMutations.filter(l=>l.breakpointId!==i))},e)}catch{}return n.domBreakpoints.delete(e)}s(ms,"removeDOMBreakpoint");function vt(o){let e=ge(o);return e?Array.from(e.domBreakpoints.values()):[]}s(vt,"listDOMBreakpoints");async function ji(o,e){let t=ge(o);if(!t)return 0;let n=Array.from(t.domBreakpoints.keys());for(let r of n)await ms(o,r,e);return n.length}s(ji,"clearDOMBreakpoints");async function Yl(o,e){if(o.networkInterceptionEnabled)return;let t=await o.v8Api.getCdp();await t.send("Fetch.enable",{patterns:[{urlPattern:"*",requestStage:"Request"}]}),t.on("Fetch.requestPaused",async r=>{let i=r.requestId,a=r.request.url,l=r.request.method;try{let u;for(let m of o.networkBreakpoints.values()){if(!m.enabled)continue;let c=m.urlPattern.replace(/\\([.*+?^${}()|[\]\\/-])/g,"$1");if(new RegExp(c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")).test(a)&&!(m.method&&m.method.toUpperCase()!==l.toUpperCase())&&m.timing==="request"){u=m;break}}if(u&&u.timing==="request"){let m={url:a,method:l,requestHeaders:r.request.headers,requestBody:r.request.postData,resourceType:r.resourceType,timing:"request"},c={id:Ft(),probeId:u.id,timestamp:Date.now(),sequenceNumber:++o.snapshotSequence,url:a,lineNumber:0,networkRequest:m,callStack:[],captureTimeMs:0};o.watchExpressions.size>0&&(c.watchResults=await Di(o,e)),o.snapshots.push(c),o.snapshots.length>o.config.maxSnapshots&&o.snapshots.splice(0,o.snapshots.length-o.config.maxSnapshots),u.hitCount++,u.lastHitAt=Date.now()}await t.send("Fetch.continueRequest",{requestId:i})}catch{try{await t.send("Fetch.continueRequest",{requestId:i})}catch{}}}),await t.send("Network.enable");let n=new Map;t.on("Network.requestWillBeSent",r=>{if(n.set(r.requestId,{method:r.request.method,postData:r.request.postData}),n.size>o.config.maxPendingRequests){let i=n.keys().next().value;i&&n.delete(i)}}),t.on("Network.responseReceived",async r=>{let i=r.requestId,a=r.response.url,l=n.get(i),u=l?.method||r.type||"GET",m=r.response.status;for(let c of o.networkBreakpoints.values()){if(!c.enabled||c.timing!=="response")continue;let p=c.urlPattern.replace(/\\([.*+?^${}()|[\]\\/-])/g,"$1");if(!new RegExp(p.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/\\\*/g,".*")).test(a)||c.method&&c.method.toUpperCase()!==u.toUpperCase()||c.onError&&m<400)continue;let f;try{let w=await t.send("Network.getResponseBody",{requestId:i});w.base64Encoded?f=Buffer.from(w.body,"base64").toString("utf-8"):f=w.body,f&&f.length>o.config.maxResponseBodyLength&&(f=f.substring(0,o.config.maxResponseBodyLength)+"... [truncated]")}catch{}let x={url:a,method:u,requestBody:l?.postData,status:m,statusText:r.response.statusText,responseHeaders:r.response.headers,responseBody:f,resourceType:r.type,timing:"response"},B={id:Ft(),probeId:c.id,timestamp:Date.now(),sequenceNumber:++o.snapshotSequence,url:a,lineNumber:0,networkRequest:x,callStack:[],captureTimeMs:0};o.watchExpressions.size>0&&(B.watchResults=await Di(o,e)),o.snapshots.push(B),o.snapshots.length>o.config.maxSnapshots&&o.snapshots.splice(0,o.snapshots.length-o.config.maxSnapshots),c.hitCount++,c.lastHitAt=Date.now(),n.delete(i);break}}),t.on("Network.loadingFinished",r=>{setTimeout(()=>{n.delete(r.requestId)},o.config.networkCleanupTimeoutMs)}),o.networkInterceptionEnabled=!0}s(Yl,"_enableNetworkInterception");async function Di(o,e){let t={};for(let n of o.watchExpressions.values())try{let r=await e.evaluate(i=>{try{return(0,eval)(i)}catch(a){return`[Error: ${a.message}]`}},n.expression);t[n.expression]=r}catch(r){t[n.expression]=`[Error: ${r.message}]`}return t}s(Di,"_evaluateWatchExpressions");async function zi(o,e,t){let n=ge(o);if(!n||!n.enabled)throw new Error("Debugging is not enabled");await Yl(n,e);let r=Ft(),i={id:r,urlPattern:t.urlPattern,method:t.method,timing:t.timing||"request",onError:t.onError,enabled:!0,hitCount:0,createdAt:Date.now()};return n.networkBreakpoints.set(r,i),i}s(zi,"setNetworkBreakpoint");function Vi(o,e){let t=ge(o);return t?t.networkBreakpoints.delete(e):!1}s(Vi,"removeNetworkBreakpoint");function It(o){let e=ge(o);return e?Array.from(e.networkBreakpoints.values()):[]}s(It,"listNetworkBreakpoints");function Gi(o){let e=ge(o);if(!e)return 0;let t=e.networkBreakpoints.size;return e.networkBreakpoints.clear(),t}s(Gi,"clearNetworkBreakpoints");var Jn=class{static{s(this,"Status")}name(){return"debug_status"}description(){return`
273
273
  Returns the current debugging status including:
274
274
  - Whether debugging is enabled
275
275
  - Source map status
276
276
  - Exceptionpoint state
277
277
  - Count of tracepoints, logpoints, watches, dompoints and netpoints
278
278
  - Snapshot statistics
279
- `}inputSchema(){return{}}outputSchema(){return{enabled:Re.boolean().describe("Whether debugging is enabled"),hasSourceMaps:Re.boolean().describe("Whether source maps are loaded"),exceptionBreakpoint:Re.string().describe("Exceptionpoint state (none, uncaught, all)"),tracepointCount:Re.number().describe("Number of tracepoints"),logpointCount:Re.number().describe("Number of logpoints"),watchExpressionCount:Re.number().describe("Number of watch expressions"),dompointCount:Re.number().describe("Number of dompoints"),netpointCount:Re.number().describe("Number of netpoints"),snapshotStats:Re.object({totalSnapshots:Re.number(),snapshotsByProbe:Re.record(Re.number()),oldestTimestamp:Re.number().optional(),newestTimestamp:Re.number().optional(),averageCaptureTimeMs:Re.number()}).nullable().describe("Snapshot statistics")}}async handle(e,t){if(!N(e.browserContext))return{enabled:!1,hasSourceMaps:!1,exceptionBreakpoint:"none",tracepointCount:0,logpointCount:0,watchExpressionCount:0,dompointCount:0,netpointCount:0,snapshotStats:null};let r=ve(e.browserContext),i=r.filter(l=>l.kind==="tracepoint").length,a=r.filter(l=>l.kind==="logpoint").length;return{enabled:!0,hasSourceMaps:Fi(e.browserContext),exceptionBreakpoint:fn(e.browserContext),tracepointCount:i,logpointCount:a,watchExpressionCount:Yn(e.browserContext).length,dompointCount:vt(e.browserContext).length,netpointCount:It(e.browserContext).length,snapshotStats:Ui(e.browserContext)}}};import{z as Ct}from"zod";var Qn=class{static{s(this,"ResolveSourceLocation")}name(){return"debug_resolve-source-location"}description(){return`
279
+ `}inputSchema(){return{}}outputSchema(){return{enabled:ke.boolean().describe("Whether debugging is enabled"),hasSourceMaps:ke.boolean().describe("Whether source maps are loaded"),exceptionBreakpoint:ke.string().describe("Exceptionpoint state (none, uncaught, all)"),tracepointCount:ke.number().describe("Number of tracepoints"),logpointCount:ke.number().describe("Number of logpoints"),watchExpressionCount:ke.number().describe("Number of watch expressions"),dompointCount:ke.number().describe("Number of dompoints"),netpointCount:ke.number().describe("Number of netpoints"),snapshotStats:ke.object({totalSnapshots:ke.number(),snapshotsByProbe:ke.record(ke.number()),oldestTimestamp:ke.number().optional(),newestTimestamp:ke.number().optional(),averageCaptureTimeMs:ke.number()}).nullable().describe("Snapshot statistics")}}async handle(e,t){if(!N(e.browserContext))return{enabled:!1,hasSourceMaps:!1,exceptionBreakpoint:"none",tracepointCount:0,logpointCount:0,watchExpressionCount:0,dompointCount:0,netpointCount:0,snapshotStats:null};let r=ve(e.browserContext),i=r.filter(l=>l.kind==="tracepoint").length,a=r.filter(l=>l.kind==="logpoint").length;return{enabled:!0,hasSourceMaps:Fi(e.browserContext),exceptionBreakpoint:fn(e.browserContext),tracepointCount:i,logpointCount:a,watchExpressionCount:Yn(e.browserContext).length,dompointCount:vt(e.browserContext).length,netpointCount:It(e.browserContext).length,snapshotStats:Ui(e.browserContext)}}};import{z as Ct}from"zod";var Qn=class{static{s(this,"ResolveSourceLocation")}name(){return"debug_resolve-source-location"}description(){return`
280
280
  Resolves a generated/bundled code location to its original source via source maps.
281
281
  Useful for translating minified stack traces or bundle line numbers to original TypeScript/JavaScript source.
282
282
 
@@ -394,7 +394,7 @@ When triggered, a snapshot is captured with DOM change info.
394
394
  Example:
395
395
  - selector: "#myButton", type: "attribute-modified", attributeName: "disabled"
396
396
  - selector: ".list-container", type: "subtree-modified"
397
- `}inputSchema(){return{selector:ht.string().describe("CSS selector for the target element"),type:ht.enum(["subtree-modified","attribute-modified","node-removed"]).describe("Type of DOM change to monitor"),attributeName:ht.string().describe("For attribute-modified: specific attribute to monitor").optional()}}outputSchema(){return{id:ht.string().describe("Dompoint ID"),selector:ht.string().describe("CSS selector"),type:ht.string().describe("Dompoint type"),attributeName:ht.string().optional().describe("Monitored attribute"),nodeId:ht.number().optional().describe("CDP node ID"),message:ht.string().describe("Status message")}}async handle(e,t){N(e.browserContext)||await Ue(e.browserContext,e.page);let n=await $i(e.browserContext,e.page,{selector:t.selector,type:t.type,attributeName:t.attributeName});return{id:n.id,selector:n.selector,type:n.type,attributeName:n.attributeName,nodeId:n.nodeId,message:`Dompoint set on "${t.selector}" for ${t.type}`}}};import{z as xs}from"zod";var Oo=class{static{s(this,"RemoveDompoint")}name(){return"debug_remove-dompoint"}description(){return"Removes a dompoint by its ID."}inputSchema(){return{id:xs.string().describe("Dompoint ID to remove")}}outputSchema(){return{success:xs.boolean().describe("Whether the dompoint was removed"),message:xs.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{success:!1,message:"No active dompoints"};let n=await ms(e.browserContext,t.id,e.page);return{success:n,message:n?`Dompoint ${t.id} removed`:`Dompoint ${t.id} not found`}}};import{z as at}from"zod";var No=class{static{s(this,"ListDompoints")}name(){return"debug_list-dompoints"}description(){return"Lists all active dompoints."}inputSchema(){return{}}outputSchema(){return{dompoints:at.array(at.object({id:at.string(),selector:at.string(),type:at.string(),attributeName:at.string().optional(),enabled:at.boolean(),hitCount:at.number(),lastHitAt:at.number().optional()})).describe("List of dompoints"),total:at.number().describe("Total count")}}async handle(e,t){if(!N(e.browserContext))return{dompoints:[],total:0};let r=vt(e.browserContext).map(i=>({id:i.id,selector:i.selector,type:i.type,attributeName:i.attributeName,enabled:i.enabled,hitCount:i.hitCount,lastHitAt:i.lastHitAt}));return{dompoints:r,total:r.length}}};import{z as oa}from"zod";var Po=class{static{s(this,"ClearDompoints")}name(){return"debug_clear-dompoints"}description(){return"Removes all dompoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:oa.number().describe("Number of dompoints cleared"),message:oa.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No dompoints to clear"};let n=await ji(e.browserContext,e.page);return{clearedCount:n,message:`Cleared ${n} dompoint(s)`}}};import{z as lt}from"zod";var Ro=class{static{s(this,"PutNetpoint")}name(){return"debug_put-netpoint"}description(){return`
397
+ `}inputSchema(){return{selector:ht.string().describe("CSS selector for the target element"),type:ht.enum(["subtree-modified","attribute-modified","node-removed"]).describe("Type of DOM change to monitor"),attributeName:ht.string().describe("For attribute-modified: specific attribute to monitor").optional()}}outputSchema(){return{id:ht.string().describe("Dompoint ID"),selector:ht.string().describe("CSS selector"),type:ht.string().describe("Dompoint type"),attributeName:ht.string().optional().describe("Monitored attribute"),nodeId:ht.number().optional().describe("CDP node ID"),message:ht.string().describe("Status message")}}async handle(e,t){N(e.browserContext)||await Ue(e.browserContext,e.page);let n=await $i(e.browserContext,e.page,{selector:t.selector,type:t.type,attributeName:t.attributeName});return{id:n.id,selector:n.selector,type:n.type,attributeName:n.attributeName,nodeId:n.nodeId,message:`Dompoint set on "${t.selector}" for ${t.type}`}}};import{z as xs}from"zod";var Oo=class{static{s(this,"RemoveDompoint")}name(){return"debug_remove-dompoint"}description(){return"Removes a dompoint by its ID."}inputSchema(){return{id:xs.string().describe("Dompoint ID to remove")}}outputSchema(){return{success:xs.boolean().describe("Whether the dompoint was removed"),message:xs.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{success:!1,message:"No active dompoints"};let n=await ms(e.browserContext,t.id,e.page);return{success:n,message:n?`Dompoint ${t.id} removed`:`Dompoint ${t.id} not found`}}};import{z as at}from"zod";var No=class{static{s(this,"ListDompoints")}name(){return"debug_list-dompoints"}description(){return"Lists all active dompoints."}inputSchema(){return{}}outputSchema(){return{dompoints:at.array(at.object({id:at.string(),selector:at.string(),type:at.string(),attributeName:at.string().optional(),enabled:at.boolean(),hitCount:at.number(),lastHitAt:at.number().optional()})).describe("List of dompoints"),total:at.number().describe("Total count")}}async handle(e,t){if(!N(e.browserContext))return{dompoints:[],total:0};let r=vt(e.browserContext).map(i=>({id:i.id,selector:i.selector,type:i.type,attributeName:i.attributeName,enabled:i.enabled,hitCount:i.hitCount,lastHitAt:i.lastHitAt}));return{dompoints:r,total:r.length}}};import{z as oa}from"zod";var Po=class{static{s(this,"ClearDompoints")}name(){return"debug_clear-dompoints"}description(){return"Removes all dompoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:oa.number().describe("Number of dompoints cleared"),message:oa.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No dompoints to clear"};let n=await ji(e.browserContext,e.page);return{clearedCount:n,message:`Cleared ${n} dompoint(s)`}}};import{z as lt}from"zod";var ko=class{static{s(this,"PutNetpoint")}name(){return"debug_put-netpoint"}description(){return`
398
398
  Puts a network tracepoint that triggers on matching HTTP requests.
399
399
 
400
400
  When triggered, a snapshot is captured with request/response details including:
@@ -411,7 +411,7 @@ Parameters:
411
411
  Examples:
412
412
  - urlPattern: "**/api/users/**", timing: "response"
413
413
  - urlPattern: "**/graphql", method: "POST", timing: "request"
414
- `}inputSchema(){return{urlPattern:lt.string().describe("Glob pattern to match request URLs"),method:lt.string().describe("HTTP method filter (GET, POST, PUT, DELETE, etc.)").optional(),timing:lt.enum(["request","response"]).describe('When to trigger: "request" or "response". Default: "request"').optional().default("request"),onError:lt.boolean().describe("Only trigger on error responses (4xx, 5xx)").optional()}}outputSchema(){return{id:lt.string().describe("Netpoint ID"),urlPattern:lt.string().describe("URL pattern"),method:lt.string().optional().describe("HTTP method filter"),timing:lt.string().describe("Trigger timing"),onError:lt.boolean().optional().describe("Error-only filter"),message:lt.string().describe("Status message")}}async handle(e,t){N(e.browserContext)||await Ue(e.browserContext,e.page);let n=await zi(e.browserContext,e.page,{urlPattern:t.urlPattern,method:t.method,timing:t.timing||"request",onError:t.onError});return{id:n.id,urlPattern:n.urlPattern,method:n.method,timing:n.timing,onError:n.onError,message:`Netpoint set for ${t.urlPattern} on ${t.timing||"request"}`}}};import{z as vs}from"zod";var ko=class{static{s(this,"RemoveNetpoint")}name(){return"debug_remove-netpoint"}description(){return"Removes a netpoint by its ID."}inputSchema(){return{id:vs.string().describe("Netpoint ID to remove")}}outputSchema(){return{success:vs.boolean().describe("Whether the netpoint was removed"),message:vs.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{success:!1,message:"No active netpoints"};let n=Vi(e.browserContext,t.id);return{success:n,message:n?`Netpoint ${t.id} removed`:`Netpoint ${t.id} not found`}}};import{z as Ye}from"zod";var _o=class{static{s(this,"ListNetpoints")}name(){return"debug_list-netpoints"}description(){return"Lists all active netpoints."}inputSchema(){return{}}outputSchema(){return{netpoints:Ye.array(Ye.object({id:Ye.string(),urlPattern:Ye.string(),method:Ye.string().optional(),timing:Ye.string(),onError:Ye.boolean().optional(),enabled:Ye.boolean(),hitCount:Ye.number(),lastHitAt:Ye.number().optional()})).describe("List of netpoints"),total:Ye.number().describe("Total count")}}async handle(e,t){if(!N(e.browserContext))return{netpoints:[],total:0};let r=It(e.browserContext).map(i=>({id:i.id,urlPattern:i.urlPattern,method:i.method,timing:i.timing,onError:i.onError,enabled:i.enabled,hitCount:i.hitCount,lastHitAt:i.lastHitAt}));return{netpoints:r,total:r.length}}};import{z as ra}from"zod";var Mo=class{static{s(this,"ClearNetpoints")}name(){return"debug_clear-netpoints"}description(){return"Removes all netpoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:ra.number().describe("Number of netpoints cleared"),message:ra.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No netpoints to clear"};let n=Gi(e.browserContext);return{clearedCount:n,message:`Cleared ${n} netpoint(s)`}}};var sa=[new Jn,new Qn,new Zn,new eo,new to,new no,new oo,new ro,new so,new io,new lo,new uo,new co,new mo,new po,new ho,new go,new fo,new yo,new wo,new To,new xo,new vo,new Io,new Co,new Eo,new Oo,new No,new Po,new Ro,new ko,new _o,new Mo];import Is from"sharp";import ru from"ssim.js";var su=!1,iu=10;function au(o){return Number.isFinite(o)?Math.max(0,Math.min(1,o)):0}s(au,"_clamp01");async function ia(o,e,t,n){let r;if(n==="semantic"){r=Is(o).resize(e,t,{fit:"cover",position:"centre"});let l=Math.max(1,Math.floor(e/2)),u=Math.max(1,Math.floor(t/2));r=r.resize(l,u,{fit:"cover",position:"centre"}).grayscale(su).blur(iu)}else r=Is(o).resize(e,t,{fit:"cover",position:"centre"});let i=await r.ensureAlpha().raw().toBuffer({resolveWithObject:!0});return{data:new Uint8ClampedArray(i.data.buffer,i.data.byteOffset,i.data.byteLength),width:i.info.width,height:i.info.height}}s(ia,"_loadNormalized");function lu(o,e){let t=ru({data:o.data,width:o.width,height:o.height},{data:e.data,width:e.width,height:e.height}),n=Number(t.mssim??t.ssim??0);return au(n)}s(lu,"_computeSsim");async function aa(o,e,t){let n=t?.mode??"semantic",r=t?.canvasWidth,i=t?.canvasHeight;if(typeof r!="number"||!Number.isFinite(r)||r<=0||typeof i!="number"||!Number.isFinite(i)||i<=0){let m=await Is(e.image).metadata();if(r=m.width??0,i=m.height??0,r<=0||i<=0)throw new Error("Failed to read Figma image dimensions.")}let a=await ia(e.image,r,i,n),l=await ia(o.image,r,i,n);return{score:lu(a,l)}}s(aa,"compare");function la(o,e){let t=Math.min(o.length,e.length),n=0;for(let r=0;r<t;r++)n+=o[r]*e[r];return n}s(la,"dot");function Cs(o){let e=0;for(let t=0;t<o.length;t++){let n=o[t];e+=n*n}return Math.sqrt(e)}s(Cs,"norm");function ua(o){let e=Cs(o);if(e===0)return o.slice();let t=new Array(o.length);for(let n=0;n<o.length;n++)t[n]=o[n]/e;return t}s(ua,"l2Normalize");function Do(o,e,t){if(t){let r=ua(o),i=ua(e);return la(r,i)}let n=Cs(o)*Cs(e);return n===0?0:la(o,e)/n}s(Do,"cosineSimilarity");import{BedrockRuntimeClient as ca,InvokeModelCommand as uu}from"@aws-sdk/client-bedrock-runtime";import{fromIni as cu}from"@aws-sdk/credential-providers";import mu from"sharp";var pu=1024,du=90,bu=1024;async function hu(o,e,t){let n=mu(o),r=t?.maxDim||pu;if(n=n.resize({width:r,height:r,fit:"inside",withoutEnlargement:!0}),e==="png")return await n.png().toBuffer();let i=t?.jpegQuality||du;return await n.jpeg({quality:i}).toBuffer()}s(hu,"_prepareImage");var gu=new Set(["amazon.titan-embed-image-v1"]),fu="amazon.titan-embed-image-v1",Zt;function yu(){return Mn&&!!Xt}s(yu,"_isAwsBedrockActive");function wu(){if(Zt)return Zt;let o=Xt;if(!o)return;let e=_n;return e?(Zt=new ca({region:o,credentials:cu({profile:e})}),Zt):(Zt=new ca({region:o}),Zt)}s(wu,"_getOrCreateBedrockClient");async function Tu(o,e,t,n){let i={inputImage:(await hu(o.image,o.type,t)).toString("base64"),embeddingConfig:{outputEmbeddingLength:bu}},a=new uu({modelId:n,contentType:"application/json",accept:"application/json",body:Buffer.from(JSON.stringify(i),"utf-8")}),l=await e.send(a),u=l?.body instanceof Uint8Array?l.body:new Uint8Array(l?.body??[]),m=Buffer.from(u).toString("utf-8"),c;try{c=m?JSON.parse(m):{}}catch{throw new Error(`Amazon Bedrock Titan returned non-JSON response for embeddings: ${m.slice(0,300)}`)}let p=c?.embedding??c?.embeddings?.[0]??c?.outputEmbedding??c?.vector;if(!Array.isArray(p)||p.length===0||typeof p[0]!="number")throw new Error(`Unexpected Amazon Bedrock Titan image embedding response format: ${m.slice(0,500)}`);return p}s(Tu,"_embedImageWithAmazonBedrockTitan");async function Su(o,e,t){let n=e?.modelId??Js??fu;if(!gu.has(n))throw new Error(`Unsupported Amazon Bedrock image embedding model id: ${n}`);return await Tu(o,t,e,n)}s(Su,"_embedImageWithAmazonBedrock");async function ma(o,e){if(yu()){let t=wu();return t?Su(o,e,t):void 0}}s(ma,"_embedImage");async function pa(o,e,t){let n=typeof t?.normalize=="boolean"?t.normalize:!0,r=await ma(e,t);if(!r)return;let i=await ma(o,t);return i?{score:Do(r,i,n)}:void 0}s(pa,"compare");import{BedrockRuntimeClient as da,InvokeModelCommand as xu}from"@aws-sdk/client-bedrock-runtime";import{fromIni as vu}from"@aws-sdk/credential-providers";import Iu from"sharp";var Cu=`
414
+ `}inputSchema(){return{urlPattern:lt.string().describe("Glob pattern to match request URLs"),method:lt.string().describe("HTTP method filter (GET, POST, PUT, DELETE, etc.)").optional(),timing:lt.enum(["request","response"]).describe('When to trigger: "request" or "response". Default: "request"').optional().default("request"),onError:lt.boolean().describe("Only trigger on error responses (4xx, 5xx)").optional()}}outputSchema(){return{id:lt.string().describe("Netpoint ID"),urlPattern:lt.string().describe("URL pattern"),method:lt.string().optional().describe("HTTP method filter"),timing:lt.string().describe("Trigger timing"),onError:lt.boolean().optional().describe("Error-only filter"),message:lt.string().describe("Status message")}}async handle(e,t){N(e.browserContext)||await Ue(e.browserContext,e.page);let n=await zi(e.browserContext,e.page,{urlPattern:t.urlPattern,method:t.method,timing:t.timing||"request",onError:t.onError});return{id:n.id,urlPattern:n.urlPattern,method:n.method,timing:n.timing,onError:n.onError,message:`Netpoint set for ${t.urlPattern} on ${t.timing||"request"}`}}};import{z as vs}from"zod";var Ro=class{static{s(this,"RemoveNetpoint")}name(){return"debug_remove-netpoint"}description(){return"Removes a netpoint by its ID."}inputSchema(){return{id:vs.string().describe("Netpoint ID to remove")}}outputSchema(){return{success:vs.boolean().describe("Whether the netpoint was removed"),message:vs.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{success:!1,message:"No active netpoints"};let n=Vi(e.browserContext,t.id);return{success:n,message:n?`Netpoint ${t.id} removed`:`Netpoint ${t.id} not found`}}};import{z as Ye}from"zod";var _o=class{static{s(this,"ListNetpoints")}name(){return"debug_list-netpoints"}description(){return"Lists all active netpoints."}inputSchema(){return{}}outputSchema(){return{netpoints:Ye.array(Ye.object({id:Ye.string(),urlPattern:Ye.string(),method:Ye.string().optional(),timing:Ye.string(),onError:Ye.boolean().optional(),enabled:Ye.boolean(),hitCount:Ye.number(),lastHitAt:Ye.number().optional()})).describe("List of netpoints"),total:Ye.number().describe("Total count")}}async handle(e,t){if(!N(e.browserContext))return{netpoints:[],total:0};let r=It(e.browserContext).map(i=>({id:i.id,urlPattern:i.urlPattern,method:i.method,timing:i.timing,onError:i.onError,enabled:i.enabled,hitCount:i.hitCount,lastHitAt:i.lastHitAt}));return{netpoints:r,total:r.length}}};import{z as ra}from"zod";var Mo=class{static{s(this,"ClearNetpoints")}name(){return"debug_clear-netpoints"}description(){return"Removes all netpoints."}inputSchema(){return{}}outputSchema(){return{clearedCount:ra.number().describe("Number of netpoints cleared"),message:ra.string().describe("Status message")}}async handle(e,t){if(!N(e.browserContext))return{clearedCount:0,message:"No netpoints to clear"};let n=Gi(e.browserContext);return{clearedCount:n,message:`Cleared ${n} netpoint(s)`}}};var sa=[new Jn,new Qn,new Zn,new eo,new to,new no,new oo,new ro,new so,new io,new lo,new uo,new co,new mo,new po,new ho,new go,new fo,new yo,new wo,new To,new xo,new vo,new Io,new Co,new Eo,new Oo,new No,new Po,new ko,new Ro,new _o,new Mo];import Is from"sharp";import ru from"ssim.js";var su=!1,iu=10;function au(o){return Number.isFinite(o)?Math.max(0,Math.min(1,o)):0}s(au,"_clamp01");async function ia(o,e,t,n){let r;if(n==="semantic"){r=Is(o).resize(e,t,{fit:"cover",position:"centre"});let l=Math.max(1,Math.floor(e/2)),u=Math.max(1,Math.floor(t/2));r=r.resize(l,u,{fit:"cover",position:"centre"}).grayscale(su).blur(iu)}else r=Is(o).resize(e,t,{fit:"cover",position:"centre"});let i=await r.ensureAlpha().raw().toBuffer({resolveWithObject:!0});return{data:new Uint8ClampedArray(i.data.buffer,i.data.byteOffset,i.data.byteLength),width:i.info.width,height:i.info.height}}s(ia,"_loadNormalized");function lu(o,e){let t=ru({data:o.data,width:o.width,height:o.height},{data:e.data,width:e.width,height:e.height}),n=Number(t.mssim??t.ssim??0);return au(n)}s(lu,"_computeSsim");async function aa(o,e,t){let n=t?.mode??"semantic",r=t?.canvasWidth,i=t?.canvasHeight;if(typeof r!="number"||!Number.isFinite(r)||r<=0||typeof i!="number"||!Number.isFinite(i)||i<=0){let m=await Is(e.image).metadata();if(r=m.width??0,i=m.height??0,r<=0||i<=0)throw new Error("Failed to read Figma image dimensions.")}let a=await ia(e.image,r,i,n),l=await ia(o.image,r,i,n);return{score:lu(a,l)}}s(aa,"compare");function la(o,e){let t=Math.min(o.length,e.length),n=0;for(let r=0;r<t;r++)n+=o[r]*e[r];return n}s(la,"dot");function Cs(o){let e=0;for(let t=0;t<o.length;t++){let n=o[t];e+=n*n}return Math.sqrt(e)}s(Cs,"norm");function ua(o){let e=Cs(o);if(e===0)return o.slice();let t=new Array(o.length);for(let n=0;n<o.length;n++)t[n]=o[n]/e;return t}s(ua,"l2Normalize");function Do(o,e,t){if(t){let r=ua(o),i=ua(e);return la(r,i)}let n=Cs(o)*Cs(e);return n===0?0:la(o,e)/n}s(Do,"cosineSimilarity");import{BedrockRuntimeClient as ca,InvokeModelCommand as uu}from"@aws-sdk/client-bedrock-runtime";import{fromIni as cu}from"@aws-sdk/credential-providers";import mu from"sharp";var pu=1024,du=90,bu=1024;async function hu(o,e,t){let n=mu(o),r=t?.maxDim||pu;if(n=n.resize({width:r,height:r,fit:"inside",withoutEnlargement:!0}),e==="png")return await n.png().toBuffer();let i=t?.jpegQuality||du;return await n.jpeg({quality:i}).toBuffer()}s(hu,"_prepareImage");var gu=new Set(["amazon.titan-embed-image-v1"]),fu="amazon.titan-embed-image-v1",Zt;function yu(){return Mn&&!!Xt}s(yu,"_isAwsBedrockActive");function wu(){if(Zt)return Zt;let o=Xt;if(!o)return;let e=_n;return e?(Zt=new ca({region:o,credentials:cu({profile:e})}),Zt):(Zt=new ca({region:o}),Zt)}s(wu,"_getOrCreateBedrockClient");async function Tu(o,e,t,n){let i={inputImage:(await hu(o.image,o.type,t)).toString("base64"),embeddingConfig:{outputEmbeddingLength:bu}},a=new uu({modelId:n,contentType:"application/json",accept:"application/json",body:Buffer.from(JSON.stringify(i),"utf-8")}),l=await e.send(a),u=l?.body instanceof Uint8Array?l.body:new Uint8Array(l?.body??[]),m=Buffer.from(u).toString("utf-8"),c;try{c=m?JSON.parse(m):{}}catch{throw new Error(`Amazon Bedrock Titan returned non-JSON response for embeddings: ${m.slice(0,300)}`)}let p=c?.embedding??c?.embeddings?.[0]??c?.outputEmbedding??c?.vector;if(!Array.isArray(p)||p.length===0||typeof p[0]!="number")throw new Error(`Unexpected Amazon Bedrock Titan image embedding response format: ${m.slice(0,500)}`);return p}s(Tu,"_embedImageWithAmazonBedrockTitan");async function Su(o,e,t){let n=e?.modelId??Js??fu;if(!gu.has(n))throw new Error(`Unsupported Amazon Bedrock image embedding model id: ${n}`);return await Tu(o,t,e,n)}s(Su,"_embedImageWithAmazonBedrock");async function ma(o,e){if(yu()){let t=wu();return t?Su(o,e,t):void 0}}s(ma,"_embedImage");async function pa(o,e,t){let n=typeof t?.normalize=="boolean"?t.normalize:!0,r=await ma(e,t);if(!r)return;let i=await ma(o,t);return i?{score:Do(r,i,n)}:void 0}s(pa,"compare");import{BedrockRuntimeClient as da,InvokeModelCommand as xu}from"@aws-sdk/client-bedrock-runtime";import{fromIni as vu}from"@aws-sdk/credential-providers";import Iu from"sharp";var Cu=`
415
415
  You are analyzing a UI screenshot to compare it against another UI.
416
416
 
417
417
  Your goal is to produce a STRUCTURAL LAYOUT FINGERPRINT that remains stable
@@ -473,7 +473,7 @@ FORMAT
473
473
  - Keep the output under ~30 lines.
474
474
 
475
475
  Return plain text only. No markdown.
476
- `;function Eu(o){return o?.prompt??Cu.trim()}s(Eu,"_resolvePrompt");function Ou(o){return typeof o?.maxDim=="number"&&o.maxDim>0?Math.floor(o.maxDim):1024}s(Ou,"_resolveMaxDim");function Nu(o){return o?.imageFormat==="jpeg"?"jpeg":"png"}s(Nu,"_resolveImageFormat");function Pu(o){let e=o?.jpegQuality;return typeof e=="number"&&e>=50&&e<=100?Math.floor(e):90}s(Pu,"_resolveJpegQuality");async function Ru(o,e){let t=Ou(e),n=Nu(e),r=Pu(e),i=Iu(o).resize({width:t,height:t,fit:"inside",withoutEnlargement:!0}),a,l;return n==="png"?(a=await i.png().toBuffer(),l="image/png"):(a=await i.jpeg({quality:r}).toBuffer(),l="image/jpeg"),{bytes:a,mimeType:l}}s(Ru,"_preprocessImage");var ku=new Set(["amazon.titan-embed-text-v2:0"]),_u="amazon.titan-embed-text-v2:0",Mu=new Set(["anthropic.claude-3-haiku-20240307-v1","anthropic.claude-3-sonnet-20240229-v1:0","anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-7-sonnet-20250219-v1:0","anthropic.claude-3-opus-20240229-v1:0","anthropic.claude-haiku-4-5-20251001-v1:0","anthropic.claude-opus-4-1-20250805-v1:0","anthropic.claude-opus-4-5-20251101-v1:0"]),Du="anthropic.claude-3-sonnet-20240229-v1:0",en;function ga(){return Mn&&!!Xt}s(ga,"_isAwsBedrockActive");function fa(){if(en)return en;let o=Xt;if(!o)return;let e=_n;return e?(en=new da({region:o,credentials:vu({profile:e})}),en):(en=new da({region:o}),en)}s(fa,"_getOrCreateBedrockClient");async function ya(o,e,t){let n=new xu({modelId:e,contentType:"application/json",accept:"application/json",body:Buffer.from(JSON.stringify(t))}),r=await o.send(n),i=Buffer.from(r.body).toString("utf-8");return JSON.parse(i)}s(ya,"_invokeBedrock");async function Bu(o,e,t,n){let{bytes:r,mimeType:i}=await Ru(o.image,e),l={anthropic_version:"bedrock-2023-05-31",max_tokens:1e4,temperature:0,messages:[{role:"user",content:[{type:"text",text:Eu(e)},{type:"image",source:{type:"base64",media_type:i,data:r.toString("base64")}}]}]},u=await ya(t,n,l),m=u?.content?.[0]?.text??u?.output_text??u?.completion;if(!m||!m.trim())throw new Error("Amazon Bedrock Claude returned empty description.");return m.trim()}s(Bu,"_describeUIWithAmazonBedrockClaude");async function Au(o,e,t){let i=(await ya(e,t,{inputText:o}))?.embedding;if(!Array.isArray(i)||typeof i[0]!="number")throw new Error("Unexpected embedding response for Amazon Bedrock Titan text embedding.");return i}s(Au,"_embedTextWithAmazonBedrockTitan");async function Lu(o,e,t){let n=e?.visionModelId??Zs??Du;if(!Mu.has(n))throw new Error(`Unsupported Amazon Bedrock vision model id: ${n}`);return await Bu(o,e,t,n)}s(Lu,"_describeUIWithAmazonBedrock");async function Fu(o,e,t){let n=e?.textEmbedModelId??Qs??_u;if(!ku.has(n))throw new Error(`Unsupported Amazon Bedrock text embedding model id: ${n}`);return await Au(o,t,n)}s(Fu,"_embedTextWithAmazonBedrock");async function ba(o,e){if(ga()){let t=fa();return t?Lu(o,e,t):void 0}}s(ba,"_describeUI");async function ha(o,e){if(ga()){let t=fa();return t?Fu(o,e,t):void 0}}s(ha,"_embedTextVector");async function wa(o,e,t){let n=typeof t?.normalize=="boolean"?t.normalize:!0,r=await ba(e,t);if(!r)return;let i=await ba(o,t);if(!i)return;let a=await ha(r,t);if(!a)return;let l=await ha(i,t);return l?{score:Do(a,l,n)}:void 0}s(wa,"compare");var Uu=.25,Hu=.5,Wu=.25;function Bo(o){return Number.isFinite(o)?Math.max(0,Math.min(1,o)):0}s(Bo,"_clamp01");function Es(o,e){return typeof o=="number"&&Number.isFinite(o)&&o>0?o:e}s(Es,"_weightOrDefault");async function Ta(o,e,t){let n=[],r=Es(t?.weights?.mssim,Uu),i=Es(t?.weights?.vectorEmbedding,Hu),a=Es(t?.weights?.textEmbedding,Wu),l=await aa(o,e,t?.mssim),u=Bo(l.score);n.push(`mssim=${u.toFixed(5)}`);let m;try{let B=await pa(o,e,t?.imageEmbedding);B&&typeof B.score=="number"?(m=Bo(B.score),n.push(`image-embedding=${m.toFixed(5)}`)):n.push("image-embedding=skipped (inactive)")}catch(B){n.push(`image-embedding=skipped (${B instanceof Error?B.message:String(B)})`)}let c;try{let B=await wa(o,e,t?.textEmbedding);B&&typeof B.score=="number"?(c=Bo(B.score),n.push(`text-embedding=${c.toFixed(5)}`)):n.push("text-embedding=skipped (inactive)")}catch(B){n.push(`text-embedding=skipped (${B instanceof Error?B.message:String(B)})`)}let p=[{name:"mssim",score:u,weight:r}];typeof m=="number"&&p.push({name:"image-embedding",score:m,weight:i}),typeof c=="number"&&p.push({name:"text-embedding",score:c,weight:a});let b=p.reduce((B,w)=>B+w.weight,0),f=b>0?p.reduce((B,w)=>B+w.score*(w.weight/b),0):0,x=Bo(f);return n.push(`combined=${x.toFixed(5)} (signals=${p.map(B=>B.name).join(", ")})`),{score:x,notes:n}}s(Ta,"compareWithNotes");import qu from"node:crypto";function $u(){let o=ei;if(!o)throw new Error("No Figma access token configured");return o}s($u,"_requireFigmaToken");function ju(o){return o==="jpg"?{mimeType:"image/jpeg",type:"jpeg"}:{mimeType:"image/png",type:"png"}}s(ju,"_mimeTypeFor");function zu(o){let e=qu.createHash("sha256");return e.update(o.fileKey),e.update("|"),e.update(o.nodeId),e.update("|"),e.update(o.format??"png"),e.update("|"),e.update(String(o.scale??2)),e.digest("hex").slice(0,24)}s(zu,"_buildCacheKey");async function Vu(o,e){let t=await fetch(o,{method:"GET",headers:{"X-Figma-Token":e,Accept:"application/json"}}),n=await t.text(),r;try{r=n?JSON.parse(n):{}}catch{throw new Error(`Figma API returned non-JSON response (status=${t.status}). Body: ${n.slice(0,500)}`)}if(!t.ok){let i=typeof r?.err=="string"?r.err:`Figma API error (status=${t.status})`;throw new Error(i)}return r}s(Vu,"_fetchJson");async function Gu(o){let e=await fetch(o,{method:"GET"});if(!e.ok){let n=await e.text().catch(()=>"");throw new Error(`Failed to download Figma rendered image (status=${e.status}): ${n.slice(0,300)}`)}let t=await e.arrayBuffer();return Buffer.from(t)}s(Gu,"_fetchBinary");async function Sa(o){let e=$u(),t=o.format??"png",n=typeof o.scale=="number"&&o.scale>0?o.scale:2,{mimeType:r,type:i}=ju(t),a=ti,l=o.fileKey,u=o.nodeId,m=`${a}/images/${encodeURIComponent(l)}?ids=${encodeURIComponent(u)}&format=${encodeURIComponent(t)}&scale=${encodeURIComponent(String(n))}`,c=await Vu(m,e),p=c.images?.[u];if(!p){let B=typeof c.err=="string"&&c.err.trim()?c.err:"Figma did not return an image URL for the given nodeId.";throw new Error(B)}let b=await Gu(p),f=zu(o),x={image:b,mimeType:r,type:i,cacheKey:f};return o.includeId===!0&&(x.nodeId=u,x.fileKey=l),x}s(Sa,"getFigmaDesignScreenshot");import{z as be}from"zod";var xa="png",Ku=!0,va="semantic",Ao=class{static{s(this,"ComparePageWithDesign")}name(){return"figma_compare-page-with-design"}description(){return`
476
+ `;function Eu(o){return o?.prompt??Cu.trim()}s(Eu,"_resolvePrompt");function Ou(o){return typeof o?.maxDim=="number"&&o.maxDim>0?Math.floor(o.maxDim):1024}s(Ou,"_resolveMaxDim");function Nu(o){return o?.imageFormat==="jpeg"?"jpeg":"png"}s(Nu,"_resolveImageFormat");function Pu(o){let e=o?.jpegQuality;return typeof e=="number"&&e>=50&&e<=100?Math.floor(e):90}s(Pu,"_resolveJpegQuality");async function ku(o,e){let t=Ou(e),n=Nu(e),r=Pu(e),i=Iu(o).resize({width:t,height:t,fit:"inside",withoutEnlargement:!0}),a,l;return n==="png"?(a=await i.png().toBuffer(),l="image/png"):(a=await i.jpeg({quality:r}).toBuffer(),l="image/jpeg"),{bytes:a,mimeType:l}}s(ku,"_preprocessImage");var Ru=new Set(["amazon.titan-embed-text-v2:0"]),_u="amazon.titan-embed-text-v2:0",Mu=new Set(["anthropic.claude-3-haiku-20240307-v1","anthropic.claude-3-sonnet-20240229-v1:0","anthropic.claude-3-5-sonnet-20241022-v2:0","anthropic.claude-3-7-sonnet-20250219-v1:0","anthropic.claude-3-opus-20240229-v1:0","anthropic.claude-haiku-4-5-20251001-v1:0","anthropic.claude-opus-4-1-20250805-v1:0","anthropic.claude-opus-4-5-20251101-v1:0"]),Du="anthropic.claude-3-sonnet-20240229-v1:0",en;function ga(){return Mn&&!!Xt}s(ga,"_isAwsBedrockActive");function fa(){if(en)return en;let o=Xt;if(!o)return;let e=_n;return e?(en=new da({region:o,credentials:vu({profile:e})}),en):(en=new da({region:o}),en)}s(fa,"_getOrCreateBedrockClient");async function ya(o,e,t){let n=new xu({modelId:e,contentType:"application/json",accept:"application/json",body:Buffer.from(JSON.stringify(t))}),r=await o.send(n),i=Buffer.from(r.body).toString("utf-8");return JSON.parse(i)}s(ya,"_invokeBedrock");async function Bu(o,e,t,n){let{bytes:r,mimeType:i}=await ku(o.image,e),l={anthropic_version:"bedrock-2023-05-31",max_tokens:1e4,temperature:0,messages:[{role:"user",content:[{type:"text",text:Eu(e)},{type:"image",source:{type:"base64",media_type:i,data:r.toString("base64")}}]}]},u=await ya(t,n,l),m=u?.content?.[0]?.text??u?.output_text??u?.completion;if(!m||!m.trim())throw new Error("Amazon Bedrock Claude returned empty description.");return m.trim()}s(Bu,"_describeUIWithAmazonBedrockClaude");async function Au(o,e,t){let i=(await ya(e,t,{inputText:o}))?.embedding;if(!Array.isArray(i)||typeof i[0]!="number")throw new Error("Unexpected embedding response for Amazon Bedrock Titan text embedding.");return i}s(Au,"_embedTextWithAmazonBedrockTitan");async function Lu(o,e,t){let n=e?.visionModelId??Zs??Du;if(!Mu.has(n))throw new Error(`Unsupported Amazon Bedrock vision model id: ${n}`);return await Bu(o,e,t,n)}s(Lu,"_describeUIWithAmazonBedrock");async function Fu(o,e,t){let n=e?.textEmbedModelId??Qs??_u;if(!Ru.has(n))throw new Error(`Unsupported Amazon Bedrock text embedding model id: ${n}`);return await Au(o,t,n)}s(Fu,"_embedTextWithAmazonBedrock");async function ba(o,e){if(ga()){let t=fa();return t?Lu(o,e,t):void 0}}s(ba,"_describeUI");async function ha(o,e){if(ga()){let t=fa();return t?Fu(o,e,t):void 0}}s(ha,"_embedTextVector");async function wa(o,e,t){let n=typeof t?.normalize=="boolean"?t.normalize:!0,r=await ba(e,t);if(!r)return;let i=await ba(o,t);if(!i)return;let a=await ha(r,t);if(!a)return;let l=await ha(i,t);return l?{score:Do(a,l,n)}:void 0}s(wa,"compare");var Uu=.25,Hu=.5,Wu=.25;function Bo(o){return Number.isFinite(o)?Math.max(0,Math.min(1,o)):0}s(Bo,"_clamp01");function Es(o,e){return typeof o=="number"&&Number.isFinite(o)&&o>0?o:e}s(Es,"_weightOrDefault");async function Ta(o,e,t){let n=[],r=Es(t?.weights?.mssim,Uu),i=Es(t?.weights?.vectorEmbedding,Hu),a=Es(t?.weights?.textEmbedding,Wu),l=await aa(o,e,t?.mssim),u=Bo(l.score);n.push(`mssim=${u.toFixed(5)}`);let m;try{let B=await pa(o,e,t?.imageEmbedding);B&&typeof B.score=="number"?(m=Bo(B.score),n.push(`image-embedding=${m.toFixed(5)}`)):n.push("image-embedding=skipped (inactive)")}catch(B){n.push(`image-embedding=skipped (${B instanceof Error?B.message:String(B)})`)}let c;try{let B=await wa(o,e,t?.textEmbedding);B&&typeof B.score=="number"?(c=Bo(B.score),n.push(`text-embedding=${c.toFixed(5)}`)):n.push("text-embedding=skipped (inactive)")}catch(B){n.push(`text-embedding=skipped (${B instanceof Error?B.message:String(B)})`)}let p=[{name:"mssim",score:u,weight:r}];typeof m=="number"&&p.push({name:"image-embedding",score:m,weight:i}),typeof c=="number"&&p.push({name:"text-embedding",score:c,weight:a});let b=p.reduce((B,w)=>B+w.weight,0),f=b>0?p.reduce((B,w)=>B+w.score*(w.weight/b),0):0,x=Bo(f);return n.push(`combined=${x.toFixed(5)} (signals=${p.map(B=>B.name).join(", ")})`),{score:x,notes:n}}s(Ta,"compareWithNotes");import qu from"node:crypto";function $u(){let o=ei;if(!o)throw new Error("No Figma access token configured");return o}s($u,"_requireFigmaToken");function ju(o){return o==="jpg"?{mimeType:"image/jpeg",type:"jpeg"}:{mimeType:"image/png",type:"png"}}s(ju,"_mimeTypeFor");function zu(o){let e=qu.createHash("sha256");return e.update(o.fileKey),e.update("|"),e.update(o.nodeId),e.update("|"),e.update(o.format??"png"),e.update("|"),e.update(String(o.scale??2)),e.digest("hex").slice(0,24)}s(zu,"_buildCacheKey");async function Vu(o,e){let t=await fetch(o,{method:"GET",headers:{"X-Figma-Token":e,Accept:"application/json"}}),n=await t.text(),r;try{r=n?JSON.parse(n):{}}catch{throw new Error(`Figma API returned non-JSON response (status=${t.status}). Body: ${n.slice(0,500)}`)}if(!t.ok){let i=typeof r?.err=="string"?r.err:`Figma API error (status=${t.status})`;throw new Error(i)}return r}s(Vu,"_fetchJson");async function Gu(o){let e=await fetch(o,{method:"GET"});if(!e.ok){let n=await e.text().catch(()=>"");throw new Error(`Failed to download Figma rendered image (status=${e.status}): ${n.slice(0,300)}`)}let t=await e.arrayBuffer();return Buffer.from(t)}s(Gu,"_fetchBinary");async function Sa(o){let e=$u(),t=o.format??"png",n=typeof o.scale=="number"&&o.scale>0?o.scale:2,{mimeType:r,type:i}=ju(t),a=ti,l=o.fileKey,u=o.nodeId,m=`${a}/images/${encodeURIComponent(l)}?ids=${encodeURIComponent(u)}&format=${encodeURIComponent(t)}&scale=${encodeURIComponent(String(n))}`,c=await Vu(m,e),p=c.images?.[u];if(!p){let B=typeof c.err=="string"&&c.err.trim()?c.err:"Figma did not return an image URL for the given nodeId.";throw new Error(B)}let b=await Gu(p),f=zu(o),x={image:b,mimeType:r,type:i,cacheKey:f};return o.includeId===!0&&(x.nodeId=u,x.fileKey=l),x}s(Sa,"getFigmaDesignScreenshot");import{z as be}from"zod";var xa="png",Ku=!0,va="semantic",Ao=class{static{s(this,"ComparePageWithDesign")}name(){return"figma_compare-page-with-design"}description(){return`
477
477
  Compares the CURRENT PAGE UI against a Figma design snapshot and returns a combined similarity score.
478
478
 
479
479
  What this tool does:
@@ -528,7 +528,7 @@ so the page layout follows the OS window size.
528
528
  Important:
529
529
  - If Playwright viewport emulation is enabled (viewport is NOT null), resizing the OS window may not change page layout.
530
530
  - On non-Chromium browsers (Firefox/WebKit), CDP is not available and this tool will fail.
531
- `.trim()}inputSchema(){return{width:ae.number().int().min(nc).optional().describe('Target window width in pixels (required when state="normal").'),height:ae.number().int().min(oc).optional().describe('Target window height in pixels (required when state="normal").'),state:ae.enum(["normal","maximized","minimized","fullscreen"]).optional().default("normal").describe('Target window state. If not "normal", width/height may be ignored by the browser.')}}outputSchema(){return{requested:ae.object({width:ae.number().int().nullable().describe("Requested window width (pixels). Null if not provided."),height:ae.number().int().nullable().describe("Requested window height (pixels). Null if not provided."),state:ae.enum(["normal","maximized","minimized","fullscreen"]).describe("Requested window state.")}).describe("Requested window change parameters."),before:ae.object({windowId:ae.number().int().describe("CDP window id for the current target."),state:ae.string().nullable().describe("Window state before resizing."),left:ae.number().int().nullable().describe("Window left position before resizing."),top:ae.number().int().nullable().describe("Window top position before resizing."),width:ae.number().int().nullable().describe("Window width before resizing."),height:ae.number().int().nullable().describe("Window height before resizing.")}).describe("Window bounds before resizing."),after:ae.object({windowId:ae.number().int().describe("CDP window id for the current target."),state:ae.string().nullable().describe("Window state after resizing."),left:ae.number().int().nullable().describe("Window left position after resizing."),top:ae.number().int().nullable().describe("Window top position after resizing."),width:ae.number().int().nullable().describe("Window width after resizing."),height:ae.number().int().nullable().describe("Window height after resizing.")}).describe("Window bounds after resizing."),viewport:ae.object({innerWidth:ae.number().int().describe("window.innerWidth after resizing (CSS pixels)."),innerHeight:ae.number().int().describe("window.innerHeight after resizing (CSS pixels)."),outerWidth:ae.number().int().describe("window.outerWidth after resizing (CSS pixels)."),outerHeight:ae.number().int().describe("window.outerHeight after resizing (CSS pixels)."),devicePixelRatio:ae.number().describe("window.devicePixelRatio after resizing.")}).describe("Page viewport metrics after resizing (helps verify responsive behavior).")}}async handle(e,t){let n=t.state??"normal",r=t.width,i=t.height;if(n==="normal"&&(typeof r!="number"||typeof i!="number"))throw new Error('state="normal" requires both width and height.');let a=e.page,l=await a.context().newCDPSession(a);try{let u=await l.send("Browser.getWindowForTarget",{}),m=Number(u.windowId),c=u.bounds??{},p={windowId:m,state:typeof c.windowState=="string"?c.windowState:null,left:typeof c.left=="number"?c.left:null,top:typeof c.top=="number"?c.top:null,width:typeof c.width=="number"?c.width:null,height:typeof c.height=="number"?c.height:null},b={};n!=="normal"?b.windowState=n:(b.windowState="normal",b.width=r,b.height=i),await l.send("Browser.setWindowBounds",{windowId:m,bounds:b});let x=(await l.send("Browser.getWindowForTarget",{})).bounds??{},B={windowId:m,state:typeof x.windowState=="string"?x.windowState:null,left:typeof x.left=="number"?x.left:null,top:typeof x.top=="number"?x.top:null,width:typeof x.width=="number"?x.width:null,height:typeof x.height=="number"?x.height:null},w=await a.evaluate(()=>({innerWidth:window.innerWidth,innerHeight:window.innerHeight,outerWidth:window.outerWidth,outerHeight:window.outerHeight,devicePixelRatio:window.devicePixelRatio})),U={innerWidth:Number(w.innerWidth),innerHeight:Number(w.innerHeight),outerWidth:Number(w.outerWidth),outerHeight:Number(w.outerHeight),devicePixelRatio:Number(w.devicePixelRatio)};return{requested:{width:typeof r=="number"?r:null,height:typeof i=="number"?i:null,state:n},before:p,after:B,viewport:U}}catch(u){let m=String(u?.message??u);throw new Error(`Failed to resize real browser window via CDP. This tool works best on Chromium-based browsers. Original error: ${m}`)}finally{await l.detach().catch(()=>{})}}};import{z as Ps}from"zod";var rc=1e4,jo=class{static{s(this,"Select")}name(){return"interaction_select"}description(){return"Select an element on the page with the given value"}inputSchema(){return{selector:Ps.string().describe("CSS selector for element to select."),value:Ps.string().describe("Value to select."),timeoutMs:Ps.number().int().positive().optional().describe("Timeout in ms to wait for the element (default 10000). Use a shorter value (e.g. 5000) to fail faster if the selector might be invalid.")}}outputSchema(){return{}}async handle(e,t){let n=t.timeoutMs??rc;return await(await e.page.waitForSelector(t.selector,{state:"visible",timeout:n})).selectOption(t.value),{}}};import{z as ne}from"zod";var Pa="auto",Ra="by",zo=class{static{s(this,"Scroll")}name(){return"interaction_scroll"}description(){return`
531
+ `.trim()}inputSchema(){return{width:ae.number().int().min(nc).optional().describe('Target window width in pixels (required when state="normal").'),height:ae.number().int().min(oc).optional().describe('Target window height in pixels (required when state="normal").'),state:ae.enum(["normal","maximized","minimized","fullscreen"]).optional().default("normal").describe('Target window state. If not "normal", width/height may be ignored by the browser.')}}outputSchema(){return{requested:ae.object({width:ae.number().int().nullable().describe("Requested window width (pixels). Null if not provided."),height:ae.number().int().nullable().describe("Requested window height (pixels). Null if not provided."),state:ae.enum(["normal","maximized","minimized","fullscreen"]).describe("Requested window state.")}).describe("Requested window change parameters."),before:ae.object({windowId:ae.number().int().describe("CDP window id for the current target."),state:ae.string().nullable().describe("Window state before resizing."),left:ae.number().int().nullable().describe("Window left position before resizing."),top:ae.number().int().nullable().describe("Window top position before resizing."),width:ae.number().int().nullable().describe("Window width before resizing."),height:ae.number().int().nullable().describe("Window height before resizing.")}).describe("Window bounds before resizing."),after:ae.object({windowId:ae.number().int().describe("CDP window id for the current target."),state:ae.string().nullable().describe("Window state after resizing."),left:ae.number().int().nullable().describe("Window left position after resizing."),top:ae.number().int().nullable().describe("Window top position after resizing."),width:ae.number().int().nullable().describe("Window width after resizing."),height:ae.number().int().nullable().describe("Window height after resizing.")}).describe("Window bounds after resizing."),viewport:ae.object({innerWidth:ae.number().int().describe("window.innerWidth after resizing (CSS pixels)."),innerHeight:ae.number().int().describe("window.innerHeight after resizing (CSS pixels)."),outerWidth:ae.number().int().describe("window.outerWidth after resizing (CSS pixels)."),outerHeight:ae.number().int().describe("window.outerHeight after resizing (CSS pixels)."),devicePixelRatio:ae.number().describe("window.devicePixelRatio after resizing.")}).describe("Page viewport metrics after resizing (helps verify responsive behavior).")}}async handle(e,t){let n=t.state??"normal",r=t.width,i=t.height;if(n==="normal"&&(typeof r!="number"||typeof i!="number"))throw new Error('state="normal" requires both width and height.');let a=e.page,l=await a.context().newCDPSession(a);try{let u=await l.send("Browser.getWindowForTarget",{}),m=Number(u.windowId),c=u.bounds??{},p={windowId:m,state:typeof c.windowState=="string"?c.windowState:null,left:typeof c.left=="number"?c.left:null,top:typeof c.top=="number"?c.top:null,width:typeof c.width=="number"?c.width:null,height:typeof c.height=="number"?c.height:null},b={};n!=="normal"?b.windowState=n:(b.windowState="normal",b.width=r,b.height=i),await l.send("Browser.setWindowBounds",{windowId:m,bounds:b});let x=(await l.send("Browser.getWindowForTarget",{})).bounds??{},B={windowId:m,state:typeof x.windowState=="string"?x.windowState:null,left:typeof x.left=="number"?x.left:null,top:typeof x.top=="number"?x.top:null,width:typeof x.width=="number"?x.width:null,height:typeof x.height=="number"?x.height:null},w=await a.evaluate(()=>({innerWidth:window.innerWidth,innerHeight:window.innerHeight,outerWidth:window.outerWidth,outerHeight:window.outerHeight,devicePixelRatio:window.devicePixelRatio})),U={innerWidth:Number(w.innerWidth),innerHeight:Number(w.innerHeight),outerWidth:Number(w.outerWidth),outerHeight:Number(w.outerHeight),devicePixelRatio:Number(w.devicePixelRatio)};return{requested:{width:typeof r=="number"?r:null,height:typeof i=="number"?i:null,state:n},before:p,after:B,viewport:U}}catch(u){let m=String(u?.message??u);throw new Error(`Failed to resize real browser window via CDP. This tool works best on Chromium-based browsers. Original error: ${m}`)}finally{await l.detach().catch(()=>{})}}};import{z as Ps}from"zod";var rc=1e4,jo=class{static{s(this,"Select")}name(){return"interaction_select"}description(){return"Select an element on the page with the given value"}inputSchema(){return{selector:Ps.string().describe("CSS selector for element to select."),value:Ps.string().describe("Value to select."),timeoutMs:Ps.number().int().positive().optional().describe("Timeout in ms to wait for the element (default 10000). Use a shorter value (e.g. 5000) to fail faster if the selector might be invalid.")}}outputSchema(){return{}}async handle(e,t){let n=t.timeoutMs??rc;return await(await e.page.waitForSelector(t.selector,{state:"visible",timeout:n})).selectOption(t.value),{}}};import{z as ne}from"zod";var Pa="auto",ka="by",zo=class{static{s(this,"Scroll")}name(){return"interaction_scroll"}description(){return`
532
532
  Scrolls the page viewport or a specific scrollable element.
533
533
 
534
534
  Modes:
@@ -544,7 +544,7 @@ Use this tool to:
544
544
  - Jump to the top/bottom without knowing exact positions
545
545
  - Bring elements into view before clicking
546
546
  - Inspect lazy-loaded content that appears on scroll
547
- `.trim()}inputSchema(){return{mode:ne.enum(["by","to","top","bottom","left","right"]).optional().default(Ra).describe('Scroll mode. "by" uses dx/dy, "to" uses x/y, and top/bottom/left/right jump to edges.'),selector:ne.string().optional().describe("Optional CSS selector for a scrollable container. If omitted, scrolls the document viewport."),dx:ne.number().optional().describe('Horizontal scroll delta in pixels (used when mode="by"). Default: 0.'),dy:ne.number().optional().describe('Vertical scroll delta in pixels (used when mode="by"). Default: 0.'),x:ne.number().optional().describe('Absolute horizontal scroll position in pixels (used when mode="to").'),y:ne.number().optional().describe('Absolute vertical scroll position in pixels (used when mode="to").'),behavior:ne.enum(["auto","smooth"]).optional().default(Pa).describe('Native scroll behavior. Use "auto" for deterministic automation.')}}outputSchema(){return{mode:ne.enum(["by","to","top","bottom","left","right"]).describe("The scroll mode used."),selector:ne.string().nullable().describe("The selector of the scroll container if provided; otherwise null (document viewport)."),behavior:ne.enum(["auto","smooth"]).describe("The scroll behavior used."),before:ne.object({x:ne.number().describe("ScrollLeft before scrolling."),y:ne.number().describe("ScrollTop before scrolling."),scrollWidth:ne.number().describe("Total scrollable width before scrolling."),scrollHeight:ne.number().describe("Total scrollable height before scrolling."),clientWidth:ne.number().describe("Viewport/container client width before scrolling."),clientHeight:ne.number().describe("Viewport/container client height before scrolling.")}).describe("Scroll metrics before the scroll action."),after:ne.object({x:ne.number().describe("ScrollLeft after scrolling."),y:ne.number().describe("ScrollTop after scrolling."),scrollWidth:ne.number().describe("Total scrollable width after scrolling."),scrollHeight:ne.number().describe("Total scrollable height after scrolling."),clientWidth:ne.number().describe("Viewport/container client width after scrolling."),clientHeight:ne.number().describe("Viewport/container client height after scrolling.")}).describe("Scroll metrics after the scroll action."),canScrollX:ne.boolean().describe("Whether horizontal scrolling is possible (scrollWidth > clientWidth)."),canScrollY:ne.boolean().describe("Whether vertical scrolling is possible (scrollHeight > clientHeight)."),maxScrollX:ne.number().describe("Maximum horizontal scrollLeft (scrollWidth - clientWidth)."),maxScrollY:ne.number().describe("Maximum vertical scrollTop (scrollHeight - clientHeight)."),isAtLeft:ne.boolean().describe("Whether the scroll position is at the far left."),isAtRight:ne.boolean().describe("Whether the scroll position is at the far right."),isAtTop:ne.boolean().describe("Whether the scroll position is at the very top."),isAtBottom:ne.boolean().describe("Whether the scroll position is at the very bottom.")}}async handle(e,t){let n=t.mode??Ra,r=t.selector,i=t.behavior??Pa,a=t.dx??0,l=t.dy??0,u=t.x,m=t.y;if(n==="to"&&typeof u!="number"&&typeof m!="number")throw new Error('mode="to" requires at least one of x or y.');if(n==="by"&&a===0&&l===0)throw new Error('mode="by" requires dx and/or dy to be non-zero.');let c=await e.page.evaluate(p=>{let b=p.modeEval,f=p.selectorEval,x=p.dxEval,B=p.dyEval,w=p.xEval,U=p.yEval,D=p.behaviorEval,H=s(()=>{if(f){let pe=document.querySelector(f);if(!pe)throw new Error(`Element with selector "${f}" not found`);return pe}let v=document.scrollingElement||document.documentElement||document.body;if(!v)throw new Error("No scrolling element available.");return v},"getTarget"),Q=s(v=>({x:v.scrollLeft,y:v.scrollTop,scrollWidth:v.scrollWidth,scrollHeight:v.scrollHeight,clientWidth:v.clientWidth,clientHeight:v.clientHeight}),"readMetrics"),$=s((v,pe,V)=>v<pe?pe:v>V?V:v,"clamp"),P=s(v=>{let pe=Math.max(0,v.scrollWidth-v.clientWidth),V=Math.max(0,v.scrollHeight-v.clientHeight);if(b==="by"){let q=$(v.scrollLeft+x,0,pe),X=$(v.scrollTop+B,0,V);v.scrollTo({left:q,top:X,behavior:D});return}if(b==="to"){let q=typeof w=="number"?$(w,0,pe):v.scrollLeft,X=typeof U=="number"?$(U,0,V):v.scrollTop;v.scrollTo({left:q,top:X,behavior:D});return}if(b==="top"){v.scrollTo({top:0,left:v.scrollLeft,behavior:D});return}if(b==="bottom"){v.scrollTo({top:V,left:v.scrollLeft,behavior:D});return}if(b==="left"){v.scrollTo({left:0,top:v.scrollTop,behavior:D});return}if(b==="right"){v.scrollTo({left:pe,top:v.scrollTop,behavior:D});return}},"doScroll"),W=H(),G=Q(W);P(W);let _=Q(W),oe=Math.max(0,_.scrollWidth-_.clientWidth),Y=Math.max(0,_.scrollHeight-_.clientHeight),M=_.scrollWidth>_.clientWidth,ee=_.scrollHeight>_.clientHeight,ue=1,ce=_.x<=ue,fe=_.x>=oe-ue,te=_.y<=ue,me=_.y>=Y-ue;return{before:G,after:_,canScrollX:M,canScrollY:ee,maxScrollX:oe,maxScrollY:Y,isAtLeft:ce,isAtRight:fe,isAtTop:te,isAtBottom:me}},{modeEval:n,selectorEval:r,dxEval:a,dyEval:l,xEval:u,yEval:m,behaviorEval:i});return{mode:n,selector:r??null,behavior:i,before:c.before,after:c.after,canScrollX:c.canScrollX,canScrollY:c.canScrollY,maxScrollX:c.maxScrollX,maxScrollY:c.maxScrollY,isAtLeft:c.isAtLeft,isAtRight:c.isAtRight,isAtTop:c.isAtTop,isAtBottom:c.isAtBottom}}};var ka=[new Lo,new Fo,new Uo,new Ho,new Wo,new qo,new $o,new jo,new zo];import{z as nn}from"zod";var sc=0,ic="load",Vo=class{static{s(this,"GoBack")}name(){return"navigation_go-back"}description(){return`
547
+ `.trim()}inputSchema(){return{mode:ne.enum(["by","to","top","bottom","left","right"]).optional().default(ka).describe('Scroll mode. "by" uses dx/dy, "to" uses x/y, and top/bottom/left/right jump to edges.'),selector:ne.string().optional().describe("Optional CSS selector for a scrollable container. If omitted, scrolls the document viewport."),dx:ne.number().optional().describe('Horizontal scroll delta in pixels (used when mode="by"). Default: 0.'),dy:ne.number().optional().describe('Vertical scroll delta in pixels (used when mode="by"). Default: 0.'),x:ne.number().optional().describe('Absolute horizontal scroll position in pixels (used when mode="to").'),y:ne.number().optional().describe('Absolute vertical scroll position in pixels (used when mode="to").'),behavior:ne.enum(["auto","smooth"]).optional().default(Pa).describe('Native scroll behavior. Use "auto" for deterministic automation.')}}outputSchema(){return{mode:ne.enum(["by","to","top","bottom","left","right"]).describe("The scroll mode used."),selector:ne.string().nullable().describe("The selector of the scroll container if provided; otherwise null (document viewport)."),behavior:ne.enum(["auto","smooth"]).describe("The scroll behavior used."),before:ne.object({x:ne.number().describe("ScrollLeft before scrolling."),y:ne.number().describe("ScrollTop before scrolling."),scrollWidth:ne.number().describe("Total scrollable width before scrolling."),scrollHeight:ne.number().describe("Total scrollable height before scrolling."),clientWidth:ne.number().describe("Viewport/container client width before scrolling."),clientHeight:ne.number().describe("Viewport/container client height before scrolling.")}).describe("Scroll metrics before the scroll action."),after:ne.object({x:ne.number().describe("ScrollLeft after scrolling."),y:ne.number().describe("ScrollTop after scrolling."),scrollWidth:ne.number().describe("Total scrollable width after scrolling."),scrollHeight:ne.number().describe("Total scrollable height after scrolling."),clientWidth:ne.number().describe("Viewport/container client width after scrolling."),clientHeight:ne.number().describe("Viewport/container client height after scrolling.")}).describe("Scroll metrics after the scroll action."),canScrollX:ne.boolean().describe("Whether horizontal scrolling is possible (scrollWidth > clientWidth)."),canScrollY:ne.boolean().describe("Whether vertical scrolling is possible (scrollHeight > clientHeight)."),maxScrollX:ne.number().describe("Maximum horizontal scrollLeft (scrollWidth - clientWidth)."),maxScrollY:ne.number().describe("Maximum vertical scrollTop (scrollHeight - clientHeight)."),isAtLeft:ne.boolean().describe("Whether the scroll position is at the far left."),isAtRight:ne.boolean().describe("Whether the scroll position is at the far right."),isAtTop:ne.boolean().describe("Whether the scroll position is at the very top."),isAtBottom:ne.boolean().describe("Whether the scroll position is at the very bottom.")}}async handle(e,t){let n=t.mode??ka,r=t.selector,i=t.behavior??Pa,a=t.dx??0,l=t.dy??0,u=t.x,m=t.y;if(n==="to"&&typeof u!="number"&&typeof m!="number")throw new Error('mode="to" requires at least one of x or y.');if(n==="by"&&a===0&&l===0)throw new Error('mode="by" requires dx and/or dy to be non-zero.');let c=await e.page.evaluate(p=>{let b=p.modeEval,f=p.selectorEval,x=p.dxEval,B=p.dyEval,w=p.xEval,U=p.yEval,D=p.behaviorEval,H=s(()=>{if(f){let pe=document.querySelector(f);if(!pe)throw new Error(`Element with selector "${f}" not found`);return pe}let v=document.scrollingElement||document.documentElement||document.body;if(!v)throw new Error("No scrolling element available.");return v},"getTarget"),Q=s(v=>({x:v.scrollLeft,y:v.scrollTop,scrollWidth:v.scrollWidth,scrollHeight:v.scrollHeight,clientWidth:v.clientWidth,clientHeight:v.clientHeight}),"readMetrics"),$=s((v,pe,V)=>v<pe?pe:v>V?V:v,"clamp"),P=s(v=>{let pe=Math.max(0,v.scrollWidth-v.clientWidth),V=Math.max(0,v.scrollHeight-v.clientHeight);if(b==="by"){let q=$(v.scrollLeft+x,0,pe),X=$(v.scrollTop+B,0,V);v.scrollTo({left:q,top:X,behavior:D});return}if(b==="to"){let q=typeof w=="number"?$(w,0,pe):v.scrollLeft,X=typeof U=="number"?$(U,0,V):v.scrollTop;v.scrollTo({left:q,top:X,behavior:D});return}if(b==="top"){v.scrollTo({top:0,left:v.scrollLeft,behavior:D});return}if(b==="bottom"){v.scrollTo({top:V,left:v.scrollLeft,behavior:D});return}if(b==="left"){v.scrollTo({left:0,top:v.scrollTop,behavior:D});return}if(b==="right"){v.scrollTo({left:pe,top:v.scrollTop,behavior:D});return}},"doScroll"),W=H(),G=Q(W);P(W);let _=Q(W),oe=Math.max(0,_.scrollWidth-_.clientWidth),Y=Math.max(0,_.scrollHeight-_.clientHeight),M=_.scrollWidth>_.clientWidth,ee=_.scrollHeight>_.clientHeight,ue=1,ce=_.x<=ue,fe=_.x>=oe-ue,te=_.y<=ue,me=_.y>=Y-ue;return{before:G,after:_,canScrollX:M,canScrollY:ee,maxScrollX:oe,maxScrollY:Y,isAtLeft:ce,isAtRight:fe,isAtTop:te,isAtBottom:me}},{modeEval:n,selectorEval:r,dxEval:a,dyEval:l,xEval:u,yEval:m,behaviorEval:i});return{mode:n,selector:r??null,behavior:i,before:c.before,after:c.after,canScrollX:c.canScrollX,canScrollY:c.canScrollY,maxScrollX:c.maxScrollX,maxScrollY:c.maxScrollY,isAtLeft:c.isAtLeft,isAtRight:c.isAtRight,isAtTop:c.isAtTop,isAtBottom:c.isAtBottom}}};var Ra=[new Lo,new Fo,new Uo,new Ho,new Wo,new qo,new $o,new jo,new zo];import{z as nn}from"zod";var sc=0,ic="load",Vo=class{static{s(this,"GoBack")}name(){return"navigation_go-back"}description(){return`
548
548
  Navigates to the previous page in history.
549
549
  In case of multiple redirects, the navigation will resolve with the response of the last redirect.
550
550
  If cannot go back, returns empty response.
@@ -607,7 +607,7 @@ Otherwise (non-2XX status code or no response at all because of timeout, network
607
607
  A monotonically increasing sequence number assigned to each HTTP request.
608
608
  It reflects the order in which requests were captured and can be used by clients
609
609
  to retrieve requests incrementally by requesting only those with a higher sequence
610
- number than the last one received.`)}).describe("HTTP request item.")).describe("Retrieved HTTP requests.")}}async handle(e,t){let n=e.getHttpRequests().filter(a=>{let l=!0;return l&&t.resourceType&&(l=a.resourceType===t.resourceType),l&&t.status&&(l&&t.status.min&&(l=a.response?a.response.status>=t.status.min:!1),l&&t.status.max&&(l=a.response?a.response.status<=t.status.max:!1)),l&&t.ok!==void 0&&(l=a.ok),l&&t.timestamp&&(l=a.timestamp>=t.timestamp),l&&t.sequenceNumber&&(l=a.sequenceNumber>t.sequenceNumber),l});return{requests:(t.limit?.count?t.limit.from==="start"?n.slice(0,t.limit.count):n.slice(-t.limit.count):n).map(a=>({url:a.url,method:a.method,headers:a.headers,body:a.body,resourceType:a.resourceType,failure:a.failure,duration:a.duration,response:a.response?{status:a.response.status,statusText:a.response.statusText,headers:a.response.headers,body:a.response.body}:void 0,ok:a.ok,timestamp:a.timestamp,sequenceNumber:a.sequenceNumber}))}}};import{z as dc}from"zod";var Qo=class{static{s(this,"GetTraceId")}name(){return"o11y_get-trace-id"}description(){return"Gets the OpenTelemetry compatible trace id of the current session."}inputSchema(){return{}}outputSchema(){return{traceId:dc.string().describe("The OpenTelemetry compatible trace id of the current session if available.").optional()}}async handle(e,t){return{traceId:await e.getTraceId()}}};import{z as j}from"zod";var Ma=0,bc=3e4;function Zo(o,e,t){return typeof o!="number"||!Number.isFinite(o)?{rating:"not_available",value:null,unit:"ms",thresholds:{good:e,poor:t}}:o<=e?{rating:"good",value:o,unit:"ms",thresholds:{good:e,poor:t}}:o>t?{rating:"poor",value:o,unit:"ms",thresholds:{good:e,poor:t}}:{rating:"needs_improvement",value:o,unit:"ms",thresholds:{good:e,poor:t}}}s(Zo,"rateMs");function hc(o,e,t){return typeof o!="number"||!Number.isFinite(o)?{rating:"not_available",value:null,unit:"score",thresholds:{good:e,poor:t}}:o<=e?{rating:"good",value:o,unit:"score",thresholds:{good:e,poor:t}}:o>t?{rating:"poor",value:o,unit:"score",thresholds:{good:e,poor:t}}:{rating:"needs_improvement",value:o,unit:"score",thresholds:{good:e,poor:t}}}s(hc,"rateScore");function Rs(o){return o==="needs_improvement"?"needs improvement":o==="not_available"?"not available":o}s(Rs,"formatRating");function gc(o){let e=o.ratings.lcp.rating,t=o.ratings.inp.rating,n=o.ratings.cls.rating,r=o.ratings.ttfb.rating,i=o.ratings.fcp.rating,a=e==="good"&&t==="good"&&n==="good",l=[];a?l.push("Core Web Vitals look good (LCP, INP and CLS are all within recommended thresholds)."):l.push("Core Web Vitals need attention. Focus on the worst-rated metric first (LCP, INP, or CLS).");let u=[],m=[],c=[],p=[],b=[],f=[];return o.lcpSelectorHint&&f.push(`LCP element hint (best-effort): ${o.lcpSelectorHint}`),e==="poor"||e==="needs_improvement"?(u.push("Optimize the LCP element (often the hero image, headline, or main content above the fold)."),u.push("Reduce render-blocking resources (critical CSS, JS). Consider inlining critical CSS and deferring non-critical JS."),u.push('Preload the LCP resource (e.g., <link rel="preload"> for the hero image/font) and ensure it is discoverable without heavy JS.'),u.push("Improve server response and caching. A slow TTFB often delays LCP."),u.push("Avoid client-only rendering for above-the-fold content when possible; stream/SSR critical content.")):e==="good"?u.push("LCP is within the recommended threshold. Keep the above-the-fold path lean."):u.push("LCP is not available in this browser/session. Consider using Chromium or a page-load scenario that produces LCP entries."),t==="poor"||t==="needs_improvement"?(m.push("Break up long main-thread tasks. Aim to keep tasks under ~50ms (split work, yield to the event loop)."),m.push("Reduce expensive work in input handlers (click, pointer, key events). Move non-urgent work to idle time."),m.push("Avoid synchronous layout thrash during interactions (batch DOM reads/writes, reduce forced reflow)."),m.push("Defer heavy third-party scripts and reduce JavaScript bundle size to improve responsiveness.")):t==="good"?m.push("INP is within the recommended threshold. Keep interaction handlers lightweight."):m.push("INP is not available in this browser/session. It requires Event Timing support and user interactions."),n==="poor"||n==="needs_improvement"?(c.push("Reserve space for images/iframes/ads (set width/height or aspect-ratio) to prevent layout jumps."),c.push("Avoid inserting content above existing content unless it is in response to a user interaction."),c.push("Use stable font loading (font-display: swap/optional) and consider preloading critical fonts to reduce text shifts."),c.push("Be careful with late-loading banners/toasts; render them in reserved containers.")):n==="good"?c.push("CLS is within the recommended threshold. Keep layout stable during load and async updates."):c.push("CLS is not available in this browser/session. Consider Chromium or a scenario with visible layout changes."),r==="poor"||r==="needs_improvement"?(p.push("Improve backend latency: reduce server processing time, optimize DB queries, and eliminate unnecessary middleware."),p.push("Enable CDN/edge caching where possible. Use caching headers and avoid dynamic responses for static content."),p.push("Reduce cold-start and TLS overhead (keep-alive, warm pools, edge runtimes).")):r==="good"?p.push("TTFB is good. Backend/network latency is unlikely to be the primary bottleneck."):p.push("TTFB is not available in this browser/session."),i==="poor"||i==="needs_improvement"?(b.push("Reduce render-blocking CSS/JS and prioritize critical content for first paint."),b.push("Optimize above-the-fold resources and avoid large synchronous scripts during initial load."),b.push("Consider code-splitting and preloading critical assets to improve first paint.")):i==="good"?b.push("FCP is good. The page provides early visual feedback."):b.push("FCP is not available in this browser/session."),f.push("For reliable debugging, capture metrics after navigation and after user actions that trigger loading or layout changes."),f.push("If values look unstable, try adding waitMs (e.g., 1000-3000) and re-measure after the UI settles."),{coreWebVitalsPassed:a,summary:l,lcp:u,inp:m,cls:c,ttfb:p,fcp:b,general:f}}s(gc,"buildRecommendations");var er=class{static{s(this,"GetWebVitals")}name(){return"o11y_get-web-vitals"}description(){return`
610
+ number than the last one received.`)}).describe("HTTP request item.")).describe("Retrieved HTTP requests.")}}async handle(e,t){let n=e.getHttpRequests().filter(a=>{let l=!0;return l&&t.resourceType&&(l=a.resourceType===t.resourceType),l&&t.status&&(l&&t.status.min&&(l=a.response?a.response.status>=t.status.min:!1),l&&t.status.max&&(l=a.response?a.response.status<=t.status.max:!1)),l&&t.ok!==void 0&&(l=a.ok),l&&t.timestamp&&(l=a.timestamp>=t.timestamp),l&&t.sequenceNumber&&(l=a.sequenceNumber>t.sequenceNumber),l});return{requests:(t.limit?.count?t.limit.from==="start"?n.slice(0,t.limit.count):n.slice(-t.limit.count):n).map(a=>({url:a.url,method:a.method,headers:a.headers,body:a.body,resourceType:a.resourceType,failure:a.failure,duration:a.duration,response:a.response?{status:a.response.status,statusText:a.response.statusText,headers:a.response.headers,body:a.response.body}:void 0,ok:a.ok,timestamp:a.timestamp,sequenceNumber:a.sequenceNumber}))}}};import{z as dc}from"zod";var Qo=class{static{s(this,"GetTraceId")}name(){return"o11y_get-trace-id"}description(){return"Gets the OpenTelemetry compatible trace id of the current session."}inputSchema(){return{}}outputSchema(){return{traceId:dc.string().describe("The OpenTelemetry compatible trace id of the current session if available.").optional()}}async handle(e,t){return{traceId:await e.getTraceId()}}};import{z as j}from"zod";var Ma=0,bc=3e4;function Zo(o,e,t){return typeof o!="number"||!Number.isFinite(o)?{rating:"not_available",value:null,unit:"ms",thresholds:{good:e,poor:t}}:o<=e?{rating:"good",value:o,unit:"ms",thresholds:{good:e,poor:t}}:o>t?{rating:"poor",value:o,unit:"ms",thresholds:{good:e,poor:t}}:{rating:"needs_improvement",value:o,unit:"ms",thresholds:{good:e,poor:t}}}s(Zo,"rateMs");function hc(o,e,t){return typeof o!="number"||!Number.isFinite(o)?{rating:"not_available",value:null,unit:"score",thresholds:{good:e,poor:t}}:o<=e?{rating:"good",value:o,unit:"score",thresholds:{good:e,poor:t}}:o>t?{rating:"poor",value:o,unit:"score",thresholds:{good:e,poor:t}}:{rating:"needs_improvement",value:o,unit:"score",thresholds:{good:e,poor:t}}}s(hc,"rateScore");function ks(o){return o==="needs_improvement"?"needs improvement":o==="not_available"?"not available":o}s(ks,"formatRating");function gc(o){let e=o.ratings.lcp.rating,t=o.ratings.inp.rating,n=o.ratings.cls.rating,r=o.ratings.ttfb.rating,i=o.ratings.fcp.rating,a=e==="good"&&t==="good"&&n==="good",l=[];a?l.push("Core Web Vitals look good (LCP, INP and CLS are all within recommended thresholds)."):l.push("Core Web Vitals need attention. Focus on the worst-rated metric first (LCP, INP, or CLS).");let u=[],m=[],c=[],p=[],b=[],f=[];return o.lcpSelectorHint&&f.push(`LCP element hint (best-effort): ${o.lcpSelectorHint}`),e==="poor"||e==="needs_improvement"?(u.push("Optimize the LCP element (often the hero image, headline, or main content above the fold)."),u.push("Reduce render-blocking resources (critical CSS, JS). Consider inlining critical CSS and deferring non-critical JS."),u.push('Preload the LCP resource (e.g., <link rel="preload"> for the hero image/font) and ensure it is discoverable without heavy JS.'),u.push("Improve server response and caching. A slow TTFB often delays LCP."),u.push("Avoid client-only rendering for above-the-fold content when possible; stream/SSR critical content.")):e==="good"?u.push("LCP is within the recommended threshold. Keep the above-the-fold path lean."):u.push("LCP is not available in this browser/session. Consider using Chromium or a page-load scenario that produces LCP entries."),t==="poor"||t==="needs_improvement"?(m.push("Break up long main-thread tasks. Aim to keep tasks under ~50ms (split work, yield to the event loop)."),m.push("Reduce expensive work in input handlers (click, pointer, key events). Move non-urgent work to idle time."),m.push("Avoid synchronous layout thrash during interactions (batch DOM reads/writes, reduce forced reflow)."),m.push("Defer heavy third-party scripts and reduce JavaScript bundle size to improve responsiveness.")):t==="good"?m.push("INP is within the recommended threshold. Keep interaction handlers lightweight."):m.push("INP is not available in this browser/session. It requires Event Timing support and user interactions."),n==="poor"||n==="needs_improvement"?(c.push("Reserve space for images/iframes/ads (set width/height or aspect-ratio) to prevent layout jumps."),c.push("Avoid inserting content above existing content unless it is in response to a user interaction."),c.push("Use stable font loading (font-display: swap/optional) and consider preloading critical fonts to reduce text shifts."),c.push("Be careful with late-loading banners/toasts; render them in reserved containers.")):n==="good"?c.push("CLS is within the recommended threshold. Keep layout stable during load and async updates."):c.push("CLS is not available in this browser/session. Consider Chromium or a scenario with visible layout changes."),r==="poor"||r==="needs_improvement"?(p.push("Improve backend latency: reduce server processing time, optimize DB queries, and eliminate unnecessary middleware."),p.push("Enable CDN/edge caching where possible. Use caching headers and avoid dynamic responses for static content."),p.push("Reduce cold-start and TLS overhead (keep-alive, warm pools, edge runtimes).")):r==="good"?p.push("TTFB is good. Backend/network latency is unlikely to be the primary bottleneck."):p.push("TTFB is not available in this browser/session."),i==="poor"||i==="needs_improvement"?(b.push("Reduce render-blocking CSS/JS and prioritize critical content for first paint."),b.push("Optimize above-the-fold resources and avoid large synchronous scripts during initial load."),b.push("Consider code-splitting and preloading critical assets to improve first paint.")):i==="good"?b.push("FCP is good. The page provides early visual feedback."):b.push("FCP is not available in this browser/session."),f.push("For reliable debugging, capture metrics after navigation and after user actions that trigger loading or layout changes."),f.push("If values look unstable, try adding waitMs (e.g., 1000-3000) and re-measure after the UI settles."),{coreWebVitalsPassed:a,summary:l,lcp:u,inp:m,cls:c,ttfb:p,fcp:b,general:f}}s(gc,"buildRecommendations");var er=class{static{s(this,"GetWebVitals")}name(){return"o11y_get-web-vitals"}description(){return`
611
611
  Collects Web Vitals-style performance metrics and provides recommendations based on Google's thresholds.
612
612
 
613
613
  Core Web Vitals:
@@ -623,7 +623,7 @@ Guidance:
623
623
  - Call after navigation and after user actions.
624
624
  - If you need more stable LCP/CLS/INP, pass waitMs (e.g. 1000-3000).
625
625
  - Some metrics may be unavailable depending on browser support and whether interactions occurred.
626
- `.trim()}inputSchema(){return{waitMs:j.number().int().min(0).max(bc).optional().default(Ma).describe("Optional wait duration in milliseconds before reading metrics (default: 0)."),includeDebug:j.boolean().optional().default(!1).describe("If true, returns additional debug details such as entry counts and LCP element hint.")}}outputSchema(){let e=j.object({rating:j.enum(["good","needs_improvement","poor","not_available"]).describe("Rating based on Google thresholds."),value:j.number().nullable().describe("Metric value (null if unavailable)."),unit:j.enum(["ms","score"]).describe("Unit of the metric."),thresholds:j.object({good:j.number().describe('Upper bound for the "good" rating.'),poor:j.number().describe('Lower bound for the "poor" rating.')}).describe("Thresholds used for rating.")});return{url:j.string().describe("Current page URL."),title:j.string().describe("Current page title."),timestampMs:j.number().int().describe("Unix epoch timestamp (ms) when the metrics were captured."),metrics:j.object({lcpMs:j.number().nullable().describe("Largest Contentful Paint in milliseconds."),inpMs:j.number().nullable().describe("Interaction to Next Paint in milliseconds (best-effort approximation)."),cls:j.number().nullable().describe("Cumulative Layout Shift score."),ttfbMs:j.number().nullable().describe("Time to First Byte in milliseconds."),fcpMs:j.number().nullable().describe("First Contentful Paint in milliseconds.")}).describe("Raw metric values (null if unavailable)."),ratings:j.object({lcp:e.describe("LCP rating."),inp:e.describe("INP rating."),cls:e.describe("CLS rating."),ttfb:e.describe("TTFB rating."),fcp:e.describe("FCP rating.")}).describe("Ratings computed from Google thresholds."),recommendations:j.object({coreWebVitalsPassed:j.boolean().describe('True if all Core Web Vitals are rated "good".'),summary:j.array(j.string()).describe("High-level summary and prioritization guidance."),lcp:j.array(j.string()).describe("Recommendations for improving LCP."),inp:j.array(j.string()).describe("Recommendations for improving INP."),cls:j.array(j.string()).describe("Recommendations for improving CLS."),ttfb:j.array(j.string()).describe("Recommendations for improving TTFB."),fcp:j.array(j.string()).describe("Recommendations for improving FCP."),general:j.array(j.string()).describe("General measurement and debugging notes.")}).describe("Recommendations based on the measured values and their ratings."),notes:j.array(j.string()).describe("Notes about metric availability, browser limitations, and interpretation."),debug:j.object({waitMs:j.number().int().describe("Actual wait duration used before reading metrics."),entries:j.object({navigation:j.number().int().describe("Count of navigation entries."),paint:j.number().int().describe("Count of paint entries."),lcp:j.number().int().describe("Count of largest-contentful-paint entries."),layoutShift:j.number().int().describe("Count of layout-shift entries."),eventTiming:j.number().int().describe("Count of event timing entries.")}).describe("Counts of PerformanceEntry types used to compute metrics."),lastLcpSelectorHint:j.string().nullable().describe("Best-effort selector hint for the last LCP element (if available)."),lastLcpTagName:j.string().nullable().describe("Tag name of the last LCP element (if available).")}).optional().describe("Optional debug details.")}}async handle(e,t){let n=t.waitMs??Ma,r=t.includeDebug===!0,i=String(e.page.url()),a=String(await e.page.title()),l=Date.now(),u=await e.page.evaluate(async H=>{let Q=H.waitMsEval,$=H.includeDebugEval,P=[],W=s(q=>new Promise(X=>{setTimeout(()=>X(),q)}),"sleep");Q>0&&await W(Q);let G=null,_=performance.getEntriesByType("navigation")??[];if(_.length>0){let q=_[0];typeof q.responseStart=="number"&&q.responseStart>=0&&(G=q.responseStart)}else P.push("TTFB: navigation entries not available (older browser or restricted timing).");let oe=null,Y=performance.getEntriesByType("paint")??[],M=Y.find(q=>q.name==="first-contentful-paint");M&&typeof M.startTime=="number"?oe=M.startTime:P.push("FCP: paint entries not available (browser may not support Paint Timing).");let ee=null,ue=null,ce=performance.getEntriesByType("largest-contentful-paint")??[];if(ce.length>0){let q=ce[ce.length-1];typeof q.startTime=="number"&&(ee=q.startTime),q.element&&q.element instanceof Element&&(ue=q.element)}else P.push("LCP: largest-contentful-paint entries not available (requires LCP support).");let fe=s(q=>{if(!q)return null;let X=q.getAttribute("data-testid")||q.getAttribute("data-test-id")||q.getAttribute("data-test");if(X&&X.trim())return'[data-testid="'+X.replace(/"/g,'\\"')+'"]';let Pe=q.getAttribute("data-selector");if(Pe&&Pe.trim())return'[data-selector="'+Pe.replace(/"/g,'\\"')+'"]';if(q.id)try{return"#"+CSS.escape(q.id)}catch{return"#"+String(q.id)}return q.tagName?q.tagName.toLowerCase():null},"selectorHintFor"),te=null,me=performance.getEntriesByType("layout-shift")??[];if(me.length>0){let q=0;for(let X of me)X&&X.hadRecentInput===!0||typeof X.value=="number"&&(q+=X.value);te=q}else P.push("CLS: layout-shift entries not available (requires Layout Instability API support).");let v=null,pe=performance.getEntriesByType("event")??[];if(pe.length>0){let q=0;for(let X of pe){let Pe=typeof X.interactionId=="number"?X.interactionId:0,Ie=typeof X.duration=="number"?X.duration:0;Pe>0&&Ie>q&&(q=Ie)}q>0?v=q:P.push("INP: event timing entries exist but no interactionId-based events were found.")}else P.push("INP: event timing entries not available (requires Event Timing API support).");P.length===0?P.push("All requested metrics were available."):P.push("Some metrics may be null due to browser support limitations.");let V={metrics:{ttfbMs:G,fcpMs:oe,lcpMs:ee,cls:te,inpMs:v},notes:P,lcp:{selectorHint:fe(ue),tagName:ue?String(ue.tagName).toLowerCase():null},debug:{waitMs:Q,entries:{navigation:_.length,paint:Y.length,lcp:ce.length,layoutShift:me.length,eventTiming:pe.length}}};return $?(V.debug.lastLcpSelectorHint=V.lcp.selectorHint,V.debug.lastLcpTagName=V.lcp.tagName):delete V.debug,V},{waitMsEval:n,includeDebugEval:r}),m=typeof u?.metrics?.lcpMs=="number"?u.metrics.lcpMs:null,c=typeof u?.metrics?.inpMs=="number"?u.metrics.inpMs:null,p=typeof u?.metrics?.cls=="number"?u.metrics.cls:null,b=typeof u?.metrics?.ttfbMs=="number"?u.metrics.ttfbMs:null,f=typeof u?.metrics?.fcpMs=="number"?u.metrics.fcpMs:null,x={lcp:Zo(m,2500,4e3),inp:Zo(c,200,500),cls:hc(p,.1,.25),ttfb:Zo(b,800,1800),fcp:Zo(f,1800,3e3)},B=typeof u?.lcp?.selectorHint=="string"?u.lcp.selectorHint:null,w=gc({ratings:x,lcpSelectorHint:B}),U=Array.isArray(u?.notes)?u.notes:[];U.push(`Ratings: LCP=${Rs(x.lcp.rating)}, INP=${Rs(x.inp.rating)}, CLS=${Rs(x.cls.rating)}.`);let D={url:i,title:a,timestampMs:l,metrics:{lcpMs:m,inpMs:c,cls:p,ttfbMs:b,fcpMs:f},ratings:x,recommendations:w,notes:U};return r&&u?.debug&&(D.debug=u.debug),D}};import fc from"node:crypto";function tr(){return fc.randomBytes(16).toString("hex")}s(tr,"newTraceId");import{z as yc}from"zod";var nr=class{static{s(this,"NewTraceId")}name(){return"o11y_new-trace-id"}description(){return"Generates new OpenTelemetry compatible trace id and sets it to the current session."}inputSchema(){return{}}outputSchema(){return{traceId:yc.string().describe("The generated new OpenTelemetry compatible trace id.")}}async handle(e,t){let n=tr();return await e.setTraceId(n),{traceId:n}}};import{z as wc}from"zod";var or=class{static{s(this,"SetTraceId")}name(){return"o11y_set-trace-id"}description(){return"Sets the OpenTelemetry compatible trace id of the current session."}inputSchema(){return{traceId:wc.string().describe("The OpenTelemetry compatible trace id to be set.")}}outputSchema(){return{}}async handle(e,t){return await e.setTraceId(t.traceId),{}}};var Da=[new Yo,new Jo,new Qo,new er,new nr,new or];import{z as F}from"zod";var Ba=30,Aa=2e3,La=!0,Tc=25,Sc=5e4,rr=class{static{s(this,"GetComponentForElement")}name(){return"react_get-component-for-element"}description(){return`
626
+ `.trim()}inputSchema(){return{waitMs:j.number().int().min(0).max(bc).optional().default(Ma).describe("Optional wait duration in milliseconds before reading metrics (default: 0)."),includeDebug:j.boolean().optional().default(!1).describe("If true, returns additional debug details such as entry counts and LCP element hint.")}}outputSchema(){let e=j.object({rating:j.enum(["good","needs_improvement","poor","not_available"]).describe("Rating based on Google thresholds."),value:j.number().nullable().describe("Metric value (null if unavailable)."),unit:j.enum(["ms","score"]).describe("Unit of the metric."),thresholds:j.object({good:j.number().describe('Upper bound for the "good" rating.'),poor:j.number().describe('Lower bound for the "poor" rating.')}).describe("Thresholds used for rating.")});return{url:j.string().describe("Current page URL."),title:j.string().describe("Current page title."),timestampMs:j.number().int().describe("Unix epoch timestamp (ms) when the metrics were captured."),metrics:j.object({lcpMs:j.number().nullable().describe("Largest Contentful Paint in milliseconds."),inpMs:j.number().nullable().describe("Interaction to Next Paint in milliseconds (best-effort approximation)."),cls:j.number().nullable().describe("Cumulative Layout Shift score."),ttfbMs:j.number().nullable().describe("Time to First Byte in milliseconds."),fcpMs:j.number().nullable().describe("First Contentful Paint in milliseconds.")}).describe("Raw metric values (null if unavailable)."),ratings:j.object({lcp:e.describe("LCP rating."),inp:e.describe("INP rating."),cls:e.describe("CLS rating."),ttfb:e.describe("TTFB rating."),fcp:e.describe("FCP rating.")}).describe("Ratings computed from Google thresholds."),recommendations:j.object({coreWebVitalsPassed:j.boolean().describe('True if all Core Web Vitals are rated "good".'),summary:j.array(j.string()).describe("High-level summary and prioritization guidance."),lcp:j.array(j.string()).describe("Recommendations for improving LCP."),inp:j.array(j.string()).describe("Recommendations for improving INP."),cls:j.array(j.string()).describe("Recommendations for improving CLS."),ttfb:j.array(j.string()).describe("Recommendations for improving TTFB."),fcp:j.array(j.string()).describe("Recommendations for improving FCP."),general:j.array(j.string()).describe("General measurement and debugging notes.")}).describe("Recommendations based on the measured values and their ratings."),notes:j.array(j.string()).describe("Notes about metric availability, browser limitations, and interpretation."),debug:j.object({waitMs:j.number().int().describe("Actual wait duration used before reading metrics."),entries:j.object({navigation:j.number().int().describe("Count of navigation entries."),paint:j.number().int().describe("Count of paint entries."),lcp:j.number().int().describe("Count of largest-contentful-paint entries."),layoutShift:j.number().int().describe("Count of layout-shift entries."),eventTiming:j.number().int().describe("Count of event timing entries.")}).describe("Counts of PerformanceEntry types used to compute metrics."),lastLcpSelectorHint:j.string().nullable().describe("Best-effort selector hint for the last LCP element (if available)."),lastLcpTagName:j.string().nullable().describe("Tag name of the last LCP element (if available).")}).optional().describe("Optional debug details.")}}async handle(e,t){let n=t.waitMs??Ma,r=t.includeDebug===!0,i=String(e.page.url()),a=String(await e.page.title()),l=Date.now(),u=await e.page.evaluate(async H=>{let Q=H.waitMsEval,$=H.includeDebugEval,P=[],W=s(q=>new Promise(X=>{setTimeout(()=>X(),q)}),"sleep");Q>0&&await W(Q);let G=null,_=performance.getEntriesByType("navigation")??[];if(_.length>0){let q=_[0];typeof q.responseStart=="number"&&q.responseStart>=0&&(G=q.responseStart)}else P.push("TTFB: navigation entries not available (older browser or restricted timing).");let oe=null,Y=performance.getEntriesByType("paint")??[],M=Y.find(q=>q.name==="first-contentful-paint");M&&typeof M.startTime=="number"?oe=M.startTime:P.push("FCP: paint entries not available (browser may not support Paint Timing).");let ee=null,ue=null,ce=performance.getEntriesByType("largest-contentful-paint")??[];if(ce.length>0){let q=ce[ce.length-1];typeof q.startTime=="number"&&(ee=q.startTime),q.element&&q.element instanceof Element&&(ue=q.element)}else P.push("LCP: largest-contentful-paint entries not available (requires LCP support).");let fe=s(q=>{if(!q)return null;let X=q.getAttribute("data-testid")||q.getAttribute("data-test-id")||q.getAttribute("data-test");if(X&&X.trim())return'[data-testid="'+X.replace(/"/g,'\\"')+'"]';let Pe=q.getAttribute("data-selector");if(Pe&&Pe.trim())return'[data-selector="'+Pe.replace(/"/g,'\\"')+'"]';if(q.id)try{return"#"+CSS.escape(q.id)}catch{return"#"+String(q.id)}return q.tagName?q.tagName.toLowerCase():null},"selectorHintFor"),te=null,me=performance.getEntriesByType("layout-shift")??[];if(me.length>0){let q=0;for(let X of me)X&&X.hadRecentInput===!0||typeof X.value=="number"&&(q+=X.value);te=q}else P.push("CLS: layout-shift entries not available (requires Layout Instability API support).");let v=null,pe=performance.getEntriesByType("event")??[];if(pe.length>0){let q=0;for(let X of pe){let Pe=typeof X.interactionId=="number"?X.interactionId:0,Ie=typeof X.duration=="number"?X.duration:0;Pe>0&&Ie>q&&(q=Ie)}q>0?v=q:P.push("INP: event timing entries exist but no interactionId-based events were found.")}else P.push("INP: event timing entries not available (requires Event Timing API support).");P.length===0?P.push("All requested metrics were available."):P.push("Some metrics may be null due to browser support limitations.");let V={metrics:{ttfbMs:G,fcpMs:oe,lcpMs:ee,cls:te,inpMs:v},notes:P,lcp:{selectorHint:fe(ue),tagName:ue?String(ue.tagName).toLowerCase():null},debug:{waitMs:Q,entries:{navigation:_.length,paint:Y.length,lcp:ce.length,layoutShift:me.length,eventTiming:pe.length}}};return $?(V.debug.lastLcpSelectorHint=V.lcp.selectorHint,V.debug.lastLcpTagName=V.lcp.tagName):delete V.debug,V},{waitMsEval:n,includeDebugEval:r}),m=typeof u?.metrics?.lcpMs=="number"?u.metrics.lcpMs:null,c=typeof u?.metrics?.inpMs=="number"?u.metrics.inpMs:null,p=typeof u?.metrics?.cls=="number"?u.metrics.cls:null,b=typeof u?.metrics?.ttfbMs=="number"?u.metrics.ttfbMs:null,f=typeof u?.metrics?.fcpMs=="number"?u.metrics.fcpMs:null,x={lcp:Zo(m,2500,4e3),inp:Zo(c,200,500),cls:hc(p,.1,.25),ttfb:Zo(b,800,1800),fcp:Zo(f,1800,3e3)},B=typeof u?.lcp?.selectorHint=="string"?u.lcp.selectorHint:null,w=gc({ratings:x,lcpSelectorHint:B}),U=Array.isArray(u?.notes)?u.notes:[];U.push(`Ratings: LCP=${ks(x.lcp.rating)}, INP=${ks(x.inp.rating)}, CLS=${ks(x.cls.rating)}.`);let D={url:i,title:a,timestampMs:l,metrics:{lcpMs:m,inpMs:c,cls:p,ttfbMs:b,fcpMs:f},ratings:x,recommendations:w,notes:U};return r&&u?.debug&&(D.debug=u.debug),D}};import fc from"node:crypto";function tr(){return fc.randomBytes(16).toString("hex")}s(tr,"newTraceId");import{z as yc}from"zod";var nr=class{static{s(this,"NewTraceId")}name(){return"o11y_new-trace-id"}description(){return"Generates new OpenTelemetry compatible trace id and sets it to the current session."}inputSchema(){return{}}outputSchema(){return{traceId:yc.string().describe("The generated new OpenTelemetry compatible trace id.")}}async handle(e,t){let n=tr();return await e.setTraceId(n),{traceId:n}}};import{z as wc}from"zod";var or=class{static{s(this,"SetTraceId")}name(){return"o11y_set-trace-id"}description(){return"Sets the OpenTelemetry compatible trace id of the current session."}inputSchema(){return{traceId:wc.string().describe("The OpenTelemetry compatible trace id to be set.")}}outputSchema(){return{}}async handle(e,t){return await e.setTraceId(t.traceId),{}}};var Da=[new Yo,new Jo,new Qo,new er,new nr,new or];import{z as F}from"zod";var Ba=30,Aa=2e3,La=!0,Tc=25,Sc=5e4,rr=class{static{s(this,"GetComponentForElement")}name(){return"react_get-component-for-element"}description(){return`
627
627
  Finds the React component(s) associated with a DOM element using React Fiber (best-effort).
628
628
 
629
629
  How it works:
@@ -642,7 +642,7 @@ What to expect (important for AI debugging):
642
642
  - wrappersDetected/wrapperFrames help interpret memo/forwardRef/context boundaries that can otherwise look confusing.
643
643
  - If hostMapping.strategy is "ancestor-fallback", the stack may include unrelated frames; try a more specific selector
644
644
  or target a deeper DOM node to improve mapping accuracy.
645
- `.trim()}inputSchema(){return{selector:F.string().optional().describe("CSS selector for the target element. If provided, takes precedence over x/y."),x:F.number().int().optional().describe("Viewport X coordinate in CSS pixels. Used when selector is not provided."),y:F.number().int().optional().describe("Viewport Y coordinate in CSS pixels. Used when selector is not provided."),maxStackDepth:F.number().int().positive().optional().default(Ba).describe("Maximum number of component frames to return in the component stack."),includePropsPreview:F.boolean().optional().default(La).describe("If true, includes a best-effort, truncated props preview for the nearest component."),maxPropsPreviewChars:F.number().int().positive().optional().default(Aa).describe("Maximum characters for props preview (after safe stringification).")}}outputSchema(){return{target:F.object({selector:F.string().nullable(),point:F.object({x:F.number().int().nullable(),y:F.number().int().nullable()}),found:F.boolean(),domHint:F.string().nullable(),elementPath:F.string().nullable()}),react:F.object({detected:F.boolean(),detectionReason:F.string(),fiberKey:F.string().nullable(),hostMapping:F.object({fiberOnTargetElement:F.boolean().describe("Whether the initial fiber pointer was found directly on the target element."),anchorDomHint:F.string().nullable().describe("DOM hint of the element where fiber pointer was found (target or ancestor)."),targetDomHint:F.string().nullable().describe("DOM hint of the actual target element."),hostFiberMatchedTarget:F.boolean().describe("Whether we found the exact host fiber for target element (fiber.stateNode === targetEl) via subtree scan."),subtreeScanNodesScanned:F.number().int().describe("Number of fiber nodes scanned during subtree search."),subtreeScanMaxNodes:F.number().int().describe("Maximum fiber nodes allowed to scan (safety cap)."),strategy:F.enum(["direct-on-target","ancestor-subtree-scan","ancestor-fallback"]).describe("Mapping strategy used to produce the final stack.")}),nearestComponent:F.object({name:F.string().nullable(),displayName:F.string().nullable(),kind:F.enum(["function","class","unknown"]),debugSource:F.object({fileName:F.string().optional(),lineNumber:F.number().int().optional(),columnNumber:F.number().int().optional()}).optional(),propsPreview:F.string().optional()}).nullable(),componentStack:F.array(F.object({name:F.string().nullable(),displayName:F.string().nullable(),kind:F.enum(["function","class","unknown"]),debugSource:F.object({fileName:F.string().optional(),lineNumber:F.number().int().optional(),columnNumber:F.number().int().optional()}).optional()})),componentStackText:F.string(),wrappersDetected:F.array(F.string()),wrapperFrames:F.array(F.object({wrapper:F.string(),frameIndex:F.number().int(),frameLabel:F.string()})),notes:F.array(F.string())})}}async handle(e,t){let n=typeof t.selector=="string"&&t.selector.trim()?t.selector.trim():void 0,r=typeof t.x=="number"&&Number.isFinite(t.x)?Math.floor(t.x):void 0,i=typeof t.y=="number"&&Number.isFinite(t.y)?Math.floor(t.y):void 0;if(!n&&(typeof r!="number"||typeof i!="number"))throw new Error("Provide either selector, or both x and y for elementFromPoint.");let a=typeof t.maxStackDepth=="number"&&t.maxStackDepth>0?Math.floor(t.maxStackDepth):Ba,l=t.includePropsPreview===void 0?La:t.includePropsPreview===!0,u=typeof t.maxPropsPreviewChars=="number"&&Number.isFinite(t.maxPropsPreviewChars)&&t.maxPropsPreviewChars>0?Math.floor(t.maxPropsPreviewChars):Aa;return await e.page.evaluate(c=>{let p=c.selectorEval,b=c.xEval,f=c.yEval,x=c.maxStackDepthEval,B=c.includePropsPreviewEval,w=c.maxPropsPreviewCharsEval,U=c.maxElementPathDepthEval,D=c.maxFiberNodesToScanEval,H=[];function Q(g){if(!g)return null;let C=g.tagName.toLowerCase(),I=g.id&&g.id.trim()?"#"+g.id.trim():"",R=typeof g.className=="string"?g.className:"",A=R?"."+R.trim().split(/\s+/).slice(0,4).join("."):"";return C+I+A}s(Q,"domHint");function $(g,C){if(!g)return null;let I=[],R=g,A=0;for(;R&&A<C;){let L=R.tagName?R.tagName.toLowerCase():"unknown",Z=R.id&&R.id.trim()?"#"+R.id.trim():"",ie=typeof R.className=="string"?R.className:"",de=ie?ie.trim().split(/\s+/).filter(Boolean).slice(0,3):[],Ee=de.length>0?"."+de.join("."):"",Ge="";try{let Mt=R.parentElement;if(Mt){let mn=Array.from(Mt.children).filter(Dt=>Dt.tagName===R.tagName);if(mn.length>1){let Dt=mn.indexOf(R)+1;Dt>0&&(Ge=`:nth-of-type(${Dt})`)}}}catch{}I.push(`${L}${Z}${Ee}${Ge}`),R=R.parentElement,A++}return I.reverse(),I.join(" > ")}s($,"buildElementPath");function P(g){if(!g)return null;let C=Object.getOwnPropertyNames(g);for(let I of C)if(I.startsWith("__reactFiber$")||I.startsWith("__reactInternalInstance$"))return I;return null}s(P,"findFiberKeyOn");function W(g){if(!g)return null;let C=P(g);if(C){let R=g[C];if(R)return{fiber:R,fiberKey:C,onTarget:!0,anchorEl:g}}let I=g;for(;I;){let R=P(I);if(R){let A=I[R];if(A)return{fiber:A,fiberKey:R,onTarget:!1,anchorEl:I}}I=I.parentElement}return null}s(W,"findFiberForElement");function G(g,C,I){if(!g)return{hostFiber:null,scanned:0,found:!1};if(g.stateNode===C)return{hostFiber:g,scanned:1,found:!0};let R=[],A=new Set;R.push(g),A.add(g);let L=0;for(;R.length>0;){let Z=R.shift();if(L++,Z&&Z.stateNode===C)return{hostFiber:Z,scanned:L,found:!0};if(L>=I)return{hostFiber:null,scanned:L,found:!1};let ie=Z?Z.child:null;ie&&!A.has(ie)&&(A.add(ie),R.push(ie));let de=Z?Z.sibling:null;de&&!A.has(de)&&(A.add(de),R.push(de))}return{hostFiber:null,scanned:L,found:!1}}s(G,"findHostFiberForDomElement");function _(g){if(!g)return!1;let C=g.prototype;return!!(C&&C.isReactComponent)}s(_,"isClassComponentType");function oe(g){if(!g)return null;if(typeof g=="function"){let C=g.displayName;return typeof C=="string"&&C.trim()?C.trim():typeof g.name=="string"&&g.name.trim()?g.name.trim():"Anonymous"}if(typeof g=="object"){let C=g.displayName;if(typeof C=="string"&&C.trim())return C.trim();let I=g.render;if(typeof I=="function"){let R=I.displayName;return typeof R=="string"&&R.trim()?R.trim():typeof I.name=="string"&&I.name.trim()?I.name.trim():"Anonymous"}}return null}s(oe,"typeDisplayName");function Y(g){if(!g)return null;if(typeof g=="function")return typeof g.name=="string"&&g.name.trim()?g.name.trim():null;if(typeof g=="object"){let C=g.render;return typeof C=="function"&&typeof C.name=="string"&&C.name.trim()?C.name.trim():null}return null}s(Y,"typeName");function M(g){if(!g)return g;if(typeof g=="object"){let C=g.render;if(typeof C=="function")return C}return g}s(M,"unwrapType");function ee(g){return g?typeof M(g.type??g.elementType)=="function":!1}s(ee,"isMeaningfulComponentFiber");function ue(g){if(!g)return"unknown";let C=M(g.type??g.elementType);return typeof C=="function"?_(C)?"class":"function":"unknown"}s(ue,"inferKind");function ce(g){let C=g?g._debugSource:void 0;if(!C||typeof C!="object")return;let I={};return typeof C.fileName=="string"&&(I.fileName=C.fileName),typeof C.lineNumber=="number"&&(I.lineNumber=C.lineNumber),typeof C.columnNumber=="number"&&(I.columnNumber=C.columnNumber),Object.keys(I).length>0?I:void 0}s(ce,"getDebugSource");function fe(g,C){let I=new WeakSet;function R(L,Z){if(L===null)return null;let ie=typeof L;if(ie==="string")return L.length>500?L.slice(0,500)+"\u2026":L;if(ie==="number"||ie==="boolean")return L;if(ie==="bigint")return String(L);if(ie!=="undefined"){if(ie==="function")return"[function]";if(ie==="symbol")return String(L);if(ie==="object"){if(L instanceof Element)return"[Element "+(L.tagName?L.tagName.toLowerCase():"")+"]";if(L instanceof Window)return"[Window]";if(L instanceof Document)return"[Document]";if(L instanceof Date)return L.toISOString();if(I.has(L))return"[circular]";if(I.add(L),Array.isArray(L))return Z<=0?"[array len="+L.length+"]":L.slice(0,20).map(Ge=>R(Ge,Z-1));if(Z<=0)return"[object]";let de={},Ee=Object.keys(L).slice(0,40);for(let Ge of Ee)try{de[Ge]=R(L[Ge],Z-1)}catch{de[Ge]="[unreadable]"}return de}return String(L)}}s(R,"helper");let A="";try{A=JSON.stringify(R(g,2))}catch{try{A=String(g)}catch{A="[unserializable]"}}return A.length>C?A.slice(0,C)+"\u2026(truncated)":A}s(fe,"safeStringify");function te(g){return g.map(I=>{let R=I?.displayName,A=I?.name;return typeof R=="string"&&R.trim()?R.trim():typeof A=="string"&&A.trim()?A.trim():"Anonymous"}).filter(I=>!!I).reverse().join(" > ")}s(te,"stackTextFromFrames");function me(g){let C=M(g.type??g.elementType),I=Y(C),R=oe(C),A=ue(g),L=ce(g),Z={name:I,displayName:R,kind:A};return L&&(Z.debugSource=L),Z}s(me,"frameFromFiber");function v(g){let C=g.displayName?g.displayName:"",I=g.name?g.name:"",R=g.debugSource,A=R&&typeof R=="object"?`${String(R.fileName??"")}:${String(R.lineNumber??"")}:${String(R.columnNumber??"")}`:"";return`${C}|${I}|${g.kind}|${A}`}s(v,"makeFrameKey");function pe(g){let C=[],I=null;for(let R of g){let A=v(R);I&&A===I||(C.push(R),I=A)}return C}s(pe,"collapseConsecutiveDuplicates");function V(g){let C=new Set;function I(A){let L=A.trim().toLowerCase();L&&C.add(L)}s(I,"canonicalAdd");for(let A of g){let L=typeof A.displayName=="string"&&A.displayName.trim()?A.displayName.trim():typeof A.name=="string"&&A.name.trim()?A.name.trim():"";if(!L)continue;let Z=L.toLowerCase();/^memo(\(|$)/i.test(L)&&I("memo"),Z.includes("forwardref")&&I("forwardref"),Z.includes(".provider")&&I("context-provider"),Z.includes(".consumer")&&I("context-consumer"),Z.includes("suspense")&&I("suspense"),Z.includes("fragment")&&I("fragment"),Z.includes("strictmode")&&I("strictmode"),Z.includes("profiler")&&I("profiler")}let R=Array.from(C);return R.sort((A,L)=>A<L?-1:A>L?1:0),R}s(V,"detectWrappers");function q(g,C){let I=[],R=new Set(C.map(A=>A.toLowerCase()));for(let A=0;A<g.length;A++){let L=g[A],Z=L.displayName&&L.displayName.trim()?L.displayName.trim():L.name&&L.name.trim()?L.name.trim():"Anonymous",ie=Z.toLowerCase();for(let de of R){let Ee=!1;de==="memo"?Ee=/^memo(\(|$)/i.test(Z):de==="forwardref"?Ee=ie.includes("forwardref"):de==="context-provider"?Ee=ie.includes(".provider"):de==="context-consumer"?Ee=ie.includes(".consumer"):de==="suspense"?Ee=ie.includes("suspense"):de==="fragment"?Ee=ie.includes("fragment"):de==="strictmode"?Ee=ie.includes("strictmode"):de==="profiler"&&(Ee=ie.includes("profiler")),Ee&&I.push({wrapper:de,frameIndex:A,frameLabel:Z})}}return I}s(q,"findWrapperFrames");let X=null;if(p&&p.trim())try{X=document.querySelector(p)}catch{X=null}else typeof b=="number"&&typeof f=="number"&&(X=document.elementFromPoint(b,f));let Pe=!!X,Ie=Q(X),ft=$(X,U);if(!Pe)return{target:{selector:p??null,point:{x:typeof b=="number"?b:null,y:typeof f=="number"?f:null},found:!1,domHint:null,elementPath:null},react:{detected:!1,detectionReason:"Target element not found.",fiberKey:null,hostMapping:{fiberOnTargetElement:!1,anchorDomHint:null,targetDomHint:null,hostFiberMatchedTarget:!1,subtreeScanNodesScanned:0,subtreeScanMaxNodes:D,strategy:"ancestor-fallback"},nearestComponent:null,componentStack:[],componentStackText:"",wrappersDetected:[],wrapperFrames:[],notes:["No DOM element could be resolved; cannot inspect React."]}};let J=W(X);if(!J)return H.push("No React fiber pointer found on the element or its ancestors."),H.push("This can happen if the page is not React, uses a different renderer, or runs with hardened/minified internals."),{target:{selector:p??null,point:{x:typeof b=="number"?b:null,y:typeof f=="number"?f:null},found:!0,domHint:Ie,elementPath:ft},react:{detected:!1,detectionReason:"React fiber not found on element/ancestors.",fiberKey:null,hostMapping:{fiberOnTargetElement:!1,anchorDomHint:null,targetDomHint:Ie,hostFiberMatchedTarget:!1,subtreeScanNodesScanned:0,subtreeScanMaxNodes:D,strategy:"ancestor-fallback"},nearestComponent:null,componentStack:[],componentStackText:"",wrappersDetected:[],wrapperFrames:[],notes:H}};let Ce=J.fiber,We=J.onTarget,Le=0,un=Q(J.anchorEl),qe="direct-on-target";if(!J.onTarget){qe="ancestor-fallback";let g=G(J.fiber,X,D);Le=g.scanned,g.found&&g.hostFiber?(Ce=g.hostFiber,We=!0,qe="ancestor-subtree-scan",H.push(`Mapped target DOM element to host fiber by scanning fiber subtree (scanned=${Le}).`)):(We=!1,H.push(`Could not find exact host fiber for the target element in the ancestor fiber subtree (scanned=${Le}). Falling back to ancestor fiber stack; some frames may be unrelated.`))}let Wt={fiberOnTargetElement:J.onTarget,anchorDomHint:un,targetDomHint:Ie,hostFiberMatchedTarget:We,subtreeScanNodesScanned:Le,subtreeScanMaxNodes:D,strategy:qe},ct=null,Rt=Ce;for(;Rt;){if(ee(Rt)){ct=Rt;break}Rt=Rt.return??null}ct||H.push("Fiber was found, but no meaningful function/class component was detected in the return chain.");let qt=[],cn=new Set,mt=ct;for(;mt&&qt.length<x;){if(cn.has(mt)){H.push("Detected a cycle in fiber.return chain; stopping stack traversal.");break}cn.add(mt),ee(mt)&&qt.push(me(mt)),mt=mt.return??null}let $t=qt.length>0?pe(qt):[],Zr=te($t),jt=V($t),es=q($t,jt);jt.length>=3&&H.push(`Wrapper-heavy stack detected (${jt.join(", ")}). Interpreting nearestComponent may require skipping wrappers.`);let kt=null;if(ct&&(kt=me(ct),B))try{let g=ct.memoizedProps;g!==void 0?kt.propsPreview=fe(g,w):H.push("memoizedProps not available on nearest component fiber.")}catch{H.push("Failed to read memoizedProps for nearest component (best-effort).")}return H.push("React Fiber inspection uses non-public internals; fields are best-effort."),H.push("Component names may come from displayName, wrappers, third-party libraries, or minified production builds."),qe==="ancestor-fallback"&&H.push("Host mapping fallback was used; consider selecting a deeper/more specific DOM element for a more accurate component stack."),{target:{selector:p??null,point:{x:typeof b=="number"?b:null,y:typeof f=="number"?f:null},found:!0,domHint:Ie,elementPath:ft},react:{detected:!0,detectionReason:qe==="direct-on-target"?"React fiber found on the target element.":qe==="ancestor-subtree-scan"?"React fiber found on an ancestor; exact host fiber located via subtree scan.":"React fiber found on an ancestor; exact host fiber not found, stack may include unrelated frames.",fiberKey:J.fiberKey,hostMapping:Wt,nearestComponent:kt,componentStack:$t,componentStackText:Zr,wrappersDetected:jt,wrapperFrames:es,notes:H}}},{selectorEval:n??null,xEval:typeof r=="number"?r:null,yEval:typeof i=="number"?i:null,maxStackDepthEval:a,includePropsPreviewEval:l,maxPropsPreviewCharsEval:u,maxElementPathDepthEval:Tc,maxFiberNodesToScanEval:Sc})}};import{z as O}from"zod";var Fa="contains",Ua=200,Ha=!0,Wa=!0,qa=80,$a=5,xc=50,vc=20,Ic=25e4,sr=class{static{s(this,"GetElementForComponent")}name(){return"react_get-element-for-component"}description(){return`
645
+ `.trim()}inputSchema(){return{selector:F.string().optional().describe("CSS selector for the target element. If provided, takes precedence over x/y."),x:F.number().int().optional().describe("Viewport X coordinate in CSS pixels. Used when selector is not provided."),y:F.number().int().optional().describe("Viewport Y coordinate in CSS pixels. Used when selector is not provided."),maxStackDepth:F.number().int().positive().optional().default(Ba).describe("Maximum number of component frames to return in the component stack."),includePropsPreview:F.boolean().optional().default(La).describe("If true, includes a best-effort, truncated props preview for the nearest component."),maxPropsPreviewChars:F.number().int().positive().optional().default(Aa).describe("Maximum characters for props preview (after safe stringification).")}}outputSchema(){return{target:F.object({selector:F.string().nullable(),point:F.object({x:F.number().int().nullable(),y:F.number().int().nullable()}),found:F.boolean(),domHint:F.string().nullable(),elementPath:F.string().nullable()}),react:F.object({detected:F.boolean(),detectionReason:F.string(),fiberKey:F.string().nullable(),hostMapping:F.object({fiberOnTargetElement:F.boolean().describe("Whether the initial fiber pointer was found directly on the target element."),anchorDomHint:F.string().nullable().describe("DOM hint of the element where fiber pointer was found (target or ancestor)."),targetDomHint:F.string().nullable().describe("DOM hint of the actual target element."),hostFiberMatchedTarget:F.boolean().describe("Whether we found the exact host fiber for target element (fiber.stateNode === targetEl) via subtree scan."),subtreeScanNodesScanned:F.number().int().describe("Number of fiber nodes scanned during subtree search."),subtreeScanMaxNodes:F.number().int().describe("Maximum fiber nodes allowed to scan (safety cap)."),strategy:F.enum(["direct-on-target","ancestor-subtree-scan","ancestor-fallback"]).describe("Mapping strategy used to produce the final stack.")}),nearestComponent:F.object({name:F.string().nullable(),displayName:F.string().nullable(),kind:F.enum(["function","class","unknown"]),debugSource:F.object({fileName:F.string().optional(),lineNumber:F.number().int().optional(),columnNumber:F.number().int().optional()}).optional(),propsPreview:F.string().optional()}).nullable(),componentStack:F.array(F.object({name:F.string().nullable(),displayName:F.string().nullable(),kind:F.enum(["function","class","unknown"]),debugSource:F.object({fileName:F.string().optional(),lineNumber:F.number().int().optional(),columnNumber:F.number().int().optional()}).optional()})),componentStackText:F.string(),wrappersDetected:F.array(F.string()),wrapperFrames:F.array(F.object({wrapper:F.string(),frameIndex:F.number().int(),frameLabel:F.string()})),notes:F.array(F.string())})}}async handle(e,t){let n=typeof t.selector=="string"&&t.selector.trim()?t.selector.trim():void 0,r=typeof t.x=="number"&&Number.isFinite(t.x)?Math.floor(t.x):void 0,i=typeof t.y=="number"&&Number.isFinite(t.y)?Math.floor(t.y):void 0;if(!n&&(typeof r!="number"||typeof i!="number"))throw new Error("Provide either selector, or both x and y for elementFromPoint.");let a=typeof t.maxStackDepth=="number"&&t.maxStackDepth>0?Math.floor(t.maxStackDepth):Ba,l=t.includePropsPreview===void 0?La:t.includePropsPreview===!0,u=typeof t.maxPropsPreviewChars=="number"&&Number.isFinite(t.maxPropsPreviewChars)&&t.maxPropsPreviewChars>0?Math.floor(t.maxPropsPreviewChars):Aa;return await e.page.evaluate(c=>{let p=c.selectorEval,b=c.xEval,f=c.yEval,x=c.maxStackDepthEval,B=c.includePropsPreviewEval,w=c.maxPropsPreviewCharsEval,U=c.maxElementPathDepthEval,D=c.maxFiberNodesToScanEval,H=[];function Q(g){if(!g)return null;let C=g.tagName.toLowerCase(),I=g.id&&g.id.trim()?"#"+g.id.trim():"",k=typeof g.className=="string"?g.className:"",A=k?"."+k.trim().split(/\s+/).slice(0,4).join("."):"";return C+I+A}s(Q,"domHint");function $(g,C){if(!g)return null;let I=[],k=g,A=0;for(;k&&A<C;){let L=k.tagName?k.tagName.toLowerCase():"unknown",Z=k.id&&k.id.trim()?"#"+k.id.trim():"",ie=typeof k.className=="string"?k.className:"",de=ie?ie.trim().split(/\s+/).filter(Boolean).slice(0,3):[],Ee=de.length>0?"."+de.join("."):"",Ge="";try{let Mt=k.parentElement;if(Mt){let mn=Array.from(Mt.children).filter(Dt=>Dt.tagName===k.tagName);if(mn.length>1){let Dt=mn.indexOf(k)+1;Dt>0&&(Ge=`:nth-of-type(${Dt})`)}}}catch{}I.push(`${L}${Z}${Ee}${Ge}`),k=k.parentElement,A++}return I.reverse(),I.join(" > ")}s($,"buildElementPath");function P(g){if(!g)return null;let C=Object.getOwnPropertyNames(g);for(let I of C)if(I.startsWith("__reactFiber$")||I.startsWith("__reactInternalInstance$"))return I;return null}s(P,"findFiberKeyOn");function W(g){if(!g)return null;let C=P(g);if(C){let k=g[C];if(k)return{fiber:k,fiberKey:C,onTarget:!0,anchorEl:g}}let I=g;for(;I;){let k=P(I);if(k){let A=I[k];if(A)return{fiber:A,fiberKey:k,onTarget:!1,anchorEl:I}}I=I.parentElement}return null}s(W,"findFiberForElement");function G(g,C,I){if(!g)return{hostFiber:null,scanned:0,found:!1};if(g.stateNode===C)return{hostFiber:g,scanned:1,found:!0};let k=[],A=new Set;k.push(g),A.add(g);let L=0;for(;k.length>0;){let Z=k.shift();if(L++,Z&&Z.stateNode===C)return{hostFiber:Z,scanned:L,found:!0};if(L>=I)return{hostFiber:null,scanned:L,found:!1};let ie=Z?Z.child:null;ie&&!A.has(ie)&&(A.add(ie),k.push(ie));let de=Z?Z.sibling:null;de&&!A.has(de)&&(A.add(de),k.push(de))}return{hostFiber:null,scanned:L,found:!1}}s(G,"findHostFiberForDomElement");function _(g){if(!g)return!1;let C=g.prototype;return!!(C&&C.isReactComponent)}s(_,"isClassComponentType");function oe(g){if(!g)return null;if(typeof g=="function"){let C=g.displayName;return typeof C=="string"&&C.trim()?C.trim():typeof g.name=="string"&&g.name.trim()?g.name.trim():"Anonymous"}if(typeof g=="object"){let C=g.displayName;if(typeof C=="string"&&C.trim())return C.trim();let I=g.render;if(typeof I=="function"){let k=I.displayName;return typeof k=="string"&&k.trim()?k.trim():typeof I.name=="string"&&I.name.trim()?I.name.trim():"Anonymous"}}return null}s(oe,"typeDisplayName");function Y(g){if(!g)return null;if(typeof g=="function")return typeof g.name=="string"&&g.name.trim()?g.name.trim():null;if(typeof g=="object"){let C=g.render;return typeof C=="function"&&typeof C.name=="string"&&C.name.trim()?C.name.trim():null}return null}s(Y,"typeName");function M(g){if(!g)return g;if(typeof g=="object"){let C=g.render;if(typeof C=="function")return C}return g}s(M,"unwrapType");function ee(g){return g?typeof M(g.type??g.elementType)=="function":!1}s(ee,"isMeaningfulComponentFiber");function ue(g){if(!g)return"unknown";let C=M(g.type??g.elementType);return typeof C=="function"?_(C)?"class":"function":"unknown"}s(ue,"inferKind");function ce(g){let C=g?g._debugSource:void 0;if(!C||typeof C!="object")return;let I={};return typeof C.fileName=="string"&&(I.fileName=C.fileName),typeof C.lineNumber=="number"&&(I.lineNumber=C.lineNumber),typeof C.columnNumber=="number"&&(I.columnNumber=C.columnNumber),Object.keys(I).length>0?I:void 0}s(ce,"getDebugSource");function fe(g,C){let I=new WeakSet;function k(L,Z){if(L===null)return null;let ie=typeof L;if(ie==="string")return L.length>500?L.slice(0,500)+"\u2026":L;if(ie==="number"||ie==="boolean")return L;if(ie==="bigint")return String(L);if(ie!=="undefined"){if(ie==="function")return"[function]";if(ie==="symbol")return String(L);if(ie==="object"){if(L instanceof Element)return"[Element "+(L.tagName?L.tagName.toLowerCase():"")+"]";if(L instanceof Window)return"[Window]";if(L instanceof Document)return"[Document]";if(L instanceof Date)return L.toISOString();if(I.has(L))return"[circular]";if(I.add(L),Array.isArray(L))return Z<=0?"[array len="+L.length+"]":L.slice(0,20).map(Ge=>k(Ge,Z-1));if(Z<=0)return"[object]";let de={},Ee=Object.keys(L).slice(0,40);for(let Ge of Ee)try{de[Ge]=k(L[Ge],Z-1)}catch{de[Ge]="[unreadable]"}return de}return String(L)}}s(k,"helper");let A="";try{A=JSON.stringify(k(g,2))}catch{try{A=String(g)}catch{A="[unserializable]"}}return A.length>C?A.slice(0,C)+"\u2026(truncated)":A}s(fe,"safeStringify");function te(g){return g.map(I=>{let k=I?.displayName,A=I?.name;return typeof k=="string"&&k.trim()?k.trim():typeof A=="string"&&A.trim()?A.trim():"Anonymous"}).filter(I=>!!I).reverse().join(" > ")}s(te,"stackTextFromFrames");function me(g){let C=M(g.type??g.elementType),I=Y(C),k=oe(C),A=ue(g),L=ce(g),Z={name:I,displayName:k,kind:A};return L&&(Z.debugSource=L),Z}s(me,"frameFromFiber");function v(g){let C=g.displayName?g.displayName:"",I=g.name?g.name:"",k=g.debugSource,A=k&&typeof k=="object"?`${String(k.fileName??"")}:${String(k.lineNumber??"")}:${String(k.columnNumber??"")}`:"";return`${C}|${I}|${g.kind}|${A}`}s(v,"makeFrameKey");function pe(g){let C=[],I=null;for(let k of g){let A=v(k);I&&A===I||(C.push(k),I=A)}return C}s(pe,"collapseConsecutiveDuplicates");function V(g){let C=new Set;function I(A){let L=A.trim().toLowerCase();L&&C.add(L)}s(I,"canonicalAdd");for(let A of g){let L=typeof A.displayName=="string"&&A.displayName.trim()?A.displayName.trim():typeof A.name=="string"&&A.name.trim()?A.name.trim():"";if(!L)continue;let Z=L.toLowerCase();/^memo(\(|$)/i.test(L)&&I("memo"),Z.includes("forwardref")&&I("forwardref"),Z.includes(".provider")&&I("context-provider"),Z.includes(".consumer")&&I("context-consumer"),Z.includes("suspense")&&I("suspense"),Z.includes("fragment")&&I("fragment"),Z.includes("strictmode")&&I("strictmode"),Z.includes("profiler")&&I("profiler")}let k=Array.from(C);return k.sort((A,L)=>A<L?-1:A>L?1:0),k}s(V,"detectWrappers");function q(g,C){let I=[],k=new Set(C.map(A=>A.toLowerCase()));for(let A=0;A<g.length;A++){let L=g[A],Z=L.displayName&&L.displayName.trim()?L.displayName.trim():L.name&&L.name.trim()?L.name.trim():"Anonymous",ie=Z.toLowerCase();for(let de of k){let Ee=!1;de==="memo"?Ee=/^memo(\(|$)/i.test(Z):de==="forwardref"?Ee=ie.includes("forwardref"):de==="context-provider"?Ee=ie.includes(".provider"):de==="context-consumer"?Ee=ie.includes(".consumer"):de==="suspense"?Ee=ie.includes("suspense"):de==="fragment"?Ee=ie.includes("fragment"):de==="strictmode"?Ee=ie.includes("strictmode"):de==="profiler"&&(Ee=ie.includes("profiler")),Ee&&I.push({wrapper:de,frameIndex:A,frameLabel:Z})}}return I}s(q,"findWrapperFrames");let X=null;if(p&&p.trim())try{X=document.querySelector(p)}catch{X=null}else typeof b=="number"&&typeof f=="number"&&(X=document.elementFromPoint(b,f));let Pe=!!X,Ie=Q(X),ft=$(X,U);if(!Pe)return{target:{selector:p??null,point:{x:typeof b=="number"?b:null,y:typeof f=="number"?f:null},found:!1,domHint:null,elementPath:null},react:{detected:!1,detectionReason:"Target element not found.",fiberKey:null,hostMapping:{fiberOnTargetElement:!1,anchorDomHint:null,targetDomHint:null,hostFiberMatchedTarget:!1,subtreeScanNodesScanned:0,subtreeScanMaxNodes:D,strategy:"ancestor-fallback"},nearestComponent:null,componentStack:[],componentStackText:"",wrappersDetected:[],wrapperFrames:[],notes:["No DOM element could be resolved; cannot inspect React."]}};let J=W(X);if(!J)return H.push("No React fiber pointer found on the element or its ancestors."),H.push("This can happen if the page is not React, uses a different renderer, or runs with hardened/minified internals."),{target:{selector:p??null,point:{x:typeof b=="number"?b:null,y:typeof f=="number"?f:null},found:!0,domHint:Ie,elementPath:ft},react:{detected:!1,detectionReason:"React fiber not found on element/ancestors.",fiberKey:null,hostMapping:{fiberOnTargetElement:!1,anchorDomHint:null,targetDomHint:Ie,hostFiberMatchedTarget:!1,subtreeScanNodesScanned:0,subtreeScanMaxNodes:D,strategy:"ancestor-fallback"},nearestComponent:null,componentStack:[],componentStackText:"",wrappersDetected:[],wrapperFrames:[],notes:H}};let Ce=J.fiber,We=J.onTarget,Le=0,un=Q(J.anchorEl),qe="direct-on-target";if(!J.onTarget){qe="ancestor-fallback";let g=G(J.fiber,X,D);Le=g.scanned,g.found&&g.hostFiber?(Ce=g.hostFiber,We=!0,qe="ancestor-subtree-scan",H.push(`Mapped target DOM element to host fiber by scanning fiber subtree (scanned=${Le}).`)):(We=!1,H.push(`Could not find exact host fiber for the target element in the ancestor fiber subtree (scanned=${Le}). Falling back to ancestor fiber stack; some frames may be unrelated.`))}let Wt={fiberOnTargetElement:J.onTarget,anchorDomHint:un,targetDomHint:Ie,hostFiberMatchedTarget:We,subtreeScanNodesScanned:Le,subtreeScanMaxNodes:D,strategy:qe},ct=null,kt=Ce;for(;kt;){if(ee(kt)){ct=kt;break}kt=kt.return??null}ct||H.push("Fiber was found, but no meaningful function/class component was detected in the return chain.");let qt=[],cn=new Set,mt=ct;for(;mt&&qt.length<x;){if(cn.has(mt)){H.push("Detected a cycle in fiber.return chain; stopping stack traversal.");break}cn.add(mt),ee(mt)&&qt.push(me(mt)),mt=mt.return??null}let $t=qt.length>0?pe(qt):[],Zr=te($t),jt=V($t),es=q($t,jt);jt.length>=3&&H.push(`Wrapper-heavy stack detected (${jt.join(", ")}). Interpreting nearestComponent may require skipping wrappers.`);let Rt=null;if(ct&&(Rt=me(ct),B))try{let g=ct.memoizedProps;g!==void 0?Rt.propsPreview=fe(g,w):H.push("memoizedProps not available on nearest component fiber.")}catch{H.push("Failed to read memoizedProps for nearest component (best-effort).")}return H.push("React Fiber inspection uses non-public internals; fields are best-effort."),H.push("Component names may come from displayName, wrappers, third-party libraries, or minified production builds."),qe==="ancestor-fallback"&&H.push("Host mapping fallback was used; consider selecting a deeper/more specific DOM element for a more accurate component stack."),{target:{selector:p??null,point:{x:typeof b=="number"?b:null,y:typeof f=="number"?f:null},found:!0,domHint:Ie,elementPath:ft},react:{detected:!0,detectionReason:qe==="direct-on-target"?"React fiber found on the target element.":qe==="ancestor-subtree-scan"?"React fiber found on an ancestor; exact host fiber located via subtree scan.":"React fiber found on an ancestor; exact host fiber not found, stack may include unrelated frames.",fiberKey:J.fiberKey,hostMapping:Wt,nearestComponent:Rt,componentStack:$t,componentStackText:Zr,wrappersDetected:jt,wrapperFrames:es,notes:H}}},{selectorEval:n??null,xEval:typeof r=="number"?r:null,yEval:typeof i=="number"?i:null,maxStackDepthEval:a,includePropsPreviewEval:l,maxPropsPreviewCharsEval:u,maxElementPathDepthEval:Tc,maxFiberNodesToScanEval:Sc})}};import{z as O}from"zod";var Fa="contains",Ua=200,Ha=!0,Wa=!0,qa=80,$a=5,xc=50,vc=20,Ic=25e4,sr=class{static{s(this,"GetElementForComponent")}name(){return"react_get-element-for-component"}description(){return`
646
646
  Maps a React COMPONENT INSTANCE to the DOM elements it renders (its "DOM footprint") by traversing the React Fiber graph.
647
647
 
648
648
  Selection strategy:
@@ -660,7 +660,7 @@ Important behavior:
660
660
  Operational note for MCP users:
661
661
  - If you are using a persistent/headful browser and want more reliable root discovery and component search,
662
662
  install the "React Developer Tools" Chrome extension in that browser profile (manual step by the user).
663
- `.trim()}inputSchema(){return{anchorSelector:O.string().optional().describe("DOM CSS selector used as an anchor to pick a concrete component instance near that element."),anchorX:O.number().int().nonnegative().optional().describe("Anchor X coordinate (viewport pixels)."),anchorY:O.number().int().nonnegative().optional().describe("Anchor Y coordinate (viewport pixels)."),componentName:O.string().optional().describe("React component name/displayName to search in the Fiber graph."),matchStrategy:O.enum(["exact","contains"]).optional().default(Fa).describe("How to match componentName against Fiber type/displayName."),fileNameHint:O.string().optional().describe('Best-effort debug source file hint (usually endsWith match), e.g., "UserCard.tsx".'),lineNumber:O.number().int().positive().optional().describe("Optional debug source line number hint (dev builds only)."),maxElements:O.number().int().positive().optional().default(Ua).describe("Maximum number of DOM elements to return from the selected component subtree."),onlyVisible:O.boolean().optional().default(Ha).describe("If true, only visually visible elements are returned."),onlyInViewport:O.boolean().optional().default(Wa).describe("If true, only elements intersecting the viewport are returned."),textPreviewMaxLength:O.number().int().positive().optional().default(qa).describe("Max length for per-element text preview (innerText/textContent/aria-label)."),maxMatches:O.number().int().positive().optional().default($a).describe("Max number of matching component candidates to return/rank.")}}outputSchema(){return{reactDetected:O.boolean().describe("True if __REACT_DEVTOOLS_GLOBAL_HOOK__ looks available."),fiberDetected:O.boolean().describe("True if DOM appears to contain React Fiber pointers (__reactFiber$...)."),rootDiscovery:O.enum(["devtools-hook","dom-fiber-scan","none"]).describe("How roots were discovered."),component:O.object({name:O.string().nullable(),displayName:O.string().nullable(),debugSource:O.object({fileName:O.string().nullable(),lineNumber:O.number().int().nullable(),columnNumber:O.number().int().nullable()}).nullable(),componentStack:O.array(O.string()),selection:O.enum(["anchor","query","query+anchor","unknown"]),scoring:O.object({score:O.number(),nameMatched:O.boolean(),debugSourceMatched:O.boolean(),anchorRelated:O.boolean(),proximityPx:O.number().nullable().optional()}).optional()}).nullable(),candidates:O.array(O.object({name:O.string().nullable(),displayName:O.string().nullable(),debugSource:O.object({fileName:O.string().nullable(),lineNumber:O.number().int().nullable(),columnNumber:O.number().int().nullable()}).nullable(),componentStack:O.array(O.string()),selection:O.enum(["anchor","query","query+anchor","unknown"]),scoring:O.object({score:O.number(),nameMatched:O.boolean(),debugSourceMatched:O.boolean(),anchorRelated:O.boolean(),proximityPx:O.number().nullable().optional()}).optional(),domFootprintCount:O.number().int()})).describe("Ranked candidate matches (best-first)."),elements:O.array(O.object({tagName:O.string(),id:O.string().nullable(),className:O.string().nullable(),selectorHint:O.string().nullable(),textPreview:O.string().nullable(),boundingBox:O.object({x:O.number(),y:O.number(),width:O.number(),height:O.number()}).nullable(),isVisible:O.boolean(),isInViewport:O.boolean()})),notes:O.array(O.string())}}async handle(e,t){let n=t.anchorSelector,r=t.anchorX,i=t.anchorY,a=t.componentName,l=t.matchStrategy??Fa,u=t.fileNameHint,m=t.lineNumber,c=t.maxElements??Ua,p=t.onlyVisible??Ha,b=t.onlyInViewport??Wa,f=t.textPreviewMaxLength??qa,x=t.maxMatches??$a,B=typeof n=="string"&&n.trim().length>0,w=typeof r=="number"&&typeof i=="number",U=typeof a=="string"&&a.trim().length>0||typeof u=="string"&&u.trim().length>0||typeof m=="number";if(!B&&!w&&!U)throw new Error("Provide at least one targeting method: anchorSelector, (anchorX+anchorY), or componentName/debugSource hints.");return await e.page.evaluate(H=>{let Q=H.anchorSelectorEval,$=H.anchorXEval,P=H.anchorYEval,W=H.componentNameEval,G=H.matchStrategyEval,_=H.fileNameHintEval,oe=H.lineNumberEval,Y=H.maxElementsEval,M=H.onlyVisibleEval,ee=H.onlyInViewportEval,ue=H.textPreviewMaxLengthEval,ce=H.maxMatchesEval,fe=H.maxRootsScan,te=H.maxFibersVisited,me=H.stackLimit,v=[];function pe(h){return typeof Element<"u"&&h instanceof Element}s(pe,"isElement");function V(h){if(typeof h!="string")return null;let d=h.trim();return d||null}s(V,"normalizeStr");function q(h){let d=h,S=Object.keys(d);for(let E of S)if(E.startsWith("__reactFiber$")){let k=d[E];if(k)return k}for(let E of S)if(E.startsWith("__reactInternalInstance$")){let k=d[E];if(k)return k}return null}s(q,"getFiberFromDomElement");function X(){let d=globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__;return!d||typeof d.getFiberRoots!="function"?null:d}s(X,"getDevtoolsHook");function Pe(h){let d=[],S=h.renderers;return!S||typeof S.forEach!="function"?d:(S.forEach((E,k)=>{try{let z=h.getFiberRoots(k);z&&typeof z.forEach=="function"&&z.forEach(se=>{se&&d.push(se)})}catch{}}),d.slice(0,fe))}s(Pe,"getAllRootsFromHook");function Ie(h){let d=[],S=Array.from(document.querySelectorAll("*")),E=S.length>5e3?Math.ceil(S.length/5e3):1;for(let k=0;k<S.length;k+=E){let z=S[k],se=q(z);if(se&&(d.push(se),d.length>=h))break}return d}s(Ie,"getSeedFibersFromDomScan");function ft(h){if(typeof h!="function")return null;let d=h,S=V(d.displayName);if(S)return S;let E=V(d.name);return E||null}s(ft,"getFunctionDisplayName");function J(h){if(!h)return null;let d=h.type??h.elementType??null;if(!d)return null;if(typeof d=="function")return ft(d);if(typeof d=="string")return d;let S=V(d.displayName);return S||V(d.name)}s(J,"getFiberTypeName");function Ce(h){if(!h)return null;let d=h.type??h.elementType??null;if(!d)return null;let S=V(d.displayName);return S||J(h)}s(Ce,"getDisplayName");function We(h){let d=new Set,S=[],E=s(k=>{k&&(d.has(k)||(d.add(k),S.push(k)))},"push");E(h),E(h?.alternate);for(let k=0;k<8;k++){let z=S[k];if(!z)break;E(z?._debugOwner),E(z?._debugOwner?.alternate)}for(let k of S){let z=k?._debugSource??k?._debugOwner?._debugSource??k?.type?._debugSource??k?.elementType?._debugSource??null;if(!z)continue;let se=V(z.fileName)??null,ye=typeof z.lineNumber=="number"?z.lineNumber:null,Fe=typeof z.columnNumber=="number"?z.columnNumber:null;if(se||ye!==null||Fe!==null)return{fileName:se,lineNumber:ye,columnNumber:Fe}}return null}s(We,"getDebugSource");function Le(h){let d=h?.stateNode;return pe(d)}s(Le,"isHostFiber");function un(h,d){let S=[],E=h??null;for(let z=0;z<d&&E;z++){let se=Ce(E),ye=Le(E);se&&!ye&&S.push(se),E=E.return??null}if(S.length===0){E=h??null;for(let z=0;z<d&&E;z++){let se=Ce(E);se&&S.push(se),E=E.return??null}}let k=[];for(let z of S)(k.length===0||k[k.length-1]!==z)&&k.push(z);return k}s(un,"buildComponentStack");function qe(h){let d=h??null,S=new Set;for(;d;){let E=d.alternate??d;if(S.has(E))break;if(S.add(E),!Le(d))return d;d=d.return??null}return null}s(qe,"firstMeaningfulComponentAbove");function Wt(h,d,S){if(!h)return!1;let E=h.trim(),k=d.trim();return!E||!k?!1:S==="exact"?E===k:E.toLowerCase().includes(k.toLowerCase())}s(Wt,"matchesName");function ct(h,d,S){let E=We(h);if(!E)return!1;if(d){let k=d.trim();if(k){let z=(E.fileName??"").trim();if(!z)return!1;let se=z.toLowerCase(),ye=k.toLowerCase();if(!(se.endsWith(ye)||se.includes(ye)))return!1}}return!(typeof S=="number"&&(E.lineNumber===null||Math.abs(E.lineNumber-S)>3))}s(ct,"matchesDebugSource");function Rt(h){if(!h)return null;let d=h.current;return d?d.child??d:h}s(Rt,"toStartFiber");function qt(h,d,S){if(h&&h.trim()){let E=document.querySelector(h);return E||(v.push(`anchorSelector did not match any element: ${h}`),null)}if(typeof d=="number"&&typeof S=="number"){let E=document.elementFromPoint(d,S);return E||(v.push(`anchorPoint did not hit any element: (${d}, ${S})`),null)}return null}s(qt,"pickAnchorElement");function cn(h){let d=V(h.getAttribute("data-testid"))??V(h.getAttribute("data-test-id"))??V(h.getAttribute("data-test"))??null;if(d)return`[data-testid='${d.replace(/'/g,"\\'")}']`;let S=V(h.getAttribute("data-selector"))??null;if(S)return`[data-selector='${S.replace(/'/g,"\\'")}']`;if(h.id)try{return`#${CSS.escape(h.id)}`}catch{return`#${h.id}`}return h.tagName.toLowerCase()}s(cn,"selectorHintFor");function mt(h,d){let S=V(h.getAttribute("aria-label"))??null;if(S)return S.slice(0,d);let E=String(h.innerText??h.textContent??"").trim();return E?E.slice(0,d):null}s(mt,"textPreviewFor");function $t(h){let d=h.getBoundingClientRect(),S=getComputedStyle(h),E=S.display!=="none"&&S.visibility!=="hidden"&&parseFloat(S.opacity||"1")>0&&d.width>0&&d.height>0,k=window.innerWidth,z=window.innerHeight,se=d.right>0&&d.bottom>0&&d.left<k&&d.top<z,ye=Number.isFinite(d.x)&&Number.isFinite(d.y)&&Number.isFinite(d.width)&&Number.isFinite(d.height)?{x:d.x,y:d.y,width:d.width,height:d.height}:null,Fe=d.left+d.width/2,Te=d.top+d.height/2;return{boundingBox:ye,isVisible:E,isInViewport:se,centerX:Fe,centerY:Te}}s($t,"computeRuntime");function Zr(h,d,S,E,k){let z=[],se=new Set,ye=[];h&&ye.push(h);let Fe=new Set;for(;ye.length>0&&!(z.length>=d);){let Te=ye.pop();if(!Te)continue;let tt=Te.alternate??Te;if(Fe.has(tt))continue;if(Fe.add(tt),Le(Te)){let he=Te.stateNode;if(!se.has(he)){se.add(he);let _e=$t(he);if(!(S&&!_e.isVisible)){if(!(E&&!_e.isInViewport)){let nt=he.tagName.toLowerCase(),At=he.id?String(he.id):null,Ke=he.className,ot=typeof Ke=="string"&&Ke.trim()?Ke.trim():null;z.push({tagName:nt,id:At,className:ot,selectorHint:cn(he),textPreview:mt(he,k),boundingBox:_e.boundingBox,isVisible:_e.isVisible,isInViewport:_e.isInViewport})}}}}let yt=Te.child??null,Bt=Te.sibling??null;yt&&ye.push(yt),Bt&&ye.push(Bt)}return z}s(Zr,"collectDomElementsFromFiberSubtree");function jt(h,d,S){let E=d.componentName?d.componentName.trim():void 0,k=!!E,z=d.fileNameHint?d.fileNameHint.trim():void 0,se=!!z,ye=typeof d.lineNumber=="number";if(!(k||se||ye))return[];let Te=[];for(let he of h){let _e=Rt(he);_e&&Te.push(_e)}let tt=new Set,yt=[],Bt=0;for(;Te.length>0&&!(yt.length>=S);){let he=Te.pop();if(!he)continue;let _e=he.alternate??he;if(tt.has(_e))continue;if(tt.add(_e),Bt++,Bt>te){v.push(`Fiber traversal safety cap reached (${te}). Results may be incomplete.`);break}let nt=Ce(he),At=J(he),Ke=k?Wt(nt,E,d.matchStrategy)||Wt(At,E,d.matchStrategy):!0,ot=se||ye?ct(he,z,d.lineNumber):!0;Ke&&ot&&yt.push(he);let Lt=he.child??null,Me=he.sibling??null;Lt&&Te.push(Lt),Me&&Te.push(Me)}return yt}s(jt,"findFibersByQuery");function es(h,d,S,E,k,z,se,ye,Fe){let Te=k.componentName?k.componentName.trim():void 0,tt=!!Te,yt=Ce(h),Bt=J(h),he=tt?Wt(yt,Te,k.matchStrategy)||Wt(Bt,Te,k.matchStrategy):!1,_e=V(k.fileNameHint)||typeof k.lineNumber=="number"?ct(h,V(k.fileNameHint)??void 0,typeof k.lineNumber=="number"?k.lineNumber:void 0):!1,nt=Zr(h,z,se,ye,Fe),At=!1,Ke=null;if(d){let Lt=cn(d);if(At=nt.some(Me=>!Me.selectorHint||!Lt?!1:Me.selectorHint===Lt)||nt.some(Me=>{if(!Me.boundingBox)return!1;let $e=d.getBoundingClientRect(),wt=Me.boundingBox;return $e.left<wt.x+wt.width&&$e.left+$e.width>wt.x&&$e.top<wt.y+wt.height&&$e.top+$e.height>wt.y}),typeof S=="number"&&typeof E=="number"&&nt.length>0){let Me=null;for(let $e of nt){if(!$e.boundingBox)continue;let wt=$e.boundingBox.x+$e.boundingBox.width/2,qs=$e.boundingBox.y+$e.boundingBox.height/2,$s=wt-S,js=qs-E,ns=Math.sqrt($s*$s+js*js);(Me===null||ns<Me)&&(Me=ns)}Ke=Me}}let ot=0;if(ot+=he?3:0,ot+=_e?3:0,ot+=At?2:0,ot+=Math.min(1.5,nt.length/25),typeof Ke=="number"&&Number.isFinite(Ke)){let Lt=Math.max(0,Math.min(1,1-Ke/1e3));ot+=1.5*Lt}return{score:ot,nameMatched:he,debugSourceMatched:_e,anchorRelated:At,proximityPx:Ke,dom:nt}}s(es,"scoreCandidate");let kt=X(),_t=!!kt;_t?v.push("React DevTools hook detected. Root discovery will use getFiberRoots() (more reliable)."):(v.push("React DevTools hook was not detected (__REACT_DEVTOOLS_GLOBAL_HOOK__)."),v.push('If you are using a persistent/headful browser profile, install the "React Developer Tools" Chrome extension in that profile (manual step by the user) to enable reliable root discovery and component search.'));let g=(()=>{let h=document.body;return h?!!(q(h)||Ie(1).length>0):!1})();g?v.push("React Fiber pointers detected on DOM nodes. Anchor-based mapping may still work without the DevTools hook (best-effort)."):v.push("No React Fiber pointers were detected on DOM nodes (__reactFiber$...). This can happen if the page is not React, React has not rendered yet, or internals are unavailable.");let C=qt(Q,$,P),I=null;if(C){let h=q(C);if(h){let d=h,S=h.alternate??null,E=d;S&&(S.child||S.sibling)&&!(d.child||d.sibling)&&(E=S);let k=qe(E);k?I=k:v.push("Anchor fiber found but no meaningful component fiber was found above it.")}else v.push("Anchor element found but React fiber was not found on it.")}let R=[],A="none";if(kt){let h=Pe(kt);h.length>0&&(R=h,A="devtools-hook")}if(R.length===0&&g){let h=Ie(10);h.length>0&&(R=h,A="dom-fiber-scan",v.push("Using DOM fiber scan as fallback root discovery (best-effort)."))}let L=!!V(W)||!!V(_)||typeof oe=="number",Z={componentName:V(W)??void 0,matchStrategy:G,fileNameHint:V(_)??void 0,lineNumber:typeof oe=="number"?oe:void 0},ie=[];L&&(R.length>0?ie=jt(R,Z,Math.max(1,Math.floor(ce))):v.push("Query was provided but no roots could be discovered. Provide an anchorSelector/anchorX+anchorY so we can map via DOM fiber pointers."));let de=[];I&&de.push(I);for(let h of ie)de.push(h);let Ee=[],Ge=new Set;for(let h of de){let d=h?.alternate??h;h&&!Ge.has(d)&&(Ge.add(d),Ee.push(h))}if(Ee.length===0)return _t||v.push("No candidates found. Without the DevTools hook, component search may be unreliable unless you provide a strong anchor."),{reactDetected:_t,fiberDetected:g,rootDiscovery:A,component:null,candidates:[],elements:[],notes:[...v,"Failed to select a target component fiber. Provide a better anchor, or ensure React is present and render has happened."]};let Mt=[];for(let h of Ee){let d=es(h,C,$,P,Z,Y,M,ee,ue),S="unknown",E=I?(I.alternate??I)===(h.alternate??h):!1,k=ie.some(tt=>(tt.alternate??tt)===(h.alternate??h));E&&k?S="query+anchor":E?S="anchor":k?S="query":S="unknown";let z=J(h),se=Ce(h),ye=We(h),Fe=un(h,me),Te={name:z,displayName:se,debugSource:ye,componentStack:Fe,selection:S,scoring:{score:d.score,nameMatched:d.nameMatched,debugSourceMatched:d.debugSourceMatched,anchorRelated:d.anchorRelated,proximityPx:d.proximityPx}};Mt.push({fiber:h,meta:Te,dom:d.dom,domFootprintCount:d.dom.length})}Mt.sort((h,d)=>(d.meta.scoring?.score??0)-(h.meta.scoring?.score??0));let mn=Mt[0],Dt=Mt.slice(0,Math.max(1,Math.floor(ce))).map(h=>({...h.meta,domFootprintCount:h.domFootprintCount})),ts=mn.dom;return L&&(Z.fileNameHint||typeof Z.lineNumber=="number")&&(Dt.some(d=>!!(d.debugSource?.fileName||d.debugSource?.lineNumber!==null))||(v.push("debugSource hints were provided, but no _debugSource information was found on matched fibers. This is common in production builds and some dev toolchains."),v.push('React DevTools may still display "Rendered by <file>:<line>" using sourcemaps/stack traces even when fiber._debugSource is null.'))),ts.length>=Y&&v.push(`Element list was truncated at maxElements=${Y}. Increase maxElements if needed.`),ts.length===0&&v.push("No DOM elements were returned for the selected component. It may render no host elements, or filtering (onlyVisible/onlyInViewport) removed them."),!_t&&g?v.push("React DevTools hook was not detected, but DOM fiber pointers were found. Using DOM-fiber scanning and anchor-based mapping (best-effort)."):!_t&&!g&&v.push("React DevTools hook was not detected and no DOM fiber pointers were found. Component-to-DOM mapping is unavailable on this page."),{reactDetected:_t,fiberDetected:g,rootDiscovery:A,component:mn.meta,candidates:Dt,elements:ts,notes:[...v,"Component metadata is best-effort. Wrappers (memo/forwardRef/HOCs), Suspense/Offscreen, and portals may make names/stacks noisy."]}},{anchorSelectorEval:typeof n=="string"&&n.trim()?n.trim():void 0,anchorXEval:typeof r=="number"&&Number.isFinite(r)?Math.floor(r):void 0,anchorYEval:typeof i=="number"&&Number.isFinite(i)?Math.floor(i):void 0,componentNameEval:typeof a=="string"&&a.trim()?a.trim():void 0,matchStrategyEval:l,fileNameHintEval:typeof u=="string"&&u.trim()?u.trim():void 0,lineNumberEval:typeof m=="number"&&Number.isFinite(m)?Math.floor(m):void 0,maxElementsEval:Math.max(1,Math.floor(c)),onlyVisibleEval:!!p,onlyInViewportEval:!!b,textPreviewMaxLengthEval:Math.max(1,Math.floor(f)),maxMatchesEval:Math.max(1,Math.floor(x)),maxRootsScan:vc,maxFibersVisited:Ic,stackLimit:xc})}};var ja=[new rr,new sr];import{z as za}from"zod";var ir=class{static{s(this,"JsInBrowser")}name(){return"run_js-in-browser"}description(){return`
663
+ `.trim()}inputSchema(){return{anchorSelector:O.string().optional().describe("DOM CSS selector used as an anchor to pick a concrete component instance near that element."),anchorX:O.number().int().nonnegative().optional().describe("Anchor X coordinate (viewport pixels)."),anchorY:O.number().int().nonnegative().optional().describe("Anchor Y coordinate (viewport pixels)."),componentName:O.string().optional().describe("React component name/displayName to search in the Fiber graph."),matchStrategy:O.enum(["exact","contains"]).optional().default(Fa).describe("How to match componentName against Fiber type/displayName."),fileNameHint:O.string().optional().describe('Best-effort debug source file hint (usually endsWith match), e.g., "UserCard.tsx".'),lineNumber:O.number().int().positive().optional().describe("Optional debug source line number hint (dev builds only)."),maxElements:O.number().int().positive().optional().default(Ua).describe("Maximum number of DOM elements to return from the selected component subtree."),onlyVisible:O.boolean().optional().default(Ha).describe("If true, only visually visible elements are returned."),onlyInViewport:O.boolean().optional().default(Wa).describe("If true, only elements intersecting the viewport are returned."),textPreviewMaxLength:O.number().int().positive().optional().default(qa).describe("Max length for per-element text preview (innerText/textContent/aria-label)."),maxMatches:O.number().int().positive().optional().default($a).describe("Max number of matching component candidates to return/rank.")}}outputSchema(){return{reactDetected:O.boolean().describe("True if __REACT_DEVTOOLS_GLOBAL_HOOK__ looks available."),fiberDetected:O.boolean().describe("True if DOM appears to contain React Fiber pointers (__reactFiber$...)."),rootDiscovery:O.enum(["devtools-hook","dom-fiber-scan","none"]).describe("How roots were discovered."),component:O.object({name:O.string().nullable(),displayName:O.string().nullable(),debugSource:O.object({fileName:O.string().nullable(),lineNumber:O.number().int().nullable(),columnNumber:O.number().int().nullable()}).nullable(),componentStack:O.array(O.string()),selection:O.enum(["anchor","query","query+anchor","unknown"]),scoring:O.object({score:O.number(),nameMatched:O.boolean(),debugSourceMatched:O.boolean(),anchorRelated:O.boolean(),proximityPx:O.number().nullable().optional()}).optional()}).nullable(),candidates:O.array(O.object({name:O.string().nullable(),displayName:O.string().nullable(),debugSource:O.object({fileName:O.string().nullable(),lineNumber:O.number().int().nullable(),columnNumber:O.number().int().nullable()}).nullable(),componentStack:O.array(O.string()),selection:O.enum(["anchor","query","query+anchor","unknown"]),scoring:O.object({score:O.number(),nameMatched:O.boolean(),debugSourceMatched:O.boolean(),anchorRelated:O.boolean(),proximityPx:O.number().nullable().optional()}).optional(),domFootprintCount:O.number().int()})).describe("Ranked candidate matches (best-first)."),elements:O.array(O.object({tagName:O.string(),id:O.string().nullable(),className:O.string().nullable(),selectorHint:O.string().nullable(),textPreview:O.string().nullable(),boundingBox:O.object({x:O.number(),y:O.number(),width:O.number(),height:O.number()}).nullable(),isVisible:O.boolean(),isInViewport:O.boolean()})),notes:O.array(O.string())}}async handle(e,t){let n=t.anchorSelector,r=t.anchorX,i=t.anchorY,a=t.componentName,l=t.matchStrategy??Fa,u=t.fileNameHint,m=t.lineNumber,c=t.maxElements??Ua,p=t.onlyVisible??Ha,b=t.onlyInViewport??Wa,f=t.textPreviewMaxLength??qa,x=t.maxMatches??$a,B=typeof n=="string"&&n.trim().length>0,w=typeof r=="number"&&typeof i=="number",U=typeof a=="string"&&a.trim().length>0||typeof u=="string"&&u.trim().length>0||typeof m=="number";if(!B&&!w&&!U)throw new Error("Provide at least one targeting method: anchorSelector, (anchorX+anchorY), or componentName/debugSource hints.");return await e.page.evaluate(H=>{let Q=H.anchorSelectorEval,$=H.anchorXEval,P=H.anchorYEval,W=H.componentNameEval,G=H.matchStrategyEval,_=H.fileNameHintEval,oe=H.lineNumberEval,Y=H.maxElementsEval,M=H.onlyVisibleEval,ee=H.onlyInViewportEval,ue=H.textPreviewMaxLengthEval,ce=H.maxMatchesEval,fe=H.maxRootsScan,te=H.maxFibersVisited,me=H.stackLimit,v=[];function pe(h){return typeof Element<"u"&&h instanceof Element}s(pe,"isElement");function V(h){if(typeof h!="string")return null;let d=h.trim();return d||null}s(V,"normalizeStr");function q(h){let d=h,S=Object.keys(d);for(let E of S)if(E.startsWith("__reactFiber$")){let R=d[E];if(R)return R}for(let E of S)if(E.startsWith("__reactInternalInstance$")){let R=d[E];if(R)return R}return null}s(q,"getFiberFromDomElement");function X(){let d=globalThis.__REACT_DEVTOOLS_GLOBAL_HOOK__;return!d||typeof d.getFiberRoots!="function"?null:d}s(X,"getDevtoolsHook");function Pe(h){let d=[],S=h.renderers;return!S||typeof S.forEach!="function"?d:(S.forEach((E,R)=>{try{let z=h.getFiberRoots(R);z&&typeof z.forEach=="function"&&z.forEach(se=>{se&&d.push(se)})}catch{}}),d.slice(0,fe))}s(Pe,"getAllRootsFromHook");function Ie(h){let d=[],S=Array.from(document.querySelectorAll("*")),E=S.length>5e3?Math.ceil(S.length/5e3):1;for(let R=0;R<S.length;R+=E){let z=S[R],se=q(z);if(se&&(d.push(se),d.length>=h))break}return d}s(Ie,"getSeedFibersFromDomScan");function ft(h){if(typeof h!="function")return null;let d=h,S=V(d.displayName);if(S)return S;let E=V(d.name);return E||null}s(ft,"getFunctionDisplayName");function J(h){if(!h)return null;let d=h.type??h.elementType??null;if(!d)return null;if(typeof d=="function")return ft(d);if(typeof d=="string")return d;let S=V(d.displayName);return S||V(d.name)}s(J,"getFiberTypeName");function Ce(h){if(!h)return null;let d=h.type??h.elementType??null;if(!d)return null;let S=V(d.displayName);return S||J(h)}s(Ce,"getDisplayName");function We(h){let d=new Set,S=[],E=s(R=>{R&&(d.has(R)||(d.add(R),S.push(R)))},"push");E(h),E(h?.alternate);for(let R=0;R<8;R++){let z=S[R];if(!z)break;E(z?._debugOwner),E(z?._debugOwner?.alternate)}for(let R of S){let z=R?._debugSource??R?._debugOwner?._debugSource??R?.type?._debugSource??R?.elementType?._debugSource??null;if(!z)continue;let se=V(z.fileName)??null,ye=typeof z.lineNumber=="number"?z.lineNumber:null,Fe=typeof z.columnNumber=="number"?z.columnNumber:null;if(se||ye!==null||Fe!==null)return{fileName:se,lineNumber:ye,columnNumber:Fe}}return null}s(We,"getDebugSource");function Le(h){let d=h?.stateNode;return pe(d)}s(Le,"isHostFiber");function un(h,d){let S=[],E=h??null;for(let z=0;z<d&&E;z++){let se=Ce(E),ye=Le(E);se&&!ye&&S.push(se),E=E.return??null}if(S.length===0){E=h??null;for(let z=0;z<d&&E;z++){let se=Ce(E);se&&S.push(se),E=E.return??null}}let R=[];for(let z of S)(R.length===0||R[R.length-1]!==z)&&R.push(z);return R}s(un,"buildComponentStack");function qe(h){let d=h??null,S=new Set;for(;d;){let E=d.alternate??d;if(S.has(E))break;if(S.add(E),!Le(d))return d;d=d.return??null}return null}s(qe,"firstMeaningfulComponentAbove");function Wt(h,d,S){if(!h)return!1;let E=h.trim(),R=d.trim();return!E||!R?!1:S==="exact"?E===R:E.toLowerCase().includes(R.toLowerCase())}s(Wt,"matchesName");function ct(h,d,S){let E=We(h);if(!E)return!1;if(d){let R=d.trim();if(R){let z=(E.fileName??"").trim();if(!z)return!1;let se=z.toLowerCase(),ye=R.toLowerCase();if(!(se.endsWith(ye)||se.includes(ye)))return!1}}return!(typeof S=="number"&&(E.lineNumber===null||Math.abs(E.lineNumber-S)>3))}s(ct,"matchesDebugSource");function kt(h){if(!h)return null;let d=h.current;return d?d.child??d:h}s(kt,"toStartFiber");function qt(h,d,S){if(h&&h.trim()){let E=document.querySelector(h);return E||(v.push(`anchorSelector did not match any element: ${h}`),null)}if(typeof d=="number"&&typeof S=="number"){let E=document.elementFromPoint(d,S);return E||(v.push(`anchorPoint did not hit any element: (${d}, ${S})`),null)}return null}s(qt,"pickAnchorElement");function cn(h){let d=V(h.getAttribute("data-testid"))??V(h.getAttribute("data-test-id"))??V(h.getAttribute("data-test"))??null;if(d)return`[data-testid='${d.replace(/'/g,"\\'")}']`;let S=V(h.getAttribute("data-selector"))??null;if(S)return`[data-selector='${S.replace(/'/g,"\\'")}']`;if(h.id)try{return`#${CSS.escape(h.id)}`}catch{return`#${h.id}`}return h.tagName.toLowerCase()}s(cn,"selectorHintFor");function mt(h,d){let S=V(h.getAttribute("aria-label"))??null;if(S)return S.slice(0,d);let E=String(h.innerText??h.textContent??"").trim();return E?E.slice(0,d):null}s(mt,"textPreviewFor");function $t(h){let d=h.getBoundingClientRect(),S=getComputedStyle(h),E=S.display!=="none"&&S.visibility!=="hidden"&&parseFloat(S.opacity||"1")>0&&d.width>0&&d.height>0,R=window.innerWidth,z=window.innerHeight,se=d.right>0&&d.bottom>0&&d.left<R&&d.top<z,ye=Number.isFinite(d.x)&&Number.isFinite(d.y)&&Number.isFinite(d.width)&&Number.isFinite(d.height)?{x:d.x,y:d.y,width:d.width,height:d.height}:null,Fe=d.left+d.width/2,Te=d.top+d.height/2;return{boundingBox:ye,isVisible:E,isInViewport:se,centerX:Fe,centerY:Te}}s($t,"computeRuntime");function Zr(h,d,S,E,R){let z=[],se=new Set,ye=[];h&&ye.push(h);let Fe=new Set;for(;ye.length>0&&!(z.length>=d);){let Te=ye.pop();if(!Te)continue;let tt=Te.alternate??Te;if(Fe.has(tt))continue;if(Fe.add(tt),Le(Te)){let he=Te.stateNode;if(!se.has(he)){se.add(he);let _e=$t(he);if(!(S&&!_e.isVisible)){if(!(E&&!_e.isInViewport)){let nt=he.tagName.toLowerCase(),At=he.id?String(he.id):null,Ke=he.className,ot=typeof Ke=="string"&&Ke.trim()?Ke.trim():null;z.push({tagName:nt,id:At,className:ot,selectorHint:cn(he),textPreview:mt(he,R),boundingBox:_e.boundingBox,isVisible:_e.isVisible,isInViewport:_e.isInViewport})}}}}let yt=Te.child??null,Bt=Te.sibling??null;yt&&ye.push(yt),Bt&&ye.push(Bt)}return z}s(Zr,"collectDomElementsFromFiberSubtree");function jt(h,d,S){let E=d.componentName?d.componentName.trim():void 0,R=!!E,z=d.fileNameHint?d.fileNameHint.trim():void 0,se=!!z,ye=typeof d.lineNumber=="number";if(!(R||se||ye))return[];let Te=[];for(let he of h){let _e=kt(he);_e&&Te.push(_e)}let tt=new Set,yt=[],Bt=0;for(;Te.length>0&&!(yt.length>=S);){let he=Te.pop();if(!he)continue;let _e=he.alternate??he;if(tt.has(_e))continue;if(tt.add(_e),Bt++,Bt>te){v.push(`Fiber traversal safety cap reached (${te}). Results may be incomplete.`);break}let nt=Ce(he),At=J(he),Ke=R?Wt(nt,E,d.matchStrategy)||Wt(At,E,d.matchStrategy):!0,ot=se||ye?ct(he,z,d.lineNumber):!0;Ke&&ot&&yt.push(he);let Lt=he.child??null,Me=he.sibling??null;Lt&&Te.push(Lt),Me&&Te.push(Me)}return yt}s(jt,"findFibersByQuery");function es(h,d,S,E,R,z,se,ye,Fe){let Te=R.componentName?R.componentName.trim():void 0,tt=!!Te,yt=Ce(h),Bt=J(h),he=tt?Wt(yt,Te,R.matchStrategy)||Wt(Bt,Te,R.matchStrategy):!1,_e=V(R.fileNameHint)||typeof R.lineNumber=="number"?ct(h,V(R.fileNameHint)??void 0,typeof R.lineNumber=="number"?R.lineNumber:void 0):!1,nt=Zr(h,z,se,ye,Fe),At=!1,Ke=null;if(d){let Lt=cn(d);if(At=nt.some(Me=>!Me.selectorHint||!Lt?!1:Me.selectorHint===Lt)||nt.some(Me=>{if(!Me.boundingBox)return!1;let $e=d.getBoundingClientRect(),wt=Me.boundingBox;return $e.left<wt.x+wt.width&&$e.left+$e.width>wt.x&&$e.top<wt.y+wt.height&&$e.top+$e.height>wt.y}),typeof S=="number"&&typeof E=="number"&&nt.length>0){let Me=null;for(let $e of nt){if(!$e.boundingBox)continue;let wt=$e.boundingBox.x+$e.boundingBox.width/2,qs=$e.boundingBox.y+$e.boundingBox.height/2,$s=wt-S,js=qs-E,ns=Math.sqrt($s*$s+js*js);(Me===null||ns<Me)&&(Me=ns)}Ke=Me}}let ot=0;if(ot+=he?3:0,ot+=_e?3:0,ot+=At?2:0,ot+=Math.min(1.5,nt.length/25),typeof Ke=="number"&&Number.isFinite(Ke)){let Lt=Math.max(0,Math.min(1,1-Ke/1e3));ot+=1.5*Lt}return{score:ot,nameMatched:he,debugSourceMatched:_e,anchorRelated:At,proximityPx:Ke,dom:nt}}s(es,"scoreCandidate");let Rt=X(),_t=!!Rt;_t?v.push("React DevTools hook detected. Root discovery will use getFiberRoots() (more reliable)."):(v.push("React DevTools hook was not detected (__REACT_DEVTOOLS_GLOBAL_HOOK__)."),v.push('If you are using a persistent/headful browser profile, install the "React Developer Tools" Chrome extension in that profile (manual step by the user) to enable reliable root discovery and component search.'));let g=(()=>{let h=document.body;return h?!!(q(h)||Ie(1).length>0):!1})();g?v.push("React Fiber pointers detected on DOM nodes. Anchor-based mapping may still work without the DevTools hook (best-effort)."):v.push("No React Fiber pointers were detected on DOM nodes (__reactFiber$...). This can happen if the page is not React, React has not rendered yet, or internals are unavailable.");let C=qt(Q,$,P),I=null;if(C){let h=q(C);if(h){let d=h,S=h.alternate??null,E=d;S&&(S.child||S.sibling)&&!(d.child||d.sibling)&&(E=S);let R=qe(E);R?I=R:v.push("Anchor fiber found but no meaningful component fiber was found above it.")}else v.push("Anchor element found but React fiber was not found on it.")}let k=[],A="none";if(Rt){let h=Pe(Rt);h.length>0&&(k=h,A="devtools-hook")}if(k.length===0&&g){let h=Ie(10);h.length>0&&(k=h,A="dom-fiber-scan",v.push("Using DOM fiber scan as fallback root discovery (best-effort)."))}let L=!!V(W)||!!V(_)||typeof oe=="number",Z={componentName:V(W)??void 0,matchStrategy:G,fileNameHint:V(_)??void 0,lineNumber:typeof oe=="number"?oe:void 0},ie=[];L&&(k.length>0?ie=jt(k,Z,Math.max(1,Math.floor(ce))):v.push("Query was provided but no roots could be discovered. Provide an anchorSelector/anchorX+anchorY so we can map via DOM fiber pointers."));let de=[];I&&de.push(I);for(let h of ie)de.push(h);let Ee=[],Ge=new Set;for(let h of de){let d=h?.alternate??h;h&&!Ge.has(d)&&(Ge.add(d),Ee.push(h))}if(Ee.length===0)return _t||v.push("No candidates found. Without the DevTools hook, component search may be unreliable unless you provide a strong anchor."),{reactDetected:_t,fiberDetected:g,rootDiscovery:A,component:null,candidates:[],elements:[],notes:[...v,"Failed to select a target component fiber. Provide a better anchor, or ensure React is present and render has happened."]};let Mt=[];for(let h of Ee){let d=es(h,C,$,P,Z,Y,M,ee,ue),S="unknown",E=I?(I.alternate??I)===(h.alternate??h):!1,R=ie.some(tt=>(tt.alternate??tt)===(h.alternate??h));E&&R?S="query+anchor":E?S="anchor":R?S="query":S="unknown";let z=J(h),se=Ce(h),ye=We(h),Fe=un(h,me),Te={name:z,displayName:se,debugSource:ye,componentStack:Fe,selection:S,scoring:{score:d.score,nameMatched:d.nameMatched,debugSourceMatched:d.debugSourceMatched,anchorRelated:d.anchorRelated,proximityPx:d.proximityPx}};Mt.push({fiber:h,meta:Te,dom:d.dom,domFootprintCount:d.dom.length})}Mt.sort((h,d)=>(d.meta.scoring?.score??0)-(h.meta.scoring?.score??0));let mn=Mt[0],Dt=Mt.slice(0,Math.max(1,Math.floor(ce))).map(h=>({...h.meta,domFootprintCount:h.domFootprintCount})),ts=mn.dom;return L&&(Z.fileNameHint||typeof Z.lineNumber=="number")&&(Dt.some(d=>!!(d.debugSource?.fileName||d.debugSource?.lineNumber!==null))||(v.push("debugSource hints were provided, but no _debugSource information was found on matched fibers. This is common in production builds and some dev toolchains."),v.push('React DevTools may still display "Rendered by <file>:<line>" using sourcemaps/stack traces even when fiber._debugSource is null.'))),ts.length>=Y&&v.push(`Element list was truncated at maxElements=${Y}. Increase maxElements if needed.`),ts.length===0&&v.push("No DOM elements were returned for the selected component. It may render no host elements, or filtering (onlyVisible/onlyInViewport) removed them."),!_t&&g?v.push("React DevTools hook was not detected, but DOM fiber pointers were found. Using DOM-fiber scanning and anchor-based mapping (best-effort)."):!_t&&!g&&v.push("React DevTools hook was not detected and no DOM fiber pointers were found. Component-to-DOM mapping is unavailable on this page."),{reactDetected:_t,fiberDetected:g,rootDiscovery:A,component:mn.meta,candidates:Dt,elements:ts,notes:[...v,"Component metadata is best-effort. Wrappers (memo/forwardRef/HOCs), Suspense/Offscreen, and portals may make names/stacks noisy."]}},{anchorSelectorEval:typeof n=="string"&&n.trim()?n.trim():void 0,anchorXEval:typeof r=="number"&&Number.isFinite(r)?Math.floor(r):void 0,anchorYEval:typeof i=="number"&&Number.isFinite(i)?Math.floor(i):void 0,componentNameEval:typeof a=="string"&&a.trim()?a.trim():void 0,matchStrategyEval:l,fileNameHintEval:typeof u=="string"&&u.trim()?u.trim():void 0,lineNumberEval:typeof m=="number"&&Number.isFinite(m)?Math.floor(m):void 0,maxElementsEval:Math.max(1,Math.floor(c)),onlyVisibleEval:!!p,onlyInViewportEval:!!b,textPreviewMaxLengthEval:Math.max(1,Math.floor(f)),maxMatchesEval:Math.max(1,Math.floor(x)),maxRootsScan:vc,maxFibersVisited:Ic,stackLimit:xc})}};var ja=[new rr,new sr];import{z as za}from"zod";var ir=class{static{s(this,"JsInBrowser")}name(){return"run_js-in-browser"}description(){return`
664
664
  Runs custom JavaScript INSIDE the active browser page using Playwright's "page.evaluate()".
665
665
 
666
666
  This code executes in the PAGE CONTEXT (real browser environment):
@@ -678,11 +678,12 @@ Notes:
678
678
  - The code runs in an isolated execution context, but within the page
679
679
  - No direct access to Node.js APIs
680
680
  - Return value must be serializable
681
- - The script is executed as a function body, so "return" statements are valid and their value is returned to the caller.
681
+ - The script is executed as a function body, so "return" and top-level "await" are valid; their value is returned to the caller.
682
+ - When using fetch(): check response.ok and/or Content-Type before calling .json(); error pages often return HTML and will cause "is not valid JSON" if parsed.
682
683
  `}inputSchema(){return{script:za.string().describe('JavaScript code to execute. May use "return" to pass a serializable value back; the script runs as a function body.')}}outputSchema(){return{result:za.any().describe(`
683
684
  The result of the evaluation. This value can be of any type, including primitives, arrays, or objects.
684
685
  It represents the direct return value of the JavaScript expression executed in the page context.
685
- The structure and type of this value are not constrained and depend entirely on the evaluated code.`)}}async handle(e,t){let n=`(function() { ${t.script} })()`;return{result:await e.page.evaluate(n)}}};import Cc from"node:crypto";import Va from"node:vm";import{z as ks}from"zod";var Ga=5e3,Ec=3e4;function Oc(o){if(o==null||typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;try{return JSON.parse(JSON.stringify(o))}catch{return String(o)}}s(Oc,"_toJsonSafe");var ar=class{static{s(this,"JsInSandbox")}name(){return"run_js-in-sandbox"}description(){return`
686
+ The structure and type of this value are not constrained and depend entirely on the evaluated code.`)}}async handle(e,t){let n=`(async function() { ${t.script} })()`;return{result:await e.page.evaluate(n)}}};import Cc from"node:crypto";import Va from"node:vm";import{z as Rs}from"zod";var Ga=5e3,Ec=3e4;function Oc(o){if(o==null||typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o;try{return JSON.parse(JSON.stringify(o))}catch{return String(o)}}s(Oc,"_toJsonSafe");var ar=class{static{s(this,"JsInSandbox")}name(){return"run_js-in-sandbox"}description(){return`
686
687
  Runs custom JavaScript inside a Node.js VM sandbox.
687
688
 
688
689
  This runs on the MCP SERVER (not in the browser).
@@ -707,7 +708,7 @@ NOT available:
707
708
  - globalThis
708
709
 
709
710
  This is NOT a security boundary. Intended for trusted automation logic.
710
- `.trim()}inputSchema(){return{code:ks.string().describe("JavaScript code (async allowed)."),timeoutMs:ks.number().int().min(0).max(Ec).optional().default(Ga).describe("Max VM CPU time for synchronous execution in milliseconds.")}}outputSchema(){return{result:ks.any().describe(`
711
+ `.trim()}inputSchema(){return{code:Rs.string().describe("JavaScript code (async allowed)."),timeoutMs:Rs.number().int().min(0).max(Ec).optional().default(Ga).describe("Max VM CPU time for synchronous execution in milliseconds.")}}outputSchema(){return{result:Rs.any().describe(`
711
712
  Return value of the sandboxed code (best-effort JSON-safe).
712
713
  If user returns undefined but logs exist, returns { logs }.
713
714
  If error occurs, returns { error, logs }.`)}}async handle(e,t){let n=[],r={log:s((...m)=>{n.push({level:"log",message:m.map(c=>String(c)).join(" ")})},"log"),warn:s((...m)=>{n.push({level:"warn",message:m.map(c=>String(c)).join(" ")})},"warn"),error:s((...m)=>{n.push({level:"error",message:m.map(c=>String(c)).join(" ")})},"error")},i=s(async m=>{let c=Math.max(0,Math.floor(m));await new Promise(p=>{setTimeout(()=>p(),c)})},"sleep"),a={page:e.page,console:r,sleep:i,Math,JSON,Number,String,Boolean,Array,Object,Date,RegExp,isFinite,isNaN,parseInt,parseFloat,URL,URLSearchParams,TextEncoder,TextDecoder,structuredClone,crypto:{randomUUID:Cc.randomUUID},AbortController,setTimeout,clearTimeout},l=Va.createContext(a),u=`
@@ -715,7 +716,7 @@ If error occurs, returns { error, logs }.`)}}async handle(e,t){let n=[],r={log:s
715
716
  (async () => {
716
717
  ${String(t.code??"")}
717
718
  })()
718
- `.trim();try{let c=new Va.Script(u,{filename:"mcp-sandbox.js"}).runInContext(l,{timeout:t.timeoutMs??Ga}),p=await Promise.resolve(c);return p===void 0&&n.length>0?{result:{logs:n}}:{result:Oc(p)}}catch(m){return{result:{error:m instanceof Error?m.stack??m.message:String(m),logs:n}}}}};var Ka=[new ir,new ar];import Nc from"picomatch";var Xa=new WeakMap;function sn(o){let e=Xa.get(o);if(e)return e;let t={stubs:[],installed:!1};return Xa.set(o,t),t}s(sn,"_ensureStore");function Ya(){let o=Date.now(),e=Math.floor(Math.random()*1e6);return`${o.toString(36)}-${e.toString(36)}`}s(Ya,"_nowId");async function Pc(o){o<=0||await new Promise(e=>{setTimeout(()=>e(),o)})}s(Pc,"_sleep");function _s(o){return typeof o!="number"||!Number.isFinite(o)||o<=0?-1:Math.floor(o)}s(_s,"_normalizeTimes");function Ja(o,e){return o===-1?!0:e<o}s(Ja,"_isTimesRemaining");function Qa(o){if(typeof o=="number"&&Number.isFinite(o))return Math.max(0,Math.min(1,o))}s(Qa,"_normalizeChance");function Rc(o){return o===void 0?!0:o<=0?!1:o>=1?!0:Math.random()<o}s(Rc,"_shouldApplyChance");function Za(o){let e=o.trim();return e?Nc(e,{dot:!0,nocase:!1}):()=>!1}s(Za,"_compileMatcher");function kc(o,e){for(let t of o)if(t.enabled&&Ja(t.times,t.usedCount)&&t.matcher(e)&&!(t.kind==="mock_http_response"&&!Rc(t.chance)))return t}s(kc,"_pickStub");async function _c(o,e){let t=o.request();if(e.usedCount++,e.delayMs>0&&await Pc(e.delayMs),e.kind==="mock_http_response"){if(e.action==="abort"){let a=e.abortErrorCode??"failed";await o.abort(a);return}let n=typeof e.status=="number"?e.status:200,r=e.headers??{},i=typeof e.body=="string"?e.body:"";await o.fulfill({status:n,headers:r,body:i});return}else if(e.kind==="intercept_http_request"){let r={headers:{...t.headers(),...e.modifications.headers??{}}};typeof e.modifications.method=="string"&&e.modifications.method.trim()&&(r.method=e.modifications.method.trim().toUpperCase()),typeof e.modifications.body=="string"&&(r.postData=e.modifications.body),await o.continue(r);return}await o.continue()}s(_c,"_applyStub");async function lr(o){let e=sn(o);e.installed||(await o.route("**/*",async t=>{let n=t.request().url(),r=sn(o),i=kc(r.stubs,n);if(!i){await t.continue();return}try{await _c(t,i)}finally{Ja(i.times,i.usedCount)||(r.stubs=r.stubs.filter(a=>a.id!==i.id))}}),e.installed=!0)}s(lr,"ensureRoutingInstalled");function el(o,e){let t=sn(o),n={...e,kind:"mock_http_response",id:Ya(),usedCount:0,matcher:Za(e.pattern),times:_s(e.times),delayMs:Math.max(0,Math.floor(e.delayMs)),chance:Qa(e.chance)};return t.stubs.push(n),n}s(el,"addMockHttpResponseStub");function tl(o,e){let t=sn(o),n={...e,kind:"intercept_http_request",id:Ya(),usedCount:0,matcher:Za(e.pattern),times:_s(e.times),delayMs:Math.max(0,Math.floor(e.delayMs))};return t.stubs.push(n),n}s(tl,"addHttpInterceptRequestStub");function nl(o,e){let t=sn(o);if(!e){let r=t.stubs.length;return t.stubs=[],r}let n=t.stubs.length;return t.stubs=t.stubs.filter(r=>r.id!==e),n-t.stubs.length}s(nl,"clearStub");function ol(o){return[...sn(o).stubs]}s(ol,"listStubs");function ur(o){return typeof o!="number"||!Number.isFinite(o)||o<=0?0:Math.floor(o)}s(ur,"normalizeDelayMs");function cr(o){return _s(o)}s(cr,"normalizeTimesPublic");function mr(o){if(!o)return;let e={};for(let[t,n]of Object.entries(o))e[String(t)]=String(n);return e}s(mr,"normalizeHeaders");function pr(o){if(typeof o=="string")return o;if(o&&typeof o=="object")return JSON.stringify(o)}s(pr,"normalizeBody");function rl(o){if(typeof o!="string")return;let e=o.trim();if(e)return e}s(rl,"normalizeAbortCode");function sl(o){if(typeof o!="string")return;let e=o.trim();if(e)return e.toUpperCase()}s(sl,"normalizeMethod");function il(o){return Qa(o)}s(il,"normalizeChance");import{z as al}from"zod";var dr=class{static{s(this,"Clear")}name(){return"stub_clear"}description(){return`
719
+ `.trim();try{let c=new Va.Script(u,{filename:"mcp-sandbox.js"}).runInContext(l,{timeout:t.timeoutMs??Ga}),p=await Promise.resolve(c);return p===void 0&&n.length>0?{result:{logs:n}}:{result:Oc(p)}}catch(m){return{result:{error:m instanceof Error?m.stack??m.message:String(m),logs:n}}}}};var Ka=[new ir,new ar];import Nc from"picomatch";var Xa=new WeakMap;function sn(o){let e=Xa.get(o);if(e)return e;let t={stubs:[],installed:!1};return Xa.set(o,t),t}s(sn,"_ensureStore");function Ya(){let o=Date.now(),e=Math.floor(Math.random()*1e6);return`${o.toString(36)}-${e.toString(36)}`}s(Ya,"_nowId");async function Pc(o){o<=0||await new Promise(e=>{setTimeout(()=>e(),o)})}s(Pc,"_sleep");function _s(o){return typeof o!="number"||!Number.isFinite(o)||o<=0?-1:Math.floor(o)}s(_s,"_normalizeTimes");function Ja(o,e){return o===-1?!0:e<o}s(Ja,"_isTimesRemaining");function Qa(o){if(typeof o=="number"&&Number.isFinite(o))return Math.max(0,Math.min(1,o))}s(Qa,"_normalizeChance");function kc(o){return o===void 0?!0:o<=0?!1:o>=1?!0:Math.random()<o}s(kc,"_shouldApplyChance");function Za(o){let e=o.trim();return e?Nc(e,{dot:!0,nocase:!1}):()=>!1}s(Za,"_compileMatcher");function Rc(o,e){for(let t of o)if(t.enabled&&Ja(t.times,t.usedCount)&&t.matcher(e)&&!(t.kind==="mock_http_response"&&!kc(t.chance)))return t}s(Rc,"_pickStub");async function _c(o,e){let t=o.request();if(e.usedCount++,e.delayMs>0&&await Pc(e.delayMs),e.kind==="mock_http_response"){if(e.action==="abort"){let a=e.abortErrorCode??"failed";await o.abort(a);return}let n=typeof e.status=="number"?e.status:200,r=e.headers??{},i=typeof e.body=="string"?e.body:"";await o.fulfill({status:n,headers:r,body:i});return}else if(e.kind==="intercept_http_request"){let r={headers:{...t.headers(),...e.modifications.headers??{}}};typeof e.modifications.method=="string"&&e.modifications.method.trim()&&(r.method=e.modifications.method.trim().toUpperCase()),typeof e.modifications.body=="string"&&(r.postData=e.modifications.body),await o.continue(r);return}await o.continue()}s(_c,"_applyStub");async function lr(o){let e=sn(o);e.installed||(await o.route("**/*",async t=>{let n=t.request().url(),r=sn(o),i=Rc(r.stubs,n);if(!i){await t.continue();return}try{await _c(t,i)}finally{Ja(i.times,i.usedCount)||(r.stubs=r.stubs.filter(a=>a.id!==i.id))}}),e.installed=!0)}s(lr,"ensureRoutingInstalled");function el(o,e){let t=sn(o),n={...e,kind:"mock_http_response",id:Ya(),usedCount:0,matcher:Za(e.pattern),times:_s(e.times),delayMs:Math.max(0,Math.floor(e.delayMs)),chance:Qa(e.chance)};return t.stubs.push(n),n}s(el,"addMockHttpResponseStub");function tl(o,e){let t=sn(o),n={...e,kind:"intercept_http_request",id:Ya(),usedCount:0,matcher:Za(e.pattern),times:_s(e.times),delayMs:Math.max(0,Math.floor(e.delayMs))};return t.stubs.push(n),n}s(tl,"addHttpInterceptRequestStub");function nl(o,e){let t=sn(o);if(!e){let r=t.stubs.length;return t.stubs=[],r}let n=t.stubs.length;return t.stubs=t.stubs.filter(r=>r.id!==e),n-t.stubs.length}s(nl,"clearStub");function ol(o){return[...sn(o).stubs]}s(ol,"listStubs");function ur(o){return typeof o!="number"||!Number.isFinite(o)||o<=0?0:Math.floor(o)}s(ur,"normalizeDelayMs");function cr(o){return _s(o)}s(cr,"normalizeTimesPublic");function mr(o){if(!o)return;let e={};for(let[t,n]of Object.entries(o))e[String(t)]=String(n);return e}s(mr,"normalizeHeaders");function pr(o){if(typeof o=="string")return o;if(o&&typeof o=="object")return JSON.stringify(o)}s(pr,"normalizeBody");function rl(o){if(typeof o!="string")return;let e=o.trim();if(e)return e}s(rl,"normalizeAbortCode");function sl(o){if(typeof o!="string")return;let e=o.trim();if(e)return e.toUpperCase()}s(sl,"normalizeMethod");function il(o){return Qa(o)}s(il,"normalizeChance");import{z as al}from"zod";var dr=class{static{s(this,"Clear")}name(){return"stub_clear"}description(){return`
719
720
  Clears stubs installed.
720
721
 
721
722
  - If stubId is provided, clears only that stub.
@@ -766,7 +767,7 @@ Notes:
766
767
  - This tool does NOT rely on window globals or page-injected counters.
767
768
  - It uses server-side tracking, so it works reliably even with strict CSP.
768
769
  - If the page has long-polling or never-ending requests, increase maxConnections or accept a shorter idleTimeMs.
769
- `.trim()}inputSchema(){return{timeoutMs:Ze.number().int().min(0).optional().default(ul).describe("Maximum time to wait before failing (milliseconds).."),idleTimeMs:Ze.number().int().min(0).optional().default(cl).describe("How long the network must stay idle continuously before resolving (milliseconds)."),maxConnections:Ze.number().int().min(0).optional().default(ml).describe("Idle threshold. Network is considered idle when in-flight requests <= maxConnections."),pollIntervalMs:Ze.number().int().min(10).optional().default(pl).describe("Polling interval used to sample the in-flight request count (milliseconds).")}}outputSchema(){return{waitedMs:Ze.number().int().nonnegative().describe("Total time waited until the network became idle or the tool timed out (milliseconds)."),idleTimeMs:Ze.number().int().nonnegative().describe("Idle duration required for success (milliseconds)."),timeoutMs:Ze.number().int().nonnegative().describe("Maximum allowed wait time (milliseconds)."),maxConnections:Ze.number().int().nonnegative().describe("Idle threshold used: in-flight requests must be <= this value."),pollIntervalMs:Ze.number().int().nonnegative().describe("Polling interval used to sample the in-flight request count (milliseconds)."),finalInFlightRequests:Ze.number().int().nonnegative().describe("The last observed number of in-flight requests at the moment the tool returned."),observedIdleMs:Ze.number().int().nonnegative().describe("How long the in-flight request count stayed <= maxConnections right before returning (milliseconds).")}}async handle(e,t){let n=t.timeoutMs??ul,r=t.idleTimeMs??cl,i=t.maxConnections??ml,a=t.pollIntervalMs??pl,l=Date.now(),u=l+n,m=l,c=0;for(;;){let p=Date.now();c=e.numOfInFlightRequests(),c>i&&(m=p);let b=p-m;if(b>=r)return{waitedMs:p-l,idleTimeMs:r,timeoutMs:n,maxConnections:i,pollIntervalMs:a,finalInFlightRequests:c,observedIdleMs:b};if(p>=u){let f=p-l;throw new Error(`Timed out after ${f}ms waiting for network idle (idleTimeMs=${r}, maxConnections=${i}, inFlight=${c}).`)}await this.sleep(a)}}async sleep(e){await new Promise(t=>{setTimeout(()=>t(),e)})}};var dl=[new fr];import Dc from"node:fs";import{chromium as hl,firefox as gl,webkit as fl}from"playwright";var Bc="chromium",bl=new Map,yr=new Map;function Ac(o){return JSON.stringify(o)}s(Ac,"_browserKey");function Lc(o){let e={headless:o.headless,executablePath:o.executablePath,handleSIGINT:!1,handleSIGTERM:!1};if(o.useInstalledOnSystem)if(o.browserType==="chromium")e.channel="chrome",e.args=["--disable-blink-features=AutomationControlled"],e.ignoreDefaultArgs=["--disable-extensions"];else throw new Error(`Browser type ${o.browserType} is not supported to be used from the one installed on the system`);return e}s(Lc,"_browserLaunchOptions");async function Fc(o){let e;switch(o.browserType){case"firefox":e=gl;break;case"webkit":e=fl;break;default:e=hl;break}return e.launch(Lc(o))}s(Fc,"_createBrowser");async function Uc(o){let e=Ac(o),t=bl.get(e);if(t&&!t.isConnected()){try{await t.close().catch(()=>{})}catch{}t=void 0}return t||(t=await Fc(o),bl.set(e,t)),t}s(Uc,"_getBrowser");function Hc(o){return o.persistent.userDataDir}s(Hc,"_persistentBrowserContextKey");function Wc(o){let e=o.browserOptions,t={headless:e.headless,executablePath:e.executablePath,bypassCSP:!0,viewport:e.headless?void 0:null,locale:o.locale};if(e.useInstalledOnSystem)if(e.browserType==="chromium")t.channel="chrome",t.args=["--disable-blink-features=AutomationControlled"],t.ignoreDefaultArgs=["--disable-extensions"];else throw new Error(`Browser type ${e.browserType} is not supported to be used from the one installed on the system`);return t}s(Wc,"_persistentBrowserContextLaunchOptions");async function qc(o){let e;switch(o.browserOptions.browserType){case"firefox":e=gl;break;case"webkit":e=fl;break;default:e=hl;break}let t=o.persistent.userDataDir;Dc.mkdirSync(t,{recursive:!0});let n=await e.launchPersistentContext(t,Wc(o));for(let r of n.pages())try{await r.close()}catch{}return n}s(qc,"_createPersistentBrowserContext");async function $c(o){let e=Hc(o),t=yr.get(e);if(t&&!t.browser()?.isConnected()){try{await t.close().catch(()=>{})}catch{}t=void 0}if(!t)t=await qc(o),yr.set(e,t);else throw new Error(`There is already active persistent browser context in the user data directory: ${o.persistent?.userDataDir}`);return t}s($c,"_getPersistentBrowserContext");async function yl(o={browserOptions:{browserType:Bc,headless:zt,executablePath:Nn,useInstalledOnSystem:Kt},persistent:Vt?{userDataDir:Gt}:void 0,locale:Pn}){return o.persistent?{browserContext:await $c(o)}:{browserContext:await(await Uc(o.browserOptions)).newContext({viewport:o.browserOptions.headless?void 0:null,bypassCSP:!0,locale:o.locale})}}s(yl,"newBrowserContext");async function wl(o,e={}){return await o.newPage()}s(wl,"newPage");async function Tl(o){await o.close();let e=!1;for(let[t,n]of yr.entries())o===n&&(yr.delete(t),e=!0);return e}s(Tl,"closeBrowserContext");function jc(o){let e=o.trim();return e.startsWith("/")||(e="/"+e),e.endsWith("/")||(e=e+"/"),e}s(jc,"_normalizeBasePath");function zc(o){let e=o.trim();return e&&(e.endsWith("/")?e.slice(0,-1):e)}s(zc,"_normalizeUpstreamBaseUrl");function Vc(o,e){try{let n=new URL(o).pathname;if(!n.startsWith(e))return null;let r=n.slice(e.length);return r?r.startsWith("/")?r:"/"+r:null}catch{return null}}s(Vc,"_computeSuffixPath");function Gc(o,e,t){try{let r=new URL(t).search??"";return o+e+r}catch{return o+e}}s(Gc,"_appendSuffixToUpstream");var wr=class{static{s(this,"OTELProxy")}config;queue;workers;isRunning;isInstalled;metrics;constructor(e){let t=e.maxQueueSize??200,n=e.concurrency??2,r=e.respondNoContent??!0,i=jc(e.localPath),a=zc(e.upstreamUrl);this.config={...e,localPath:i,upstreamUrl:a,maxQueueSize:t,concurrency:n,respondNoContent:r},this.queue=[],this.workers=[],this.isRunning=!1,this.isInstalled=!1,this.metrics={routedRequests:0,acceptedBatches:0,droppedBatches:0,forwardedBatches:0,failedBatches:0,inFlight:0,queueSize:0,lastError:null}}getMetrics(){return{...this.metrics,queueSize:this.queue.length}}async install(e){if(this.isInstalled)return;let t=this.config.localPath;if(!t.startsWith("/"))throw new Error('localPath must start with "/" (e.g. "/__mcp_otel/").');let n=`**${t}**`;await e.route(n,async r=>{await this._handleRoute(r)}),this.isInstalled=!0,this.isRunning||await this.start(),K(`[otel-proxy] installed route pattern: ${n} (basePath=${t}, upstreamBase=${this.config.upstreamUrl})`)}async uninstall(e){if(!this.isInstalled)return;let t=`**${this.config.localPath}**`;try{await e.unroute(t)}catch{}this.isInstalled=!1,await this.stop()}async start(){if(this.isRunning)return;this.isRunning=!0;let e=Math.max(1,this.config.concurrency);for(let t=0;t<e;t++){let n=this._workerLoop(t);this.workers.push(n)}K(`[otel-proxy] started with concurrency=${e}, maxQueueSize=${this.config.maxQueueSize}`)}async stop(){if(this.isRunning){this.isRunning=!1,this.queue.length=0;try{await Promise.allSettled(this.workers)}finally{this.workers.length=0}K("[otel-proxy] stopped")}}async _handleRoute(e){let t=e.request();if(this.metrics.routedRequests++,t.method().toUpperCase()==="OPTIONS"){await this._fulfillFast(e);return}if(this.config.shouldForward&&!this.config.shouldForward(t)){await this._fulfillFast(e);return}let n=t.url(),r=this.config.localPath,i=Vc(n,r);if(!i){await e.fallback();return}let a=Gc(this.config.upstreamUrl,i,n),u=await t.postDataBuffer()??Buffer.alloc(0),c=t.headers()["content-type"]??"application/x-protobuf",p=t.method(),b={"content-type":c};if(this.config.upstreamHeaders)for(let[x,B]of Object.entries(this.config.upstreamHeaders))b[x]=B;if(this.queue.length>=this.config.maxQueueSize){this.metrics.droppedBatches++,await this._fulfillFast(e),rs(`[otel-proxy] dropped batch (queue full: ${this.queue.length}/${this.config.maxQueueSize}) suffix=${i}`);return}let f={body:u,contentType:c,createdAtMs:Date.now(),upstreamUrl:a,method:p,headers:b};this.queue.push(f),this.metrics.acceptedBatches++,await this._fulfillFast(e)}async _fulfillFast(e){let t=this.config.respondNoContent?204:200;if(t===204){await e.fulfill({status:t});return}await e.fulfill({status:t,headers:{"content-type":"text/plain; charset=utf-8"},body:""})}async _workerLoop(e){for(;this.isRunning;){let t=this.queue.shift();if(!t){await this._sleep(25);continue}this.metrics.inFlight++;try{await this._forwardUpstream(t),this.metrics.forwardedBatches++}catch(n){this.metrics.failedBatches++;let r=n instanceof Error?n.message:String(n);this.metrics.lastError=r,rs(`[otel-proxy] worker=${e} forward failed: ${r}`)}finally{this.metrics.inFlight--}}}async _forwardUpstream(e){let t=await fetch(e.upstreamUrl,{method:e.method,headers:e.headers,body:new Uint8Array(e.body)});if(t.status<200||t.status>=300){let n=await this._safeReadText(t);throw new Error(`upstream returned ${t.status} for ${e.upstreamUrl}: ${n}`)}}async _safeReadText(e){try{return(await e.text()).slice(0,500)}catch{return""}}async _sleep(e){await new Promise(t=>{setTimeout(()=>t(),e)})}};import*as xr from"node:fs";import*as Et from"node:path";import{fileURLToPath as Kc}from"node:url";var Xc=Kc(import.meta.url),Yc=Et.dirname(Xc),Tr="/__mcp_otel/",Jc="otel-initializer.bundle.js";function Qc(){return os?os:Et.join(Yc,"platform","browser","otel")}s(Qc,"_getOtelAssetsDir");function Zc(){if(bn==="otlp/http"||kn){if(!kn)throw new Error('OTEL exporter HTTP url must be set when OTEL exporter type is "otlp/http"');return{type:"otlp/http",url:Tr,upstreamURL:kn,headers:Ys}}else{if(bn==="console")return{type:"console"};if(bn==="none")return{type:"none"};throw new Error(`Invalid OTEL exporter type ${bn}`)}}s(Zc,"_getOTELExporterConfig");function em(){return{userInteractionEvents:Xs}}s(em,"_getOTELInstrumentationConfig");function tm(){return{serviceName:Gs,serviceVersion:Ks,exporter:Zc(),instrumentation:em(),debug:!1}}s(tm,"_getOTELConfig");function nm(o,e){let t=Et.isAbsolute(o)?o:Et.join(process.cwd(),o),n=Et.join(t,e);if(!xr.existsSync(n))throw new Error(`OTEL bundle not found at: ${n}`);return xr.readFileSync(n,"utf-8")}s(nm,"_readBundleContent");async function om(o,e){await o.evaluate(t=>{let n=globalThis;n.__MCP_DEVTOOLS__||(n.__MCP_DEVTOOLS__={}),n.__MCP_TRACE_ID__=t.traceId,n.__mcpOtel&&typeof n.__mcpOtel.init=="function"?n.__mcpOtel.init(t):(n.__MCP_DEVTOOLS__.otelInitialized=!1,n.__MCP_DEVTOOLS__.otelInitError="__mcpOtel.init is not available while applying config")},e).catch(t=>{let n=t instanceof Error?t.message:String(t);K(`[otel-controller] applyConfigToPage failed (ignored): ${n}`)})}s(om,"_applyConfigToPage");function rm(o,e){let t=new WeakMap,n=s(a=>{if(t.has(a))return;let l=s(async u=>{u===a.mainFrame()&&await om(a,e())},"onFrameNavigated");t.set(a,l),a.on("framenavigated",l)},"attachToPage");for(let a of o.pages())n(a);let r=s(a=>{n(a)},"onNewPage");o.on("page",r);let i=s(()=>{try{o.off("page",r)}catch{}for(let a of o.pages()){let l=t.get(a);if(l)try{a.off("framenavigated",l)}catch{}}},"detach");return K("[otel-controller] auto-sync installed (page+framenavigated)"),{detach:i}}s(rm,"_installAutoSync");var Sr=class{static{s(this,"OTELController")}browserContext;config;proxy;initialized=!1;autoSyncDetach;constructor(e){this.browserContext=e,this.config=tm()}async init(e){if(this.initialized){K("[otel-controller] init skipped: BrowserContext already initialized");return}if(!e.traceId||!e.traceId.trim())throw new Error("[otel-controller] init requires a non-empty traceId");this.config.traceId=e.traceId;let t=Qc();this.config.exporter.type==="otlp/http"&&(this.proxy=new wr({localPath:Tr,upstreamUrl:this.config.exporter.upstreamURL,upstreamHeaders:{...this.config.exporter.headers??{}}}),await this.proxy.install(this.browserContext)),K(`[otel-controller] exporter=${this.config.exporter.type} localBase=${Tr}`+(this.config.exporter.type==="otlp/http"?` upstreamBase=${this.config.exporter.upstreamURL}`:""));let n=nm(t,Jc),r=rm(this.browserContext,()=>this.config);this.autoSyncDetach=r.detach,await this.browserContext.addInitScript({content:n}),await this.browserContext.addInitScript(i=>{let a=globalThis;a.__MCP_DEVTOOLS__||(a.__MCP_DEVTOOLS__={}),a.__MCP_TRACE_ID__=i.traceId,a.__mcpOtel&&typeof a.__mcpOtel.init=="function"?a.__mcpOtel.init(i):(a.__MCP_DEVTOOLS__.otelInitialized=!1,a.__MCP_DEVTOOLS__.otelInitError="__mcpOtel.init is not available (initializer bundle did not install)")},this.config),this.initialized=!0,K("[otel-controller] init installed: bundle + config init scripts + auto-sync")}isOTELRequest(e){return new URL(e.url()).pathname.startsWith(Tr)}async isInitialized(e){return await e.evaluate(()=>globalThis.__MCP_DEVTOOLS__?.otelInitialized===!0)}async getInitError(e){return await e.evaluate(()=>{let n=globalThis.__MCP_DEVTOOLS__?.otelInitError;if(typeof n=="string"&&n.trim())return n})}async getTraceId(e){return await e.evaluate(()=>{let t=globalThis;if(t.__mcpOtel&&typeof t.__mcpOtel.getTraceId=="function"){let r=t.__mcpOtel.getTraceId();if(typeof r=="string"&&r.trim())return r}let n=t.__MCP_TRACE_ID__;if(typeof n=="string"&&n.trim())return n})}async setTraceId(e,t){this.config.traceId=t,await e.evaluate(n=>{let r=globalThis;r.__mcpOtel&&typeof r.__mcpOtel.setTraceId=="function"?r.__mcpOtel.setTraceId(n):r.__MCP_TRACE_ID__=n},t)}async close(){if(this.autoSyncDetach){try{this.autoSyncDetach()}catch{}this.autoSyncDetach=void 0}this.proxy&&(await this.proxy.uninstall(this.browserContext),this.proxy=void 0)}};var vr=class{static{s(this,"BrowserToolSessionContext")}_sessionId;options;otelController;consoleMessages=[];httpRequests=[];initialized=!1;closed=!1;traceId;_numOfInFlightRequests=0;_lastNetworkActivityTimestamp=0;browserContext;page;constructor(e,t,n,r){this._sessionId=e,this.browserContext=t,this.page=n,this.options=r,this.otelController=new Sr(this.browserContext)}async init(){if(this.closed)throw new Error("Session context is already closed");if(this.initialized)throw new Error("Session context is already initialized");let e=this,t=0;this.page.on("console",r=>{e.consoleMessages.push(e._toConsoleMessage(r,++t)),e.consoleMessages.length>pn&&e.consoleMessages.splice(0,e.consoleMessages.length-pn)}),this.page.on("pageerror",r=>{e.consoleMessages.push(e._errorToConsoleMessage(r,++t)),e.consoleMessages.length>pn&&e.consoleMessages.splice(0,e.consoleMessages.length-pn)});let n=0;this.page.on("request",async r=>{e.otelController.isOTELRequest(r)||(e._numOfInFlightRequests++,e._lastNetworkActivityTimestamp=Date.now())}),this.page.on("requestfinished",async r=>{e.otelController.isOTELRequest(r)||(e._numOfInFlightRequests--,e._lastNetworkActivityTimestamp=Date.now(),e.httpRequests.push(await e._toHttpRequest(r,++n)),e.httpRequests.length>dn&&e.httpRequests.splice(0,e.httpRequests.length-dn))}),this.page.on("requestfailed",async r=>{e.otelController.isOTELRequest(r)||(e._numOfInFlightRequests--,e._lastNetworkActivityTimestamp=Date.now(),e.httpRequests.push(await e._toHttpRequest(r,++n)),e.httpRequests.length>dn&&e.httpRequests.splice(0,e.httpRequests.length-dn))}),this.options.otelEnable&&(this.traceId=tr(),await this.otelController.init({traceId:this.traceId})),this.initialized=!0}_toConsoleMessageLevelName(e){switch(e){case"assert":case"error":return"error";case"warning":return"warning";case"count":case"dir":case"dirxml":case"info":case"log":case"table":case"time":case"timeEnd":return"info";case"clear":case"debug":case"endGroup":case"profile":case"profileEnd":case"startGroup":case"startGroupCollapsed":case"trace":return"debug";default:return"info"}}_toConsoleMessage(e,t){let n=Date.now(),r=this._toConsoleMessageLevelName(e.type()),i=Yt[r].code;return{type:e.type(),text:e.text(),level:{name:r,code:i},location:{url:e.location().url,lineNumber:e.location().lineNumber,columnNumber:e.location().columnNumber},timestamp:n,sequenceNumber:t}}_errorToConsoleMessage(e,t){let n=Date.now();return e instanceof Error?{type:"error",text:e.message,level:{name:"error",code:3},timestamp:n,sequenceNumber:t}:{type:"error",text:String(e),level:{name:"error",code:3},timestamp:n,sequenceNumber:t}}_isBodyLikelyPresent(e,t){return!(t==="HEAD"||t==="OPTIONS"||e===204||e===304||e>=300&&e<400)}async _safeReadResponseBody(e){try{let n=e.request().method(),r=e.status();return this._isBodyLikelyPresent(r,n)?(await e.body()).toString("utf-8"):void 0}catch{return}}async _toHttpRequest(e,t){let n=await e.response();return{url:e.url(),method:e.method(),headers:e.headers(),body:e.postData()||void 0,resourceType:e.resourceType(),failure:e.failure()?.errorText,duration:e.timing().responseEnd,response:n?{status:n.status(),statusText:n.statusText(),headers:n.headers(),body:await this._safeReadResponseBody(n)}:void 0,ok:n?n.ok():!1,timestamp:Math.floor(e.timing().startTime),sequenceNumber:t}}numOfInFlightRequests(){return this._numOfInFlightRequests}lastNetworkActivityTimestamp(){return this._lastNetworkActivityTimestamp}sessionId(){return this._sessionId}async getTraceId(){return this.traceId}async setTraceId(e){if(!this.options.otelEnable)throw new Error("OTEL is not enabled");this.traceId=e,await this.otelController.setTraceId(this.page,e)}getConsoleMessages(){return this.consoleMessages}getHttpRequests(){return this.httpRequests}async close(){if(this.closed)return!1;K(`Closing OTEL controller of the session with id ${this._sessionId} ...`),await this.otelController.close();try{K(`Closing browser context of the session with id ${this._sessionId} ...`),await Tl(this.browserContext)}catch(e){K(`Error occurred while closing browser context of the session with id ${this._sessionId} ...`,e)}return this.consoleMessages.length=0,this.httpRequests.length=0,this.closed=!0,!0}};var Ir=class{static{s(this,"BrowserToolExecutor")}sessionIdProvider;sessionContext;constructor(e){this.sessionIdProvider=e}async _createSessionContext(){let e=await yl(),t=await wl(e.browserContext),n=this.sessionIdProvider(),r=new vr(n,e.browserContext,t,{otelEnable:Vs});return await r.init(),r}async _sessionContext(){return this.sessionContext||(this.sessionContext=await this._createSessionContext(),K(`Created session context on the first tool call for the session with id ${this.sessionContext.sessionId()}`)),this.sessionContext}async executeTool(e,t){K(`Executing tool ${e.name()} with input: ${hn(t)}`);try{let n=await this._sessionContext(),r=await e.handle(n,t);return K(`Executed tool ${e.name()} and got output: ${hn(r)}`),r}catch(n){throw K(`Error occurred while executing ${e.name()}: ${n}`),n}}};var Cr=[...Oi,...Mi,...sa,...Ia,...ka,..._a,...Da,...ja,...Ka,...ll,...dl];function Sl(o){return new Ir(o)}s(Sl,"createToolExecutor");import{Option as Ht}from"commander";var Ms=class{static{s(this,"BrowserCliProvider")}platform="browser";cliName="browser-devtools-cli";tools=Cr;sessionDescription="Manage browser sessions";cliExamples=["browser-devtools-cli --no-headless interactive","browser-devtools-cli --persistent --no-headless interactive"];bashCompletionOptions="--headless --no-headless --persistent --no-persistent --user-data-dir --use-system-browser --browser-path";bashCompletionCommands="daemon session tools config completion interactive navigation content interaction a11y accessibility o11y react run stub sync figma debug";zshCompletionOptions=` '--headless[Run in headless mode]' \\
770
+ `.trim()}inputSchema(){return{timeoutMs:Ze.number().int().min(0).optional().default(ul).describe("Maximum time to wait before failing (milliseconds).."),idleTimeMs:Ze.number().int().min(0).optional().default(cl).describe("How long the network must stay idle continuously before resolving (milliseconds)."),maxConnections:Ze.number().int().min(0).optional().default(ml).describe("Idle threshold. Network is considered idle when in-flight requests <= maxConnections."),pollIntervalMs:Ze.number().int().min(10).optional().default(pl).describe("Polling interval used to sample the in-flight request count (milliseconds).")}}outputSchema(){return{waitedMs:Ze.number().int().nonnegative().describe("Total time waited until the network became idle or the tool timed out (milliseconds)."),idleTimeMs:Ze.number().int().nonnegative().describe("Idle duration required for success (milliseconds)."),timeoutMs:Ze.number().int().nonnegative().describe("Maximum allowed wait time (milliseconds)."),maxConnections:Ze.number().int().nonnegative().describe("Idle threshold used: in-flight requests must be <= this value."),pollIntervalMs:Ze.number().int().nonnegative().describe("Polling interval used to sample the in-flight request count (milliseconds)."),finalInFlightRequests:Ze.number().int().nonnegative().describe("The last observed number of in-flight requests at the moment the tool returned."),observedIdleMs:Ze.number().int().nonnegative().describe("How long the in-flight request count stayed <= maxConnections right before returning (milliseconds).")}}async handle(e,t){let n=t.timeoutMs??ul,r=t.idleTimeMs??cl,i=t.maxConnections??ml,a=t.pollIntervalMs??pl,l=Date.now(),u=l+n,m=l,c=0;for(;;){let p=Date.now();c=e.numOfInFlightRequests(),c>i&&(m=p);let b=p-m;if(b>=r)return{waitedMs:p-l,idleTimeMs:r,timeoutMs:n,maxConnections:i,pollIntervalMs:a,finalInFlightRequests:c,observedIdleMs:b};if(p>=u){let f=p-l;throw new Error(`Timed out after ${f}ms waiting for network idle (idleTimeMs=${r}, maxConnections=${i}, inFlight=${c}).`)}await this.sleep(a)}}async sleep(e){await new Promise(t=>{setTimeout(()=>t(),e)})}};var dl=[new fr];import Dc from"node:fs";import{chromium as hl,firefox as gl,webkit as fl}from"playwright";var Bc="chromium",bl=new Map,yr=new Map;function Ac(o){return JSON.stringify(o)}s(Ac,"_browserKey");function Lc(o){let e={headless:o.headless,executablePath:o.executablePath,handleSIGINT:!1,handleSIGTERM:!1};if(o.useInstalledOnSystem)if(o.browserType==="chromium")e.channel="chrome",e.args=["--disable-blink-features=AutomationControlled"],e.ignoreDefaultArgs=["--disable-extensions"];else throw new Error(`Browser type ${o.browserType} is not supported to be used from the one installed on the system`);return e}s(Lc,"_browserLaunchOptions");async function Fc(o){let e;switch(o.browserType){case"firefox":e=gl;break;case"webkit":e=fl;break;default:e=hl;break}return e.launch(Lc(o))}s(Fc,"_createBrowser");async function Uc(o){let e=Ac(o),t=bl.get(e);if(t&&!t.isConnected()){try{await t.close().catch(()=>{})}catch{}t=void 0}return t||(t=await Fc(o),bl.set(e,t)),t}s(Uc,"_getBrowser");function Hc(o){return o.persistent.userDataDir}s(Hc,"_persistentBrowserContextKey");function Wc(o){let e=o.browserOptions,t={headless:e.headless,executablePath:e.executablePath,bypassCSP:!0,viewport:e.headless?void 0:null,locale:o.locale};if(e.useInstalledOnSystem)if(e.browserType==="chromium")t.channel="chrome",t.args=["--disable-blink-features=AutomationControlled"],t.ignoreDefaultArgs=["--disable-extensions"];else throw new Error(`Browser type ${e.browserType} is not supported to be used from the one installed on the system`);return t}s(Wc,"_persistentBrowserContextLaunchOptions");async function qc(o){let e;switch(o.browserOptions.browserType){case"firefox":e=gl;break;case"webkit":e=fl;break;default:e=hl;break}let t=o.persistent.userDataDir;Dc.mkdirSync(t,{recursive:!0});let n=await e.launchPersistentContext(t,Wc(o));for(let r of n.pages())try{await r.close()}catch{}return n}s(qc,"_createPersistentBrowserContext");async function $c(o){let e=Hc(o),t=yr.get(e);if(t&&!t.browser()?.isConnected()){try{await t.close().catch(()=>{})}catch{}t=void 0}if(!t)t=await qc(o),yr.set(e,t);else throw new Error(`There is already active persistent browser context in the user data directory: ${o.persistent?.userDataDir}`);return t}s($c,"_getPersistentBrowserContext");async function yl(o={browserOptions:{browserType:Bc,headless:zt,executablePath:Nn,useInstalledOnSystem:Kt},persistent:Vt?{userDataDir:Gt}:void 0,locale:Pn}){return o.persistent?{browserContext:await $c(o)}:{browserContext:await(await Uc(o.browserOptions)).newContext({viewport:o.browserOptions.headless?void 0:null,bypassCSP:!0,locale:o.locale})}}s(yl,"newBrowserContext");async function wl(o,e={}){return await o.newPage()}s(wl,"newPage");async function Tl(o){await o.close();let e=!1;for(let[t,n]of yr.entries())o===n&&(yr.delete(t),e=!0);return e}s(Tl,"closeBrowserContext");function jc(o){let e=o.trim();return e.startsWith("/")||(e="/"+e),e.endsWith("/")||(e=e+"/"),e}s(jc,"_normalizeBasePath");function zc(o){let e=o.trim();return e&&(e.endsWith("/")?e.slice(0,-1):e)}s(zc,"_normalizeUpstreamBaseUrl");function Vc(o,e){try{let n=new URL(o).pathname;if(!n.startsWith(e))return null;let r=n.slice(e.length);return r?r.startsWith("/")?r:"/"+r:null}catch{return null}}s(Vc,"_computeSuffixPath");function Gc(o,e,t){try{let r=new URL(t).search??"";return o+e+r}catch{return o+e}}s(Gc,"_appendSuffixToUpstream");var wr=class{static{s(this,"OTELProxy")}config;queue;workers;isRunning;isInstalled;metrics;constructor(e){let t=e.maxQueueSize??200,n=e.concurrency??2,r=e.respondNoContent??!0,i=jc(e.localPath),a=zc(e.upstreamUrl);this.config={...e,localPath:i,upstreamUrl:a,maxQueueSize:t,concurrency:n,respondNoContent:r},this.queue=[],this.workers=[],this.isRunning=!1,this.isInstalled=!1,this.metrics={routedRequests:0,acceptedBatches:0,droppedBatches:0,forwardedBatches:0,failedBatches:0,inFlight:0,queueSize:0,lastError:null}}getMetrics(){return{...this.metrics,queueSize:this.queue.length}}async install(e){if(this.isInstalled)return;let t=this.config.localPath;if(!t.startsWith("/"))throw new Error('localPath must start with "/" (e.g. "/__mcp_otel/").');let n=`**${t}**`;await e.route(n,async r=>{await this._handleRoute(r)}),this.isInstalled=!0,this.isRunning||await this.start(),K(`[otel-proxy] installed route pattern: ${n} (basePath=${t}, upstreamBase=${this.config.upstreamUrl})`)}async uninstall(e){if(!this.isInstalled)return;let t=`**${this.config.localPath}**`;try{await e.unroute(t)}catch{}this.isInstalled=!1,await this.stop()}async start(){if(this.isRunning)return;this.isRunning=!0;let e=Math.max(1,this.config.concurrency);for(let t=0;t<e;t++){let n=this._workerLoop(t);this.workers.push(n)}K(`[otel-proxy] started with concurrency=${e}, maxQueueSize=${this.config.maxQueueSize}`)}async stop(){if(this.isRunning){this.isRunning=!1,this.queue.length=0;try{await Promise.allSettled(this.workers)}finally{this.workers.length=0}K("[otel-proxy] stopped")}}async _handleRoute(e){let t=e.request();if(this.metrics.routedRequests++,t.method().toUpperCase()==="OPTIONS"){await this._fulfillFast(e);return}if(this.config.shouldForward&&!this.config.shouldForward(t)){await this._fulfillFast(e);return}let n=t.url(),r=this.config.localPath,i=Vc(n,r);if(!i){await e.fallback();return}let a=Gc(this.config.upstreamUrl,i,n),u=await t.postDataBuffer()??Buffer.alloc(0),c=t.headers()["content-type"]??"application/x-protobuf",p=t.method(),b={"content-type":c};if(this.config.upstreamHeaders)for(let[x,B]of Object.entries(this.config.upstreamHeaders))b[x]=B;if(this.queue.length>=this.config.maxQueueSize){this.metrics.droppedBatches++,await this._fulfillFast(e),rs(`[otel-proxy] dropped batch (queue full: ${this.queue.length}/${this.config.maxQueueSize}) suffix=${i}`);return}let f={body:u,contentType:c,createdAtMs:Date.now(),upstreamUrl:a,method:p,headers:b};this.queue.push(f),this.metrics.acceptedBatches++,await this._fulfillFast(e)}async _fulfillFast(e){let t=this.config.respondNoContent?204:200;if(t===204){await e.fulfill({status:t});return}await e.fulfill({status:t,headers:{"content-type":"text/plain; charset=utf-8"},body:""})}async _workerLoop(e){for(;this.isRunning;){let t=this.queue.shift();if(!t){await this._sleep(25);continue}this.metrics.inFlight++;try{await this._forwardUpstream(t),this.metrics.forwardedBatches++}catch(n){this.metrics.failedBatches++;let r=n instanceof Error?n.message:String(n);this.metrics.lastError=r,rs(`[otel-proxy] worker=${e} forward failed: ${r}`)}finally{this.metrics.inFlight--}}}async _forwardUpstream(e){let t=await fetch(e.upstreamUrl,{method:e.method,headers:e.headers,body:new Uint8Array(e.body)});if(t.status<200||t.status>=300){let n=await this._safeReadText(t);throw new Error(`upstream returned ${t.status} for ${e.upstreamUrl}: ${n}`)}}async _safeReadText(e){try{return(await e.text()).slice(0,500)}catch{return""}}async _sleep(e){await new Promise(t=>{setTimeout(()=>t(),e)})}};import*as xr from"node:fs";import*as Et from"node:path";import{fileURLToPath as Kc}from"node:url";var Xc=Kc(import.meta.url),Yc=Et.dirname(Xc),Tr="/__mcp_otel/",Jc="otel-initializer.bundle.js";function Qc(){return os?os:Et.join(Yc,"platform","browser","otel")}s(Qc,"_getOtelAssetsDir");function Zc(){if(bn==="otlp/http"||Rn){if(!Rn)throw new Error('OTEL exporter HTTP url must be set when OTEL exporter type is "otlp/http"');return{type:"otlp/http",url:Tr,upstreamURL:Rn,headers:Ys}}else{if(bn==="console")return{type:"console"};if(bn==="none")return{type:"none"};throw new Error(`Invalid OTEL exporter type ${bn}`)}}s(Zc,"_getOTELExporterConfig");function em(){return{userInteractionEvents:Xs}}s(em,"_getOTELInstrumentationConfig");function tm(){return{serviceName:Gs,serviceVersion:Ks,exporter:Zc(),instrumentation:em(),debug:!1}}s(tm,"_getOTELConfig");function nm(o,e){let t=Et.isAbsolute(o)?o:Et.join(process.cwd(),o),n=Et.join(t,e);if(!xr.existsSync(n))throw new Error(`OTEL bundle not found at: ${n}`);return xr.readFileSync(n,"utf-8")}s(nm,"_readBundleContent");async function om(o,e){let t={traceId:e.traceId,serviceName:e.serviceName,serviceVersion:e.serviceVersion,exporter:e.exporter,instrumentation:e.instrumentation,debug:e.debug};await o.evaluate(n=>{let r=globalThis;r.__MCP_DEVTOOLS__||(r.__MCP_DEVTOOLS__={}),r.__MCP_TRACE_ID__=n.traceId,r.__mcpOtel&&typeof r.__mcpOtel.init=="function"?r.__mcpOtel.init(n):(r.__MCP_DEVTOOLS__.otelInitialized=!1,r.__MCP_DEVTOOLS__.otelInitError="__mcpOtel.init is not available while applying config")},t).catch(n=>{let r=n instanceof Error?n.message:String(n);K(`[otel-controller] applyConfigToPage failed (ignored): ${r}`)})}s(om,"_applyConfigToPage");function rm(o,e){let t=new WeakMap,n=s(a=>{if(t.has(a))return;let l=s(async u=>{u===a.mainFrame()&&await om(a,e())},"onFrameNavigated");t.set(a,l),a.on("framenavigated",l)},"attachToPage");for(let a of o.pages())n(a);let r=s(a=>{n(a)},"onNewPage");o.on("page",r);let i=s(()=>{try{o.off("page",r)}catch{}for(let a of o.pages()){let l=t.get(a);if(l)try{a.off("framenavigated",l)}catch{}}},"detach");return K("[otel-controller] auto-sync installed (page+framenavigated)"),{detach:i}}s(rm,"_installAutoSync");var Sr=class{static{s(this,"OTELController")}browserContext;config;proxy;initialized=!1;autoSyncDetach;constructor(e){this.browserContext=e,this.config=tm()}async init(e){if(this.initialized){K("[otel-controller] init skipped: BrowserContext already initialized");return}if(!e.traceId||!e.traceId.trim())throw new Error("[otel-controller] init requires a non-empty traceId");this.config.traceId=e.traceId;let t=Qc();this.config.exporter.type==="otlp/http"&&(this.proxy=new wr({localPath:Tr,upstreamUrl:this.config.exporter.upstreamURL,upstreamHeaders:{...this.config.exporter.headers??{}}}),await this.proxy.install(this.browserContext)),K(`[otel-controller] exporter=${this.config.exporter.type} localBase=${Tr}`+(this.config.exporter.type==="otlp/http"?` upstreamBase=${this.config.exporter.upstreamURL}`:""));let n=nm(t,Jc),r=rm(this.browserContext,()=>this.config);this.autoSyncDetach=r.detach,await this.browserContext.addInitScript({content:n});let i={traceId:this.config.traceId,serviceName:this.config.serviceName,serviceVersion:this.config.serviceVersion,exporter:this.config.exporter,instrumentation:this.config.instrumentation,debug:this.config.debug};await this.browserContext.addInitScript(a=>{let l=globalThis;l.__MCP_DEVTOOLS__||(l.__MCP_DEVTOOLS__={}),l.__MCP_TRACE_ID__=a.traceId,l.__mcpOtel&&typeof l.__mcpOtel.init=="function"?l.__mcpOtel.init(a):(l.__MCP_DEVTOOLS__.otelInitialized=!1,l.__MCP_DEVTOOLS__.otelInitError="__mcpOtel.init is not available (initializer bundle did not install)")},i),this.initialized=!0,K("[otel-controller] init installed: bundle + config init scripts + auto-sync")}isOTELRequest(e){return new URL(e.url()).pathname.startsWith(Tr)}async isInitialized(e){return await e.evaluate(()=>globalThis.__MCP_DEVTOOLS__?.otelInitialized===!0)}async getInitError(e){return await e.evaluate(()=>{let n=globalThis.__MCP_DEVTOOLS__?.otelInitError;if(typeof n=="string"&&n.trim())return n})}async getTraceId(e){return await e.evaluate(()=>{let t=globalThis;if(t.__mcpOtel&&typeof t.__mcpOtel.getTraceId=="function"){let r=t.__mcpOtel.getTraceId();if(typeof r=="string"&&r.trim())return r}let n=t.__MCP_TRACE_ID__;if(typeof n=="string"&&n.trim())return n})}async setTraceId(e,t){this.config.traceId=t,await e.evaluate(n=>{let r=globalThis;r.__mcpOtel&&typeof r.__mcpOtel.setTraceId=="function"?r.__mcpOtel.setTraceId(n):r.__MCP_TRACE_ID__=n},t)}async close(){if(this.autoSyncDetach){try{this.autoSyncDetach()}catch{}this.autoSyncDetach=void 0}this.proxy&&(await this.proxy.uninstall(this.browserContext),this.proxy=void 0)}};var vr=class{static{s(this,"BrowserToolSessionContext")}_sessionId;options;otelController;consoleMessages=[];httpRequests=[];initialized=!1;closed=!1;traceId;_numOfInFlightRequests=0;_lastNetworkActivityTimestamp=0;browserContext;page;constructor(e,t,n,r){this._sessionId=e,this.browserContext=t,this.page=n,this.options=r,this.otelController=new Sr(this.browserContext)}async init(){if(this.closed)throw new Error("Session context is already closed");if(this.initialized)throw new Error("Session context is already initialized");let e=this,t=0;this.page.on("console",r=>{e.consoleMessages.push(e._toConsoleMessage(r,++t)),e.consoleMessages.length>pn&&e.consoleMessages.splice(0,e.consoleMessages.length-pn)}),this.page.on("pageerror",r=>{e.consoleMessages.push(e._errorToConsoleMessage(r,++t)),e.consoleMessages.length>pn&&e.consoleMessages.splice(0,e.consoleMessages.length-pn)});let n=0;this.page.on("request",async r=>{e.otelController.isOTELRequest(r)||(e._numOfInFlightRequests++,e._lastNetworkActivityTimestamp=Date.now())}),this.page.on("requestfinished",async r=>{e.otelController.isOTELRequest(r)||(e._numOfInFlightRequests--,e._lastNetworkActivityTimestamp=Date.now(),e.httpRequests.push(await e._toHttpRequest(r,++n)),e.httpRequests.length>dn&&e.httpRequests.splice(0,e.httpRequests.length-dn))}),this.page.on("requestfailed",async r=>{e.otelController.isOTELRequest(r)||(e._numOfInFlightRequests--,e._lastNetworkActivityTimestamp=Date.now(),e.httpRequests.push(await e._toHttpRequest(r,++n)),e.httpRequests.length>dn&&e.httpRequests.splice(0,e.httpRequests.length-dn))}),this.options.otelEnable&&(this.traceId=tr(),await this.otelController.init({traceId:this.traceId})),this.initialized=!0}_toConsoleMessageLevelName(e){switch(e){case"assert":case"error":return"error";case"warning":return"warning";case"count":case"dir":case"dirxml":case"info":case"log":case"table":case"time":case"timeEnd":return"info";case"clear":case"debug":case"endGroup":case"profile":case"profileEnd":case"startGroup":case"startGroupCollapsed":case"trace":return"debug";default:return"info"}}_toConsoleMessage(e,t){let n=Date.now(),r=this._toConsoleMessageLevelName(e.type()),i=Yt[r].code;return{type:e.type(),text:e.text(),level:{name:r,code:i},location:{url:e.location().url,lineNumber:e.location().lineNumber,columnNumber:e.location().columnNumber},timestamp:n,sequenceNumber:t}}_errorToConsoleMessage(e,t){let n=Date.now();return e instanceof Error?{type:"error",text:e.message,level:{name:"error",code:3},timestamp:n,sequenceNumber:t}:{type:"error",text:String(e),level:{name:"error",code:3},timestamp:n,sequenceNumber:t}}_isBodyLikelyPresent(e,t){return!(t==="HEAD"||t==="OPTIONS"||e===204||e===304||e>=300&&e<400)}async _safeReadResponseBody(e){try{let n=e.request().method(),r=e.status();return this._isBodyLikelyPresent(r,n)?(await e.body()).toString("utf-8"):void 0}catch{return}}async _toHttpRequest(e,t){let n=await e.response();return{url:e.url(),method:e.method(),headers:e.headers(),body:e.postData()||void 0,resourceType:e.resourceType(),failure:e.failure()?.errorText,duration:e.timing().responseEnd,response:n?{status:n.status(),statusText:n.statusText(),headers:n.headers(),body:await this._safeReadResponseBody(n)}:void 0,ok:n?n.ok():!1,timestamp:Math.floor(e.timing().startTime),sequenceNumber:t}}numOfInFlightRequests(){return this._numOfInFlightRequests}lastNetworkActivityTimestamp(){return this._lastNetworkActivityTimestamp}sessionId(){return this._sessionId}async getTraceId(){return this.traceId}async setTraceId(e){if(!this.options.otelEnable)throw new Error("OTEL is not enabled");this.traceId=e,await this.otelController.setTraceId(this.page,e)}getConsoleMessages(){return this.consoleMessages}getHttpRequests(){return this.httpRequests}async close(){if(this.closed)return!1;K(`Closing OTEL controller of the session with id ${this._sessionId} ...`),await this.otelController.close();try{K(`Closing browser context of the session with id ${this._sessionId} ...`),await Tl(this.browserContext)}catch(e){K(`Error occurred while closing browser context of the session with id ${this._sessionId} ...`,e)}return this.consoleMessages.length=0,this.httpRequests.length=0,this.closed=!0,!0}};var Ir=class{static{s(this,"BrowserToolExecutor")}sessionIdProvider;sessionContext;constructor(e){this.sessionIdProvider=e}async _createSessionContext(){let e=await yl(),t=await wl(e.browserContext),n=this.sessionIdProvider(),r=new vr(n,e.browserContext,t,{otelEnable:Vs});return await r.init(),r}async _sessionContext(){return this.sessionContext||(this.sessionContext=await this._createSessionContext(),K(`Created session context on the first tool call for the session with id ${this.sessionContext.sessionId()}`)),this.sessionContext}async executeTool(e,t){K(`Executing tool ${e.name()} with input: ${hn(t)}`);try{let n=await this._sessionContext(),r=await e.handle(n,t);return K(`Executed tool ${e.name()} and got output: ${hn(r)}`),r}catch(n){throw K(`Error occurred while executing ${e.name()}: ${n}`),n}}};var Cr=[...Oi,...Mi,...sa,...Ia,...Ra,..._a,...Da,...ja,...Ka,...ll,...dl];function Sl(o){return new Ir(o)}s(Sl,"createToolExecutor");import{Option as Ht}from"commander";var Ms=class{static{s(this,"BrowserCliProvider")}platform="browser";cliName="browser-devtools-cli";tools=Cr;sessionDescription="Manage browser sessions";cliExamples=["browser-devtools-cli --no-headless interactive","browser-devtools-cli --persistent --no-headless interactive"];bashCompletionOptions="--headless --no-headless --persistent --no-persistent --user-data-dir --use-system-browser --browser-path";bashCompletionCommands="daemon session tools config completion interactive navigation content interaction a11y accessibility o11y react run stub sync figma debug";zshCompletionOptions=` '--headless[Run in headless mode]' \\
770
771
  '--no-headless[Run in headful mode]' \\
771
772
  '--persistent[Use persistent context]' \\
772
773
  '--no-persistent[Use ephemeral context]' \\
@@ -995,7 +996,7 @@ When asked to check for UI problems, layout issues, or visual bugs, ALWAYS follo
995
996
  - Use scroll tool if elements are below the fold before inspection.
996
997
  - For responsive issues, use resize-viewport or resize-window tools to test different sizes.
997
998
  </ui_debugging_policy>
998
- `;var El={serverInfo:{instructions:Il,policies:[Cl]},toolsInfo:{tools:Cr,createToolExecutor:Sl},cliInfo:{cliProvider:vl}};import{z as ke}from"zod";var Er=class{static{s(this,"Connect")}name(){return"debug_connect"}description(){return`
999
+ `;var El={serverInfo:{instructions:Il,policies:[Cl]},toolsInfo:{tools:Cr,createToolExecutor:Sl},cliInfo:{cliProvider:vl}};import{z as Re}from"zod";var Er=class{static{s(this,"Connect")}name(){return"debug_connect"}description(){return`
999
1000
  Connects to a Node.js process for V8 debugging.
1000
1001
 
1001
1002
  Supports multiple connection methods:
@@ -1016,7 +1017,7 @@ When MCP runs in a container connecting to another container:
1016
1017
 
1017
1018
  Once connected, you can use tracepoints, logpoints, exceptionpoints,
1018
1019
  and watch expressions - the same debugging tools available for browser.
1019
- `}inputSchema(){return{pid:ke.number().int().positive().describe("Process ID to connect to").optional(),processName:ke.string().describe('Process name pattern to search for (e.g., "server.js", "api")').optional(),containerId:ke.string().describe("Docker container ID - process runs inside this container").optional(),containerName:ke.string().describe("Docker container name or pattern (e.g., my-node-app) - resolved via docker ps -f name=").optional(),host:ke.string().describe("Inspector host (default: 127.0.0.1); for containerized MCP use host.docker.internal or container name").optional(),port:ke.number().int().positive().describe("Inspector port (default: 9229); for Docker use host-mapped port").optional(),wsUrl:ke.string().describe("Direct WebSocket URL (e.g., ws://127.0.0.1:9229/abc-123)").optional()}}outputSchema(){return{connected:ke.boolean().describe("Whether connection was successful"),pid:ke.number().describe("Process ID"),command:ke.string().optional().describe("Process command line"),containerId:ke.string().optional().describe("Docker container ID when connected via container"),inspectorHost:ke.string().optional().describe("Inspector host"),inspectorPort:ke.number().optional().describe("Inspector port"),webSocketUrl:ke.string().optional().describe("WebSocket URL"),title:ke.string().describe("Target title")}}async handle(e,t){let n=await e.connect({pid:t.pid,processName:t.processName,containerId:t.containerId,containerName:t.containerName,host:t.host,port:t.port,wsUrl:t.wsUrl,activateIfNeeded:!0});return{connected:!0,pid:n.processInfo.pid,command:n.processInfo.command,containerId:n.processInfo.containerId,inspectorHost:n.processInfo.inspectorHost,inspectorPort:n.processInfo.inspectorPort,webSocketUrl:n.processInfo.webSocketUrl,title:n.target.title}}};import{z as sm}from"zod";var Or=class{static{s(this,"Disconnect")}name(){return"debug_disconnect"}description(){return"Disconnects from the currently connected Node.js process and cleans up debugging resources."}inputSchema(){return{}}outputSchema(){return{disconnected:sm.boolean().describe("Whether disconnection was successful")}}async handle(e,t){return await e.disconnect(),{disconnected:!0}}};import{z as we}from"zod";function Ol(o,e,t,n,r){let i;if(e)i=ci(o,e);else if(r){let a=dt(o),l=new Set(a.filter(m=>m.kind===r).map(m=>m.id)),u=An(o);r==="tracepoint"?i=u.filter(m=>l.has(m.probeId)||m.probeId==="__exception__"):i=u.filter(m=>l.has(m.probeId))}else i=An(o);return t!==void 0&&(i=i.filter(a=>a.sequenceNumber>t)),n!==void 0&&(i=i.slice(-n)),i}s(Ol,"_filterSnapshots");var Nr=class{static{s(this,"GetTracepointSnapshots")}name(){return"debug_get-tracepoint-snapshots"}description(){return"Retrieves snapshots captured by tracepoints on the Node.js process. Each snapshot contains call stack with local variables, async stack trace, watch expression results, and traceContext (traceId, spanId) when the process uses @opentelemetry/api."}inputSchema(){return{probeId:we.string().describe("Filter by specific tracepoint ID").optional(),fromSequence:we.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:we.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:we.array(we.any()).describe("Captured snapshots"),count:we.number().describe("Number of snapshots returned")}}async handle(e,t){let n=Ol(e.storeKey,t.probeId,t.fromSequence,t.limit,"tracepoint");return{snapshots:n,count:n.length}}},Pr=class{static{s(this,"GetLogpointSnapshots")}name(){return"debug_get-logpoint-snapshots"}description(){return"Retrieves snapshots captured by logpoints on the Node.js process. Each snapshot contains the log expression result and traceContext (traceId, spanId) when the process uses @opentelemetry/api."}inputSchema(){return{probeId:we.string().describe("Filter by specific logpoint ID").optional(),fromSequence:we.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence").optional(),limit:we.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:we.array(we.any()).describe("Captured snapshots"),count:we.number().describe("Number of snapshots returned")}}async handle(e,t){let n=Ol(e.storeKey,t.probeId,t.fromSequence,t.limit,"logpoint");return{snapshots:n,count:n.length}}},Rr=class{static{s(this,"GetExceptionpointSnapshots")}name(){return"debug_get-exceptionpoint-snapshots"}description(){return"Retrieves snapshots captured by exception breakpoints on the Node.js process. Snapshots include traceContext (traceId, spanId) when the process uses @opentelemetry/api."}inputSchema(){return{fromSequence:we.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence").optional(),limit:we.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:we.array(we.any()).describe("Captured snapshots"),count:we.number().describe("Number of snapshots returned")}}async handle(e,t){let r=An(e.storeKey).filter(i=>i.probeId==="__exception__");return t.fromSequence!==void 0&&(r=r.filter(i=>i.sequenceNumber>t.fromSequence)),t.limit!==void 0&&(r=r.slice(-t.limit)),{snapshots:r,count:r.length}}},kr=class{static{s(this,"ClearTracepointSnapshots")}name(){return"debug_clear-tracepoint-snapshots"}description(){return"Clears tracepoint snapshots. Optionally filter by specific tracepoint ID."}inputSchema(){return{probeId:we.string().describe("Clear only snapshots for this tracepoint ID").optional()}}outputSchema(){return{cleared:we.number().describe("Number of snapshots cleared")}}async handle(e,t){let{clearSnapshots:n,clearSnapshotsByProbe:r}=await import("./core-B3VLZZCP.js");return{cleared:t.probeId?r(e.storeKey,t.probeId):n(e.storeKey)}}},_r=class{static{s(this,"ClearLogpointSnapshots")}name(){return"debug_clear-logpoint-snapshots"}description(){return"Clears logpoint snapshots. Optionally filter by specific logpoint ID."}inputSchema(){return{probeId:we.string().describe("Clear only snapshots for this logpoint ID").optional()}}outputSchema(){return{cleared:we.number().describe("Number of snapshots cleared")}}async handle(e,t){let{clearSnapshotsByProbe:n,clearSnapshots:r}=await import("./core-B3VLZZCP.js");return{cleared:t.probeId?n(e.storeKey,t.probeId):r(e.storeKey)}}},Mr=class{static{s(this,"ClearExceptionpointSnapshots")}name(){return"debug_clear-exceptionpoint-snapshots"}description(){return"Clears all exception snapshots."}inputSchema(){return{}}outputSchema(){return{cleared:we.number().describe("Number of snapshots cleared")}}async handle(e,t){let{clearSnapshotsByProbe:n}=await import("./core-B3VLZZCP.js");return{cleared:n(e.storeKey,"__exception__")}}};import{z as Ne}from"zod";var Br=class{static{s(this,"GetLogs")}name(){return"debug_get-logs"}description(){return"Retrieves console messages/logs from the Node.js process with filtering options."}inputSchema(){return{type:Ne.enum(xe(pt)).transform(rt(pt)).describe(`Type of console messages to retrieve. When specified, messages with equal or higher levels are retrieved. Valid values: ${xe(pt).join(", ")}.`).optional(),search:Ne.string().describe("Text to search for in console messages.").optional(),timestamp:Ne.number().int().nonnegative().describe("Start time filter as Unix epoch timestamp in milliseconds. If provided, only messages recorded at or after this timestamp will be returned.").optional(),sequenceNumber:Ne.number().int().nonnegative().describe("Sequence number for incremental retrieval. If provided, only messages with sequence number greater than this value will be returned.").optional(),limit:Ne.object({count:Ne.number().int().nonnegative().default(0).describe("Max number of messages. 0 = no limit."),from:Ne.enum(["start","end"]).default("end").describe("Which side to keep when truncated.")}).describe("Maximum number of console messages to return.").optional()}}outputSchema(){return{messages:Ne.array(Ne.object({type:Ne.string().describe("Type of the console message."),text:Ne.string().describe("Text of the console message."),location:Ne.object({url:Ne.string().describe("URL of the resource."),lineNumber:Ne.number().nonnegative().describe("0-based line number."),columnNumber:Ne.number().nonnegative().describe("0-based column number.")}).describe("Location of the console message.").optional(),timestamp:Ne.number().int().nonnegative().describe("Unix epoch timestamp (ms)."),sequenceNumber:Ne.number().int().nonnegative().describe("Monotonic sequence number.")})).describe("Retrieved console messages.")}}async handle(e,t){let n=t.type?Yt[t.type]?.code:void 0,r=pi(e.storeKey).filter(l=>!(n!==void 0&&l.level.code<n||t.timestamp&&l.timestamp<t.timestamp||t.sequenceNumber&&l.sequenceNumber<=t.sequenceNumber||t.search&&!l.text.includes(t.search)));return{messages:(t.limit?.count?t.limit.from==="start"?r.slice(0,t.limit.count):r.slice(-t.limit.count):r).map(l=>({type:l.type,text:l.text,location:l.location?{url:l.location.url,lineNumber:l.location.lineNumber,columnNumber:l.location.columnNumber}:void 0,timestamp:l.timestamp,sequenceNumber:l.sequenceNumber}))}}};import{z as ut}from"zod";var Ar=class{static{s(this,"RemoveTracepoint")}name(){return"debug_remove-tracepoint"}description(){return"Removes a tracepoint by its ID."}inputSchema(){return{id:ut.string().describe("Tracepoint ID to remove")}}outputSchema(){return{removed:ut.boolean().describe("Whether the tracepoint was removed")}}async handle(e,t){return{removed:await gn(e.storeKey,t.id)}}},Lr=class{static{s(this,"ListTracepoints")}name(){return"debug_list-tracepoints"}description(){return"Lists all active tracepoints on the Node.js process."}inputSchema(){return{}}outputSchema(){return{tracepoints:ut.array(ut.any()).describe("Active tracepoints")}}async handle(e,t){return{tracepoints:dt(e.storeKey).filter(r=>r.kind==="tracepoint").map(r=>({id:r.id,urlPattern:r.urlPattern,lineNumber:r.lineNumber,columnNumber:r.columnNumber,condition:r.condition,hitCondition:r.hitCondition,hitCount:r.hitCount,resolvedLocations:r.resolvedLocations,enabled:r.enabled}))}}},Fr=class{static{s(this,"ClearTracepoints")}name(){return"debug_clear-tracepoints"}description(){return"Removes all tracepoints from the Node.js process."}inputSchema(){return{}}outputSchema(){return{cleared:ut.number().describe("Number of tracepoints cleared")}}async handle(e,t){let n=dt(e.storeKey).filter(i=>i.kind==="tracepoint"),r=0;for(let i of n)await gn(e.storeKey,i.id)&&r++;return{cleared:r}}},Ur=class{static{s(this,"RemoveLogpoint")}name(){return"debug_remove-logpoint"}description(){return"Removes a logpoint by its ID."}inputSchema(){return{id:ut.string().describe("Logpoint ID to remove")}}outputSchema(){return{removed:ut.boolean().describe("Whether the logpoint was removed")}}async handle(e,t){return{removed:await gn(e.storeKey,t.id)}}},Hr=class{static{s(this,"ListLogpoints")}name(){return"debug_list-logpoints"}description(){return"Lists all active logpoints on the Node.js process."}inputSchema(){return{}}outputSchema(){return{logpoints:ut.array(ut.any()).describe("Active logpoints")}}async handle(e,t){return{logpoints:dt(e.storeKey).filter(r=>r.kind==="logpoint").map(r=>({id:r.id,urlPattern:r.urlPattern,lineNumber:r.lineNumber,logExpression:r.logExpression,condition:r.condition,hitCondition:r.hitCondition,hitCount:r.hitCount,resolvedLocations:r.resolvedLocations,enabled:r.enabled}))}}},Wr=class{static{s(this,"ClearLogpoints")}name(){return"debug_clear-logpoints"}description(){return"Removes all logpoints from the Node.js process."}inputSchema(){return{}}outputSchema(){return{cleared:ut.number().describe("Number of logpoints cleared")}}async handle(e,t){let n=dt(e.storeKey).filter(i=>i.kind==="logpoint"),r=0;for(let i of n)await gn(e.storeKey,i.id)&&r++;return{cleared:r}}};import{z as Ds}from"zod";var qr=class{static{s(this,"PutExceptionpoint")}name(){return"debug_put-exceptionpoint"}description(){return`
1020
+ `}inputSchema(){return{pid:Re.number().int().positive().describe("Process ID to connect to").optional(),processName:Re.string().describe('Process name pattern to search for (e.g., "server.js", "api")').optional(),containerId:Re.string().describe("Docker container ID - process runs inside this container").optional(),containerName:Re.string().describe("Docker container name or pattern (e.g., my-node-app) - resolved via docker ps -f name=").optional(),host:Re.string().describe("Inspector host (default: 127.0.0.1); for containerized MCP use host.docker.internal or container name").optional(),port:Re.number().int().positive().describe("Inspector port (default: 9229); for Docker use host-mapped port").optional(),wsUrl:Re.string().describe("Direct WebSocket URL (e.g., ws://127.0.0.1:9229/abc-123)").optional()}}outputSchema(){return{connected:Re.boolean().describe("Whether connection was successful"),pid:Re.number().describe("Process ID"),command:Re.string().optional().describe("Process command line"),containerId:Re.string().optional().describe("Docker container ID when connected via container"),inspectorHost:Re.string().optional().describe("Inspector host"),inspectorPort:Re.number().optional().describe("Inspector port"),webSocketUrl:Re.string().optional().describe("WebSocket URL"),title:Re.string().describe("Target title")}}async handle(e,t){let n=await e.connect({pid:t.pid,processName:t.processName,containerId:t.containerId,containerName:t.containerName,host:t.host,port:t.port,wsUrl:t.wsUrl,activateIfNeeded:!0});return{connected:!0,pid:n.processInfo.pid,command:n.processInfo.command,containerId:n.processInfo.containerId,inspectorHost:n.processInfo.inspectorHost,inspectorPort:n.processInfo.inspectorPort,webSocketUrl:n.processInfo.webSocketUrl,title:n.target.title}}};import{z as sm}from"zod";var Or=class{static{s(this,"Disconnect")}name(){return"debug_disconnect"}description(){return"Disconnects from the currently connected Node.js process and cleans up debugging resources."}inputSchema(){return{}}outputSchema(){return{disconnected:sm.boolean().describe("Whether disconnection was successful")}}async handle(e,t){return await e.disconnect(),{disconnected:!0}}};import{z as we}from"zod";function Ol(o,e,t,n,r){let i;if(e)i=ci(o,e);else if(r){let a=dt(o),l=new Set(a.filter(m=>m.kind===r).map(m=>m.id)),u=An(o);r==="tracepoint"?i=u.filter(m=>l.has(m.probeId)||m.probeId==="__exception__"):i=u.filter(m=>l.has(m.probeId))}else i=An(o);return t!==void 0&&(i=i.filter(a=>a.sequenceNumber>t)),n!==void 0&&(i=i.slice(-n)),i}s(Ol,"_filterSnapshots");var Nr=class{static{s(this,"GetTracepointSnapshots")}name(){return"debug_get-tracepoint-snapshots"}description(){return"Retrieves snapshots captured by tracepoints on the Node.js process. Each snapshot contains call stack with local variables, async stack trace, watch expression results, and traceContext (traceId, spanId) when the process uses @opentelemetry/api."}inputSchema(){return{probeId:we.string().describe("Filter by specific tracepoint ID").optional(),fromSequence:we.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence (for polling)").optional(),limit:we.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:we.array(we.any()).describe("Captured snapshots"),count:we.number().describe("Number of snapshots returned")}}async handle(e,t){let n=Ol(e.storeKey,t.probeId,t.fromSequence,t.limit,"tracepoint");return{snapshots:n,count:n.length}}},Pr=class{static{s(this,"GetLogpointSnapshots")}name(){return"debug_get-logpoint-snapshots"}description(){return"Retrieves snapshots captured by logpoints on the Node.js process. Each snapshot contains the log expression result and traceContext (traceId, spanId) when the process uses @opentelemetry/api."}inputSchema(){return{probeId:we.string().describe("Filter by specific logpoint ID").optional(),fromSequence:we.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence").optional(),limit:we.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:we.array(we.any()).describe("Captured snapshots"),count:we.number().describe("Number of snapshots returned")}}async handle(e,t){let n=Ol(e.storeKey,t.probeId,t.fromSequence,t.limit,"logpoint");return{snapshots:n,count:n.length}}},kr=class{static{s(this,"GetExceptionpointSnapshots")}name(){return"debug_get-exceptionpoint-snapshots"}description(){return"Retrieves snapshots captured by exception breakpoints on the Node.js process. Snapshots include traceContext (traceId, spanId) when the process uses @opentelemetry/api."}inputSchema(){return{fromSequence:we.number().int().nonnegative().describe("Return snapshots with sequence number > fromSequence").optional(),limit:we.number().int().positive().describe("Maximum number of snapshots to return").optional()}}outputSchema(){return{snapshots:we.array(we.any()).describe("Captured snapshots"),count:we.number().describe("Number of snapshots returned")}}async handle(e,t){let r=An(e.storeKey).filter(i=>i.probeId==="__exception__");return t.fromSequence!==void 0&&(r=r.filter(i=>i.sequenceNumber>t.fromSequence)),t.limit!==void 0&&(r=r.slice(-t.limit)),{snapshots:r,count:r.length}}},Rr=class{static{s(this,"ClearTracepointSnapshots")}name(){return"debug_clear-tracepoint-snapshots"}description(){return"Clears tracepoint snapshots. Optionally filter by specific tracepoint ID."}inputSchema(){return{probeId:we.string().describe("Clear only snapshots for this tracepoint ID").optional()}}outputSchema(){return{cleared:we.number().describe("Number of snapshots cleared")}}async handle(e,t){let{clearSnapshots:n,clearSnapshotsByProbe:r}=await import("./core-B3VLZZCP.js");return{cleared:t.probeId?r(e.storeKey,t.probeId):n(e.storeKey)}}},_r=class{static{s(this,"ClearLogpointSnapshots")}name(){return"debug_clear-logpoint-snapshots"}description(){return"Clears logpoint snapshots. Optionally filter by specific logpoint ID."}inputSchema(){return{probeId:we.string().describe("Clear only snapshots for this logpoint ID").optional()}}outputSchema(){return{cleared:we.number().describe("Number of snapshots cleared")}}async handle(e,t){let{clearSnapshotsByProbe:n,clearSnapshots:r}=await import("./core-B3VLZZCP.js");return{cleared:t.probeId?n(e.storeKey,t.probeId):r(e.storeKey)}}},Mr=class{static{s(this,"ClearExceptionpointSnapshots")}name(){return"debug_clear-exceptionpoint-snapshots"}description(){return"Clears all exception snapshots."}inputSchema(){return{}}outputSchema(){return{cleared:we.number().describe("Number of snapshots cleared")}}async handle(e,t){let{clearSnapshotsByProbe:n}=await import("./core-B3VLZZCP.js");return{cleared:n(e.storeKey,"__exception__")}}};import{z as Ne}from"zod";var Br=class{static{s(this,"GetLogs")}name(){return"debug_get-logs"}description(){return"Retrieves console messages/logs from the Node.js process with filtering options."}inputSchema(){return{type:Ne.enum(xe(pt)).transform(rt(pt)).describe(`Type of console messages to retrieve. When specified, messages with equal or higher levels are retrieved. Valid values: ${xe(pt).join(", ")}.`).optional(),search:Ne.string().describe("Text to search for in console messages.").optional(),timestamp:Ne.number().int().nonnegative().describe("Start time filter as Unix epoch timestamp in milliseconds. If provided, only messages recorded at or after this timestamp will be returned.").optional(),sequenceNumber:Ne.number().int().nonnegative().describe("Sequence number for incremental retrieval. If provided, only messages with sequence number greater than this value will be returned.").optional(),limit:Ne.object({count:Ne.number().int().nonnegative().default(0).describe("Max number of messages. 0 = no limit."),from:Ne.enum(["start","end"]).default("end").describe("Which side to keep when truncated.")}).describe("Maximum number of console messages to return.").optional()}}outputSchema(){return{messages:Ne.array(Ne.object({type:Ne.string().describe("Type of the console message."),text:Ne.string().describe("Text of the console message."),location:Ne.object({url:Ne.string().describe("URL of the resource."),lineNumber:Ne.number().nonnegative().describe("0-based line number."),columnNumber:Ne.number().nonnegative().describe("0-based column number.")}).describe("Location of the console message.").optional(),timestamp:Ne.number().int().nonnegative().describe("Unix epoch timestamp (ms)."),sequenceNumber:Ne.number().int().nonnegative().describe("Monotonic sequence number.")})).describe("Retrieved console messages.")}}async handle(e,t){let n=t.type?Yt[t.type]?.code:void 0,r=pi(e.storeKey).filter(l=>!(n!==void 0&&l.level.code<n||t.timestamp&&l.timestamp<t.timestamp||t.sequenceNumber&&l.sequenceNumber<=t.sequenceNumber||t.search&&!l.text.includes(t.search)));return{messages:(t.limit?.count?t.limit.from==="start"?r.slice(0,t.limit.count):r.slice(-t.limit.count):r).map(l=>({type:l.type,text:l.text,location:l.location?{url:l.location.url,lineNumber:l.location.lineNumber,columnNumber:l.location.columnNumber}:void 0,timestamp:l.timestamp,sequenceNumber:l.sequenceNumber}))}}};import{z as ut}from"zod";var Ar=class{static{s(this,"RemoveTracepoint")}name(){return"debug_remove-tracepoint"}description(){return"Removes a tracepoint by its ID."}inputSchema(){return{id:ut.string().describe("Tracepoint ID to remove")}}outputSchema(){return{removed:ut.boolean().describe("Whether the tracepoint was removed")}}async handle(e,t){return{removed:await gn(e.storeKey,t.id)}}},Lr=class{static{s(this,"ListTracepoints")}name(){return"debug_list-tracepoints"}description(){return"Lists all active tracepoints on the Node.js process."}inputSchema(){return{}}outputSchema(){return{tracepoints:ut.array(ut.any()).describe("Active tracepoints")}}async handle(e,t){return{tracepoints:dt(e.storeKey).filter(r=>r.kind==="tracepoint").map(r=>({id:r.id,urlPattern:r.urlPattern,lineNumber:r.lineNumber,columnNumber:r.columnNumber,condition:r.condition,hitCondition:r.hitCondition,hitCount:r.hitCount,resolvedLocations:r.resolvedLocations,enabled:r.enabled}))}}},Fr=class{static{s(this,"ClearTracepoints")}name(){return"debug_clear-tracepoints"}description(){return"Removes all tracepoints from the Node.js process."}inputSchema(){return{}}outputSchema(){return{cleared:ut.number().describe("Number of tracepoints cleared")}}async handle(e,t){let n=dt(e.storeKey).filter(i=>i.kind==="tracepoint"),r=0;for(let i of n)await gn(e.storeKey,i.id)&&r++;return{cleared:r}}},Ur=class{static{s(this,"RemoveLogpoint")}name(){return"debug_remove-logpoint"}description(){return"Removes a logpoint by its ID."}inputSchema(){return{id:ut.string().describe("Logpoint ID to remove")}}outputSchema(){return{removed:ut.boolean().describe("Whether the logpoint was removed")}}async handle(e,t){return{removed:await gn(e.storeKey,t.id)}}},Hr=class{static{s(this,"ListLogpoints")}name(){return"debug_list-logpoints"}description(){return"Lists all active logpoints on the Node.js process."}inputSchema(){return{}}outputSchema(){return{logpoints:ut.array(ut.any()).describe("Active logpoints")}}async handle(e,t){return{logpoints:dt(e.storeKey).filter(r=>r.kind==="logpoint").map(r=>({id:r.id,urlPattern:r.urlPattern,lineNumber:r.lineNumber,logExpression:r.logExpression,condition:r.condition,hitCondition:r.hitCondition,hitCount:r.hitCount,resolvedLocations:r.resolvedLocations,enabled:r.enabled}))}}},Wr=class{static{s(this,"ClearLogpoints")}name(){return"debug_clear-logpoints"}description(){return"Removes all logpoints from the Node.js process."}inputSchema(){return{}}outputSchema(){return{cleared:ut.number().describe("Number of logpoints cleared")}}async handle(e,t){let n=dt(e.storeKey).filter(i=>i.kind==="logpoint"),r=0;for(let i of n)await gn(e.storeKey,i.id)&&r++;return{cleared:r}}};import{z as Ds}from"zod";var qr=class{static{s(this,"PutExceptionpoint")}name(){return"debug_put-exceptionpoint"}description(){return`
1020
1021
  Sets the exception tracepoint state for a Node.js process:
1021
1022
  - "none": Don't capture on exceptions
1022
1023
  - "uncaught": Capture only on uncaught exceptions
@@ -1070,7 +1071,7 @@ Adds a watch expression to be evaluated at every tracepoint hit on the Node.js p
1070
1071
  Watch expression results are included in the snapshot's watchResults field.
1071
1072
 
1072
1073
  Examples: "user.name", "this.state", "items.length", "JSON.stringify(config)"
1073
- `}inputSchema(){return{expression:Nt.string().describe("JavaScript expression to watch")}}outputSchema(){return{id:Nt.string().describe("Watch expression ID"),expression:Nt.string().describe("The expression")}}async handle(e,t){let n=di(e.storeKey,t.expression);return{id:n.id,expression:n.expression}}},Kr=class{static{s(this,"RemoveWatch")}name(){return"debug_remove-watch"}description(){return"Removes a watch expression by its ID."}inputSchema(){return{id:Nt.string().describe("Watch expression ID to remove")}}outputSchema(){return{removed:Nt.boolean().describe("Whether the watch was removed")}}async handle(e,t){return{removed:bi(e.storeKey,t.id)}}},Xr=class{static{s(this,"ListWatches")}name(){return"debug_list-watches"}description(){return"Lists all active watch expressions."}inputSchema(){return{}}outputSchema(){return{watches:Nt.array(Nt.any()).describe("Active watch expressions")}}async handle(e,t){return{watches:Ln(e.storeKey)}}},Yr=class{static{s(this,"ClearWatches")}name(){return"debug_clear-watches"}description(){return"Removes all watch expressions."}inputSchema(){return{}}outputSchema(){return{cleared:Nt.number().describe("Number of watches cleared")}}async handle(e,t){return{cleared:hi(e.storeKey)}}};var Nl=[new Er,new Or,new Vr,new jr,new Ar,new Lr,new Fr,new $r,new Ur,new Hr,new Wr,new qr,new Nr,new kr,new Pr,new _r,new Rr,new Mr,new Br,new zr,new Gr,new Kr,new Xr,new Yr];import{z as Bs}from"zod";var Jr=class{static{s(this,"RunJsInNode")}name(){return"run_js-in-node"}description(){return`
1074
+ `}inputSchema(){return{expression:Nt.string().describe("JavaScript expression to watch")}}outputSchema(){return{id:Nt.string().describe("Watch expression ID"),expression:Nt.string().describe("The expression")}}async handle(e,t){let n=di(e.storeKey,t.expression);return{id:n.id,expression:n.expression}}},Kr=class{static{s(this,"RemoveWatch")}name(){return"debug_remove-watch"}description(){return"Removes a watch expression by its ID."}inputSchema(){return{id:Nt.string().describe("Watch expression ID to remove")}}outputSchema(){return{removed:Nt.boolean().describe("Whether the watch was removed")}}async handle(e,t){return{removed:bi(e.storeKey,t.id)}}},Xr=class{static{s(this,"ListWatches")}name(){return"debug_list-watches"}description(){return"Lists all active watch expressions."}inputSchema(){return{}}outputSchema(){return{watches:Nt.array(Nt.any()).describe("Active watch expressions")}}async handle(e,t){return{watches:Ln(e.storeKey)}}},Yr=class{static{s(this,"ClearWatches")}name(){return"debug_clear-watches"}description(){return"Removes all watch expressions."}inputSchema(){return{}}outputSchema(){return{cleared:Nt.number().describe("Number of watches cleared")}}async handle(e,t){return{cleared:hi(e.storeKey)}}};var Nl=[new Er,new Or,new Vr,new jr,new Ar,new Lr,new Fr,new $r,new Ur,new Hr,new Wr,new qr,new Nr,new Rr,new Pr,new _r,new kr,new Mr,new Br,new zr,new Gr,new Kr,new Xr,new Yr];import{z as Bs}from"zod";var Jr=class{static{s(this,"RunJsInNode")}name(){return"run_js-in-node"}description(){return`
1074
1075
  Runs custom JavaScript INSIDE the connected Node.js process using CDP Runtime.evaluate.
1075
1076
 
1076
1077
  This code executes in the NODE PROCESS CONTEXT (real Node.js environment):
@@ -1089,13 +1090,13 @@ Notes:
1089
1090
  - Execution blocks the Node event loop until the script completes
1090
1091
  - Long-running scripts will block the process; use short expressions
1091
1092
  - Return value must be serializable (JSON-compatible)
1092
- `}inputSchema(){return{script:Bs.string().describe("JavaScript code to execute in the Node process."),timeoutMs:Bs.number().int().min(100).max(3e4).describe("Max evaluation time in milliseconds (default: 5000, max: 30000).").optional()}}outputSchema(){return{result:Bs.any().describe("The result of the evaluation. Can be primitives, arrays, or objects. Must be serializable (JSON-compatible).")}}async handle(e,t){return{result:await fi(e.storeKey,t.script,t.timeoutMs??5e3)}}};var Pl=[new Jr];import{EventEmitter as im}from"node:events";import{WebSocket as am}from"ws";var As=class extends im{static{s(this,"NodeCDPSession")}ws=null;reqId=0;pending=new Map;connected=!1;wsUrl;constructor(e){super(),this.wsUrl=e}async connect(){if(!this.connected)return new Promise((e,t)=>{this.ws=new am(this.wsUrl);let n=setTimeout(()=>{t(new Error(`Connection timeout to ${this.wsUrl}`)),this.ws?.close()},1e4);this.ws.on("open",()=>{clearTimeout(n),this.connected=!0,e()}),this.ws.on("error",r=>{clearTimeout(n),this.connected||t(r)}),this.ws.on("close",()=>{this.connected=!1;for(let[r,i]of this.pending)i.reject(new Error("CDP session closed"));this.pending.clear()}),this.ws.on("message",r=>{try{let i=JSON.parse(r.toString());this._handleMessage(i)}catch{}})})}async send(e,t){if(!this.ws||!this.connected)throw new Error("CDP session is not connected");let n=++this.reqId;return new Promise((r,i)=>{this.pending.set(n,{resolve:r,reject:i});let a=JSON.stringify({id:n,method:e,params:t||{}});this.ws.send(a,l=>{l&&(this.pending.delete(n),i(l))}),setTimeout(()=>{this.pending.has(n)&&(this.pending.delete(n),i(new Error(`CDP command timeout: ${e}`)))},3e4)})}async detach(){if(this.ws){this.connected=!1,this.ws.close(),this.ws=null;for(let[,e]of this.pending)e.reject(new Error("CDP session detached"));this.pending.clear()}}isConnected(){return this.connected}_handleMessage(e){if(e.id!==void 0){let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.error?t.reject(new Error(`CDP error: ${e.error.message||JSON.stringify(e.error)}`)):t.resolve(e.result||{}))}else e.method&&this.emit(e.method,e.params)}};async function vn(o){let e=new As(o);return await e.connect(),e}s(vn,"createNodeCDPSession");import{execSync as In}from"node:child_process";import*as Rl from"node:http";var Pt="127.0.0.1",ln=9229,Ls=1e4,kl=200,lm=20;async function Qr(o=Pt,e=ln,t=5e3){return new Promise((n,r)=>{let i=setTimeout(()=>{r(new Error(`Inspector discovery timeout on ${o}:${e}`))},t),a=Rl.get(`http://${o}:${e}/json/list`,l=>{let u="";l.on("data",m=>{u+=m}),l.on("end",()=>{clearTimeout(i);try{let m=JSON.parse(u);n(m)}catch{r(new Error(`Invalid response from inspector at ${o}:${e}`))}})});a.on("error",l=>{clearTimeout(i),r(new Error(`Cannot reach inspector at ${o}:${e}: ${l.message}`))}),a.end()})}s(Qr,"discoverInspectorTargets");async function um(o=Pt,e=ln,t=lm){for(let n=e;n<e+t;n++)try{let r=await Qr(o,n,1e3);if(r.length>0)return{port:n,targets:r}}catch{}return null}s(um,"scanForInspector");function cm(o){try{let e=process.platform,t;e==="win32"?t=In(`wmic process where "name like '%node%'" get ProcessId,CommandLine /format:csv`,{encoding:"utf-8",timeout:5e3}):t=In('ps aux | grep -E "[n]ode|[t]s-node|[n]px"',{encoding:"utf-8",timeout:5e3});let n=[];for(let r of t.split(`
1093
- `)){let i=r.trim();if(i)if(e==="win32"){let a=i.split(",");if(a.length>=3){let l=parseInt(a[a.length-1],10),u=a.slice(1,-1).join(",");!isNaN(l)&&l>0&&n.push({pid:l,command:u})}}else{let a=i.split(/\s+/);if(a.length>=11){let l=parseInt(a[1],10),u=a.slice(10).join(" ");!isNaN(l)&&l>0&&n.push({pid:l,command:u})}}}if(o){let r=new RegExp(o,"i");return n.filter(i=>r.test(i.command))}return n}catch{return[]}}s(cm,"findNodeProcesses");async function mm(o,e=Pt,t=Ls){if(process.platform==="win32")throw new Error("SIGUSR1 activation is not supported on Windows. Start the Node.js process with --inspect flag or NODE_OPTIONS=--inspect instead.");try{process.kill(o,0)}catch{throw new Error(`Process ${o} does not exist or is not accessible`)}K(`Sending SIGUSR1 to process ${o} to activate V8 Inspector...`),process.kill(o,"SIGUSR1");let n=Date.now();for(;Date.now()-n<t;){let r=await um(e,ln,10);if(r)return K(`Inspector activated on port ${r.port} for process ${o}`),r;await new Promise(i=>setTimeout(i,kl))}throw new Error(`Timeout waiting for inspector to activate on process ${o}`)}s(mm,"activateInspector");function pm(o){try{let t=In(`docker ps -q -f name=${o}`,{encoding:"utf-8",timeout:5e3}).trim().split(`
1094
- `).filter(Boolean);return t.length===0?null:(t.length>1&&K(`Multiple containers match "${o}", using first: ${t[0]}`),t[0])}catch(e){if(/Cannot connect to the Docker daemon|docker: command not found/i.test(e.message??""))throw new Error(`${e.message} When MCP runs in a container, mount /var/run/docker.sock and ensure the docker CLI is available.`);return null}}s(pm,"resolveContainerId");async function dm(o,e=Pt,t=ln,n=Ls){if(process.platform==="win32")throw new Error("Docker container activation may have limitations on Windows. Ensure the container has port 9229 exposed and Node is started with --inspect.");let r;try{let a=In(`docker exec ${o} sh -c "ps aux 2>/dev/null | grep '[n]ode' | head -1"`,{encoding:"utf-8",timeout:5e3}).trim();if(!a)throw new Error(`No Node.js process found inside container ${o}`);if(r=a.split(/\s+/).filter(Boolean)[1]||"",!r||!/^\d+$/.test(r))throw new Error(`Could not parse Node PID from container ${o}`)}catch(a){if(a.message?.includes("No Node.js process"))throw a;let l=/Cannot connect to the Docker daemon|docker: command not found/i.test(a.message??"")?" When MCP runs in a container, mount /var/run/docker.sock and ensure the docker CLI is available.":"";throw new Error(`Cannot find Node process in container ${o}: ${a.message}. Ensure Docker is running and the container has a Node.js process.${l}`)}K(`Sending SIGUSR1 to Node process ${r} inside container ${o}...`);try{In(`docker exec ${o} kill -USR1 ${r}`,{encoding:"utf-8",timeout:5e3})}catch(a){let l=/Cannot connect to the Docker daemon|docker: command not found/i.test(a.message??"")?" When MCP runs in a container, mount /var/run/docker.sock and ensure the docker CLI is available.":"";throw new Error(`Failed to send SIGUSR1 to container ${o}: ${a.message}${l}`)}let i=Date.now();for(;Date.now()-i<n;){try{let a=await Qr(e,t,2e3);if(a.length>0)return K(`Inspector active at ${e}:${t} for container ${o}`),{port:t,targets:a}}catch{}await new Promise(a=>setTimeout(a,kl))}throw new Error(`Timeout waiting for inspector from container ${o}. Ensure the container exposes port 9229 (e.g. docker run -p 9229:9229 ...) and Node is started with --inspect or --inspect=0.0.0.0:9229.`)}s(dm,"activateInspectorInContainer");async function _l(o){let e=o.host||Pt,t=o.timeoutMs||Ls,n=o.activateIfNeeded!==!1;if(o.wsUrl)return K(`Connecting to Node.js inspector via WebSocket: ${o.wsUrl}`),{session:await vn(o.wsUrl),processInfo:{pid:0,inspectorActive:!0,webSocketUrl:o.wsUrl},target:{id:"direct",type:"node",title:"Direct WebSocket connection",url:"",webSocketDebuggerUrl:o.wsUrl}};let r=o.containerId??null;if(!r&&o.containerName&&(r=pm(o.containerName),!r))throw new Error(`No running container found matching name: ${o.containerName}`);if(r){let m=o.port||ln,c=[];try{c=await Qr(e,m,3e3)}catch{}if(c.length===0&&n&&(K(`Inspector not active. Activating via SIGUSR1 in container ${r}...`),c=(await dm(r,e,m,t)).targets),c.length===0)throw new Error(`Cannot connect to Node.js in container ${r}. Inspector not active. Ensure port 9229 is exposed (e.g. -p 9229:9229) and use activateIfNeeded or start Node with --inspect.`);let p=c[0],b=p.webSocketDebuggerUrl;return e!==Pt&&(b=b.replace(/ws:\/\/[^:]+:/,`ws://${e}:`)),{session:await vn(b),processInfo:{pid:0,inspectorActive:!0,inspectorHost:e,inspectorPort:m,webSocketUrl:b,containerId:r},target:p}}let i=o.pid,a;if(!i&&o.processName){let m=cm(o.processName);if(m.length===0)throw new Error(`No Node.js process found matching: ${o.processName}`);if(m.length>1){let c=m.map(p=>` PID ${p.pid}: ${p.command}`).join(`
1093
+ `}inputSchema(){return{script:Bs.string().describe("JavaScript code to execute in the Node process."),timeoutMs:Bs.number().int().min(100).max(3e4).describe("Max evaluation time in milliseconds (default: 5000, max: 30000).").optional()}}outputSchema(){return{result:Bs.any().describe("The result of the evaluation. Can be primitives, arrays, or objects. Must be serializable (JSON-compatible).")}}async handle(e,t){return{result:await fi(e.storeKey,t.script,t.timeoutMs??5e3)}}};var Pl=[new Jr];import{EventEmitter as im}from"node:events";import{WebSocket as am}from"ws";var As=class extends im{static{s(this,"NodeCDPSession")}ws=null;reqId=0;pending=new Map;connected=!1;wsUrl;constructor(e){super(),this.wsUrl=e}async connect(){if(!this.connected)return new Promise((e,t)=>{this.ws=new am(this.wsUrl);let n=setTimeout(()=>{t(new Error(`Connection timeout to ${this.wsUrl}`)),this.ws?.close()},1e4);this.ws.on("open",()=>{clearTimeout(n),this.connected=!0,e()}),this.ws.on("error",r=>{clearTimeout(n),this.connected||t(r)}),this.ws.on("close",()=>{this.connected=!1;for(let[r,i]of this.pending)i.reject(new Error("CDP session closed"));this.pending.clear()}),this.ws.on("message",r=>{try{let i=JSON.parse(r.toString());this._handleMessage(i)}catch{}})})}async send(e,t){if(!this.ws||!this.connected)throw new Error("CDP session is not connected");let n=++this.reqId;return new Promise((r,i)=>{this.pending.set(n,{resolve:r,reject:i});let a=JSON.stringify({id:n,method:e,params:t||{}});this.ws.send(a,l=>{l&&(this.pending.delete(n),i(l))}),setTimeout(()=>{this.pending.has(n)&&(this.pending.delete(n),i(new Error(`CDP command timeout: ${e}`)))},3e4)})}async detach(){if(this.ws){this.connected=!1,this.ws.close(),this.ws=null;for(let[,e]of this.pending)e.reject(new Error("CDP session detached"));this.pending.clear()}}isConnected(){return this.connected}_handleMessage(e){if(e.id!==void 0){let t=this.pending.get(e.id);t&&(this.pending.delete(e.id),e.error?t.reject(new Error(`CDP error: ${e.error.message||JSON.stringify(e.error)}`)):t.resolve(e.result||{}))}else e.method&&this.emit(e.method,e.params)}};async function vn(o){let e=new As(o);return await e.connect(),e}s(vn,"createNodeCDPSession");import{execSync as In}from"node:child_process";import*as kl from"node:http";var Pt="127.0.0.1",ln=9229,Ls=1e4,Rl=200,lm=20;async function Qr(o=Pt,e=ln,t=5e3){return new Promise((n,r)=>{let i=setTimeout(()=>{r(new Error(`Inspector discovery timeout on ${o}:${e}`))},t),a=kl.get(`http://${o}:${e}/json/list`,l=>{let u="";l.on("data",m=>{u+=m}),l.on("end",()=>{clearTimeout(i);try{let m=JSON.parse(u);n(m)}catch{r(new Error(`Invalid response from inspector at ${o}:${e}`))}})});a.on("error",l=>{clearTimeout(i),r(new Error(`Cannot reach inspector at ${o}:${e}: ${l.message}`))}),a.end()})}s(Qr,"discoverInspectorTargets");async function um(o=Pt,e=ln,t=lm){for(let n=e;n<e+t;n++)try{let r=await Qr(o,n,1e3);if(r.length>0)return{port:n,targets:r}}catch{}return null}s(um,"scanForInspector");function cm(o){try{let e=process.platform,t;e==="win32"?t=In(`wmic process where "name like '%node%'" get ProcessId,CommandLine /format:csv`,{encoding:"utf-8",timeout:5e3}):t=In('ps aux | grep -E "[n]ode|[t]s-node|[n]px"',{encoding:"utf-8",timeout:5e3});let n=[];for(let r of t.split(`
1094
+ `)){let i=r.trim();if(i)if(e==="win32"){let a=i.split(",");if(a.length>=3){let l=parseInt(a[a.length-1],10),u=a.slice(1,-1).join(",");!isNaN(l)&&l>0&&n.push({pid:l,command:u})}}else{let a=i.split(/\s+/);if(a.length>=11){let l=parseInt(a[1],10),u=a.slice(10).join(" ");!isNaN(l)&&l>0&&n.push({pid:l,command:u})}}}if(o){let r=new RegExp(o,"i");return n.filter(i=>r.test(i.command))}return n}catch{return[]}}s(cm,"findNodeProcesses");async function mm(o,e=Pt,t=Ls){if(process.platform==="win32")throw new Error("SIGUSR1 activation is not supported on Windows. Start the Node.js process with --inspect flag or NODE_OPTIONS=--inspect instead.");try{process.kill(o,0)}catch{throw new Error(`Process ${o} does not exist or is not accessible`)}K(`Sending SIGUSR1 to process ${o} to activate V8 Inspector...`),process.kill(o,"SIGUSR1");let n=Date.now();for(;Date.now()-n<t;){let r=await um(e,ln,10);if(r)return K(`Inspector activated on port ${r.port} for process ${o}`),r;await new Promise(i=>setTimeout(i,Rl))}throw new Error(`Timeout waiting for inspector to activate on process ${o}`)}s(mm,"activateInspector");function pm(o){try{let t=In(`docker ps -q -f name=${o}`,{encoding:"utf-8",timeout:5e3}).trim().split(`
1095
+ `).filter(Boolean);return t.length===0?null:(t.length>1&&K(`Multiple containers match "${o}", using first: ${t[0]}`),t[0])}catch(e){if(/Cannot connect to the Docker daemon|docker: command not found/i.test(e.message??""))throw new Error(`${e.message} When MCP runs in a container, mount /var/run/docker.sock and ensure the docker CLI is available.`);return null}}s(pm,"resolveContainerId");async function dm(o,e=Pt,t=ln,n=Ls){if(process.platform==="win32")throw new Error("Docker container activation may have limitations on Windows. Ensure the container has port 9229 exposed and Node is started with --inspect.");let r;try{let a=In(`docker exec ${o} sh -c "ps aux 2>/dev/null | grep '[n]ode' | head -1"`,{encoding:"utf-8",timeout:5e3}).trim();if(!a)throw new Error(`No Node.js process found inside container ${o}`);if(r=a.split(/\s+/).filter(Boolean)[1]||"",!r||!/^\d+$/.test(r))throw new Error(`Could not parse Node PID from container ${o}`)}catch(a){if(a.message?.includes("No Node.js process"))throw a;let l=/Cannot connect to the Docker daemon|docker: command not found/i.test(a.message??"")?" When MCP runs in a container, mount /var/run/docker.sock and ensure the docker CLI is available.":"";throw new Error(`Cannot find Node process in container ${o}: ${a.message}. Ensure Docker is running and the container has a Node.js process.${l}`)}K(`Sending SIGUSR1 to Node process ${r} inside container ${o}...`);try{In(`docker exec ${o} kill -USR1 ${r}`,{encoding:"utf-8",timeout:5e3})}catch(a){let l=/Cannot connect to the Docker daemon|docker: command not found/i.test(a.message??"")?" When MCP runs in a container, mount /var/run/docker.sock and ensure the docker CLI is available.":"";throw new Error(`Failed to send SIGUSR1 to container ${o}: ${a.message}${l}`)}let i=Date.now();for(;Date.now()-i<n;){try{let a=await Qr(e,t,2e3);if(a.length>0)return K(`Inspector active at ${e}:${t} for container ${o}`),{port:t,targets:a}}catch{}await new Promise(a=>setTimeout(a,Rl))}throw new Error(`Timeout waiting for inspector from container ${o}. Ensure the container exposes port 9229 (e.g. docker run -p 9229:9229 ...) and Node is started with --inspect or --inspect=0.0.0.0:9229.`)}s(dm,"activateInspectorInContainer");async function _l(o){let e=o.host||Pt,t=o.timeoutMs||Ls,n=o.activateIfNeeded!==!1;if(o.wsUrl)return K(`Connecting to Node.js inspector via WebSocket: ${o.wsUrl}`),{session:await vn(o.wsUrl),processInfo:{pid:0,inspectorActive:!0,webSocketUrl:o.wsUrl},target:{id:"direct",type:"node",title:"Direct WebSocket connection",url:"",webSocketDebuggerUrl:o.wsUrl}};let r=o.containerId??null;if(!r&&o.containerName&&(r=pm(o.containerName),!r))throw new Error(`No running container found matching name: ${o.containerName}`);if(r){let m=o.port||ln,c=[];try{c=await Qr(e,m,3e3)}catch{}if(c.length===0&&n&&(K(`Inspector not active. Activating via SIGUSR1 in container ${r}...`),c=(await dm(r,e,m,t)).targets),c.length===0)throw new Error(`Cannot connect to Node.js in container ${r}. Inspector not active. Ensure port 9229 is exposed (e.g. -p 9229:9229) and use activateIfNeeded or start Node with --inspect.`);let p=c[0],b=p.webSocketDebuggerUrl;return e!==Pt&&(b=b.replace(/ws:\/\/[^:]+:/,`ws://${e}:`)),{session:await vn(b),processInfo:{pid:0,inspectorActive:!0,inspectorHost:e,inspectorPort:m,webSocketUrl:b,containerId:r},target:p}}let i=o.pid,a;if(!i&&o.processName){let m=cm(o.processName);if(m.length===0)throw new Error(`No Node.js process found matching: ${o.processName}`);if(m.length>1){let c=m.map(p=>` PID ${p.pid}: ${p.command}`).join(`
1095
1096
  `);throw new Error(`Multiple Node.js processes match "${o.processName}":
1096
1097
  ${c}
1097
- Please specify a PID directly.`)}i=m[0].pid,a=m[0].command,K(`Found Node.js process: PID ${i} - ${a}`)}let l=o.port||ln,u=[];try{u=await Qr(e,l,3e3)}catch{}if(u.length>0){let m=u[0];K(`Inspector already active at ${e}:${l}, connecting...`);let c=m.webSocketDebuggerUrl;return e!==Pt&&(c=c.replace(/ws:\/\/[^:]+:/,`ws://${e}:`)),{session:await vn(c),processInfo:{pid:i||0,command:a,inspectorActive:!0,inspectorHost:e,inspectorPort:l,webSocketUrl:c},target:m}}if(i&&n){K(`Inspector not active on ${e}:${l}. Activating via SIGUSR1 on PID ${i}...`);let{port:m,targets:c}=await mm(i,e,t);if(c.length===0)throw new Error(`Inspector activated on port ${m} but no targets found`);let p=c[0],b=p.webSocketDebuggerUrl;return e!==Pt&&(b=b.replace(/ws:\/\/[^:]+:/,`ws://${e}:`)),{session:await vn(b),processInfo:{pid:i,command:a,inspectorActive:!0,inspectorHost:e,inspectorPort:m,webSocketUrl:b},target:p}}throw i?new Error(`Cannot connect to process ${i}. Inspector is not active and activation failed. Try starting the process with NODE_OPTIONS=--inspect or --inspect flag.`):new Error("No target specified. Provide a PID, process name, port, or WebSocket URL. If the process is not started with --inspect, provide a PID to activate via SIGUSR1.")}s(_l,"connectToNodeProcess");var Cn=class{static{s(this,"NodeToolSessionContext")}_sessionId;_connection=null;_storeKey=null;closed=!1;constructor(e){this._sessionId=e}sessionId(){return this._sessionId}async connect(e){if(this._connection)throw new Error("Already connected to a Node.js process. Disconnect first.");K(`Connecting to Node.js process with options: ${JSON.stringify(e)}`);let t=await _l(e);return this._connection=t,this._storeKey=ri(t.processInfo.pid,t.processInfo.webSocketUrl),await si(this._storeKey,t.session,{pid:t.processInfo.pid,command:t.processInfo.command}),K(`Connected to Node.js process: PID=${t.processInfo.pid}, store=${this._storeKey}`),{processInfo:t.processInfo,target:t.target}}async disconnect(){!this._connection||!this._storeKey||(K(`Disconnecting from Node.js process: ${this._storeKey}`),await ii(this._storeKey),await this._connection.session.detach(),this._connection=null,this._storeKey=null)}get storeKey(){if(!this._storeKey)throw new Error("Not connected to any Node.js process. Call connect first.");return this._storeKey}get isConnected(){return this._connection!==null&&this._connection.session.isConnected()}get processInfo(){return this._connection?.processInfo??null}async close(){return this.closed?!1:(await this.disconnect(),this.closed=!0,!0)}};var En=class{static{s(this,"NodeToolExecutor")}sessionIdProvider;sessionContext;constructor(e){this.sessionIdProvider=e}_sessionContext(){if(!this.sessionContext){let e=this.sessionIdProvider();this.sessionContext=new Cn(e),K(`Created Node.js session context for session ${e}`)}return this.sessionContext}async executeTool(e,t){K(`Executing Node.js tool ${e.name()} with input: ${hn(t)}`);try{let n=this._sessionContext(),r=await e.handle(n,t);return K(`Executed Node.js tool ${e.name()} successfully`),r}catch(n){throw K(`Error executing Node.js tool ${e.name()}: ${n}`),n}}};var On=[...Nl,...Pl];function Fs(o){return new En(o)}s(Fs,"createToolExecutor");var Us=class{static{s(this,"NodeCliProvider")}platform="node";cliName="node-devtools-cli";tools=On;sessionDescription="Manage Node.js debugging sessions";cliExamples=["node-devtools-cli interactive","node-devtools-cli connect --pid 12345"];bashCompletionOptions="";bashCompletionCommands="daemon session tools config completion interactive connect disconnect status tracepoint logpoint exceptionpoint watch";zshCompletionOptions="";zshCompletionCommands=[{name:"daemon",description:"Manage the daemon server"},{name:"session",description:"Manage Node.js debug sessions"},{name:"tools",description:"List and inspect available tools"},{name:"config",description:"Show current configuration"},{name:"completion",description:"Generate shell completion scripts"},{name:"interactive",description:"Start interactive REPL mode"},{name:"connect",description:"Connect to a Node.js process"},{name:"disconnect",description:"Disconnect from current process"},{name:"status",description:"Show connection status"},{name:"tracepoint",description:"Tracepoint commands"},{name:"logpoint",description:"Logpoint commands"},{name:"exceptionpoint",description:"Exceptionpoint commands"},{name:"watch",description:"Watch expression commands"}];replPrompt="node> ";cliDescription="Node.js DevTools MCP CLI";packageName="browser-devtools-mcp";buildEnv(e){return{...process.env}}addOptions(e){return e}getConfig(){return{consoleMessagesBufferSize:Rn}}formatConfig(e){return[" Node.js:",` Console Messages Buffer: ${e.consoleMessagesBufferSize??Rn}`].join(`
1098
- `)}formatConfigForRepl(e){return` console-messages-buffer = ${Rn}`}},Ml=new Us;var Hs=`
1098
+ Please specify a PID directly.`)}i=m[0].pid,a=m[0].command,K(`Found Node.js process: PID ${i} - ${a}`)}let l=o.port||ln,u=[];try{u=await Qr(e,l,3e3)}catch{}if(u.length>0){let m=u[0];K(`Inspector already active at ${e}:${l}, connecting...`);let c=m.webSocketDebuggerUrl;return e!==Pt&&(c=c.replace(/ws:\/\/[^:]+:/,`ws://${e}:`)),{session:await vn(c),processInfo:{pid:i||0,command:a,inspectorActive:!0,inspectorHost:e,inspectorPort:l,webSocketUrl:c},target:m}}if(i&&n){K(`Inspector not active on ${e}:${l}. Activating via SIGUSR1 on PID ${i}...`);let{port:m,targets:c}=await mm(i,e,t);if(c.length===0)throw new Error(`Inspector activated on port ${m} but no targets found`);let p=c[0],b=p.webSocketDebuggerUrl;return e!==Pt&&(b=b.replace(/ws:\/\/[^:]+:/,`ws://${e}:`)),{session:await vn(b),processInfo:{pid:i,command:a,inspectorActive:!0,inspectorHost:e,inspectorPort:m,webSocketUrl:b},target:p}}throw i?new Error(`Cannot connect to process ${i}. Inspector is not active and activation failed. Try starting the process with NODE_OPTIONS=--inspect or --inspect flag.`):new Error("No target specified. Provide a PID, process name, port, or WebSocket URL. If the process is not started with --inspect, provide a PID to activate via SIGUSR1.")}s(_l,"connectToNodeProcess");var Cn=class{static{s(this,"NodeToolSessionContext")}_sessionId;_connection=null;_storeKey=null;closed=!1;constructor(e){this._sessionId=e}sessionId(){return this._sessionId}async connect(e){if(this._connection)throw new Error("Already connected to a Node.js process. Disconnect first.");K(`Connecting to Node.js process with options: ${JSON.stringify(e)}`);let t=await _l(e);return this._connection=t,this._storeKey=ri(t.processInfo.pid,t.processInfo.webSocketUrl),await si(this._storeKey,t.session,{pid:t.processInfo.pid,command:t.processInfo.command}),K(`Connected to Node.js process: PID=${t.processInfo.pid}, store=${this._storeKey}`),{processInfo:t.processInfo,target:t.target}}async disconnect(){!this._connection||!this._storeKey||(K(`Disconnecting from Node.js process: ${this._storeKey}`),await ii(this._storeKey),await this._connection.session.detach(),this._connection=null,this._storeKey=null)}get storeKey(){if(!this._storeKey)throw new Error("Not connected to any Node.js process. Call connect first.");return this._storeKey}get isConnected(){return this._connection!==null&&this._connection.session.isConnected()}get processInfo(){return this._connection?.processInfo??null}async close(){return this.closed?!1:(await this.disconnect(),this.closed=!0,!0)}};var En=class{static{s(this,"NodeToolExecutor")}sessionIdProvider;sessionContext;constructor(e){this.sessionIdProvider=e}_sessionContext(){if(!this.sessionContext){let e=this.sessionIdProvider();this.sessionContext=new Cn(e),K(`Created Node.js session context for session ${e}`)}return this.sessionContext}async executeTool(e,t){K(`Executing Node.js tool ${e.name()} with input: ${hn(t)}`);try{let n=this._sessionContext(),r=await e.handle(n,t);return K(`Executed Node.js tool ${e.name()} successfully`),r}catch(n){throw K(`Error executing Node.js tool ${e.name()}: ${n}`),n}}};var On=[...Nl,...Pl];function Fs(o){return new En(o)}s(Fs,"createToolExecutor");var Us=class{static{s(this,"NodeCliProvider")}platform="node";cliName="node-devtools-cli";tools=On;sessionDescription="Manage Node.js debugging sessions";cliExamples=["node-devtools-cli interactive","node-devtools-cli connect --pid 12345"];bashCompletionOptions="";bashCompletionCommands="daemon session tools config completion interactive connect disconnect status tracepoint logpoint exceptionpoint watch";zshCompletionOptions="";zshCompletionCommands=[{name:"daemon",description:"Manage the daemon server"},{name:"session",description:"Manage Node.js debug sessions"},{name:"tools",description:"List and inspect available tools"},{name:"config",description:"Show current configuration"},{name:"completion",description:"Generate shell completion scripts"},{name:"interactive",description:"Start interactive REPL mode"},{name:"connect",description:"Connect to a Node.js process"},{name:"disconnect",description:"Disconnect from current process"},{name:"status",description:"Show connection status"},{name:"tracepoint",description:"Tracepoint commands"},{name:"logpoint",description:"Logpoint commands"},{name:"exceptionpoint",description:"Exceptionpoint commands"},{name:"watch",description:"Watch expression commands"}];replPrompt="node> ";cliDescription="Node.js DevTools MCP CLI";packageName="browser-devtools-mcp";buildEnv(e){return{...process.env}}addOptions(e){return e}getConfig(){return{consoleMessagesBufferSize:kn}}formatConfig(e){return[" Node.js:",` Console Messages Buffer: ${e.consoleMessagesBufferSize??kn}`].join(`
1099
+ `)}formatConfigForRepl(e){return` console-messages-buffer = ${kn}`}},Ml=new Us;var Hs=`
1099
1100
  Node.js Backend Debugging Platform
1100
1101
 
1101
1102
  This platform provides non-blocking V8 debugging for Node.js backend processes.
@@ -1 +1 @@
1
- import{a as h}from"./core-4DMVQUQB.js";import{F as E,G as b,H as C,I as y,K as I,L as u,M as c,O as d,a as t}from"./core-IV5QBQ2N.js";import{createRequire as P}from"node:module";import{Command as N,Option as x,InvalidOptionArgumentError as _}from"commander";import{serve as q}from"@hono/node-server";import{Hono as M}from"hono";import{cors as $}from"hono/cors";import{z as F}from"zod";var k=P(import.meta.url),D=0,A=0,i=new M,a=new Map,O="#default",p={get sessionNotFound(){return f(404,"Session Not Found")},get toolNotFound(){return f(404,"Tool Not Found")},get internalServerError(){return f(500,"Internal Server Error")}};function f(n,r){return{error:{code:n,message:r}}}t(f,"_buildErrorResponse");async function S(n){if(n.closed=!0,n.context)try{await n.context.close(),u("Closed MCP session context")}catch(r){d("Error occurred while closing MCP session context",r)}a.delete(n.id)}t(S,"_closeSession");function H(n,r){let s=Date.now(),e={id:r,toolExecutor:h.toolsInfo.createToolExecutor(()=>r),closed:!1,createdAt:s,lastActiveAt:s};return u(`Created session with id ${r}`),e}t(H,"_createSession");function R(n){let r=Date.now();return{id:n.id,createdAt:n.createdAt,lastActiveAt:n.lastActiveAt,idleSeconds:Math.floor((r-n.lastActiveAt)/1e3)}}t(R,"_getSessionInfo");async function j(n){let r=n.req.header("session-id")||O;return a.get(r)}t(j,"_getSession");async function G(n){let r=n.req.header("session-id")||O,s=a.get(r);return s?u(`Reusing session with id ${r}`):(u(`No session could be found with id ${r}`),s=H(n,r),a.set(r,s)),s}t(G,"_getOrCreateSession");function L(){let n=!1;setInterval(t(()=>{let s=Date.now();n&&a.size===0&&(c("No active session found, so terminating daemon server"),process.exit(0));for(let[e,o]of a)u(`Checking whether session with id ${e} is idle or not ...`),s-o.lastActiveAt>b*1e3&&(u(`Session with id ${e} is idle, so it will be closing ...`),S(o).then(()=>{u(`Session with id ${e} was idle, so it has been closed`)}).catch(l=>{d(`Unable to delete idle session with id ${e}`,l)}));n=a.size===0},"sessionCheck"),C*1e3)}t(L,"_scheduleIdleSessionCheck");async function U(n){let r=n.req.raw.clone();u(`Got request: ${await r.json()}`)}t(U,"_logRequest");async function z(n){let r=Object.fromEntries(h.toolsInfo.tools.map(e=>[e.name(),e]));i.use("*",$({origin:"*",allowMethods:["GET","POST","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","session-id"]})),A=n,D=Date.now();let s=t(async e=>{c(`Received ${e}, initiating graceful shutdown...`);let o=[];for(let l of a.values())o.push(S(l));await Promise.allSettled(o),c("All sessions closed, exiting..."),process.exit(0)},"gracefulShutdown");process.on("SIGTERM",()=>s("SIGTERM")),process.on("SIGINT",()=>s("SIGINT")),process.on("uncaughtException",e=>{d("Uncaught exception",e)}),process.on("unhandledRejection",e=>{d("Unhandled rejection",e)}),i.get("/health",e=>e.json({status:"ok"})),i.get("/info",e=>{let o={version:k("../package.json").version,uptime:Math.floor((Date.now()-D)/1e3),sessionCount:a.size,port:A};return e.json(o)}),i.get("/sessions",e=>{let o=[];for(let l of a.values())o.push(R(l));return e.json({sessions:o})}),i.get("/session",async e=>{let o=await j(e);return o?e.json(R(o)):e.json(p.sessionNotFound,404)}),i.post("/shutdown",async e=>{c("Shutdown request received, closing all sessions...");let o=[];for(let l of a.values())o.push(S(l));return await Promise.allSettled(o),c("All sessions closed, shutting down daemon server..."),setTimeout(()=>{process.exit(0)},500),e.json({status:"shutting_down"},200)}),i.post("/call",async e=>{try{I()&&await U(e);let o=await G(e);o.lastActiveAt=Date.now();let l=await e.req.json(),v=r[l.toolName];if(!v)return e.json(p.toolNotFound,404);let T;try{T=F.object(v.inputSchema()).parse(l.toolInput)}catch(g){let m=g.errors&&Array.isArray(g.errors)?g.errors.map(w=>`${w.path?.join(".")||"input"}: ${w.message}`).join("; "):"Invalid tool input";return e.json(f(400,`Invalid Tool Request: ${m}`),400)}try{let m={toolOutput:await o.toolExecutor.executeTool(v,T)};return e.json(m,200)}catch(g){let m={toolError:{code:g.code,message:g.message}};return e.json(m,500)}}catch(o){return d("Error occurred while handling tool call request",o),e.json(p.internalServerError,500)}}),i.delete("/session",async e=>{try{let o=await j(e);return o?(await S(o),e.json({ok:!0},200)):e.json(p.sessionNotFound,404)}catch(o){return d("Error occurred while deleting session",o),e.json(p.internalServerError,500)}}),i.onError((e,o)=>(d("Unhandled error in request handler",e),o.json({error:{code:500,message:"Internal Server Error"}},500))),i.notFound(e=>e.json({error:"Not Found",status:404},404)),q({fetch:i.fetch,port:n},()=>c(`Listening on port ${n}`)),L()}t(z,"startDaemonHTTPServer");var W=import.meta.url===`file://${process.argv[1]}`||import.meta.url===`file://${process.argv[1]}.mjs`||process.argv[1]?.endsWith("daemon-server.js")||process.argv[1]?.endsWith("daemon-server.mjs");if(W){let n=function(e){let o=Number(e);if(!Number.isInteger(o)||o<1||o>65535)throw new _("port must be an integer between 1 and 65535");return o};Z=n,t(n,"parsePort");let s=new N().addOption(new x("--port <number>","port for daemon HTTP server").argParser(n).default(E)).allowUnknownOption().parse(process.argv).opts();y(),c("Starting daemon HTTP server..."),z(s.port).then(()=>{c("Daemon HTTP server started")}).catch(e=>{d("Failed to start daemon HTTP server",e),process.exit(1)})}var Z;export{z as startDaemonHTTPServer};
1
+ import{a as h}from"./core-ROCTQ3TM.js";import{F as E,G as b,H as C,I as y,K as I,L as u,M as c,O as d,a as t}from"./core-IV5QBQ2N.js";import{createRequire as P}from"node:module";import{Command as N,Option as x,InvalidOptionArgumentError as _}from"commander";import{serve as q}from"@hono/node-server";import{Hono as M}from"hono";import{cors as $}from"hono/cors";import{z as F}from"zod";var k=P(import.meta.url),D=0,A=0,i=new M,a=new Map,O="#default",p={get sessionNotFound(){return f(404,"Session Not Found")},get toolNotFound(){return f(404,"Tool Not Found")},get internalServerError(){return f(500,"Internal Server Error")}};function f(n,r){return{error:{code:n,message:r}}}t(f,"_buildErrorResponse");async function S(n){if(n.closed=!0,n.context)try{await n.context.close(),u("Closed MCP session context")}catch(r){d("Error occurred while closing MCP session context",r)}a.delete(n.id)}t(S,"_closeSession");function H(n,r){let s=Date.now(),e={id:r,toolExecutor:h.toolsInfo.createToolExecutor(()=>r),closed:!1,createdAt:s,lastActiveAt:s};return u(`Created session with id ${r}`),e}t(H,"_createSession");function R(n){let r=Date.now();return{id:n.id,createdAt:n.createdAt,lastActiveAt:n.lastActiveAt,idleSeconds:Math.floor((r-n.lastActiveAt)/1e3)}}t(R,"_getSessionInfo");async function j(n){let r=n.req.header("session-id")||O;return a.get(r)}t(j,"_getSession");async function G(n){let r=n.req.header("session-id")||O,s=a.get(r);return s?u(`Reusing session with id ${r}`):(u(`No session could be found with id ${r}`),s=H(n,r),a.set(r,s)),s}t(G,"_getOrCreateSession");function L(){let n=!1;setInterval(t(()=>{let s=Date.now();n&&a.size===0&&(c("No active session found, so terminating daemon server"),process.exit(0));for(let[e,o]of a)u(`Checking whether session with id ${e} is idle or not ...`),s-o.lastActiveAt>b*1e3&&(u(`Session with id ${e} is idle, so it will be closing ...`),S(o).then(()=>{u(`Session with id ${e} was idle, so it has been closed`)}).catch(l=>{d(`Unable to delete idle session with id ${e}`,l)}));n=a.size===0},"sessionCheck"),C*1e3)}t(L,"_scheduleIdleSessionCheck");async function U(n){let r=n.req.raw.clone();u(`Got request: ${await r.json()}`)}t(U,"_logRequest");async function z(n){let r=Object.fromEntries(h.toolsInfo.tools.map(e=>[e.name(),e]));i.use("*",$({origin:"*",allowMethods:["GET","POST","DELETE","OPTIONS"],allowHeaders:["Content-Type","Authorization","session-id"]})),A=n,D=Date.now();let s=t(async e=>{c(`Received ${e}, initiating graceful shutdown...`);let o=[];for(let l of a.values())o.push(S(l));await Promise.allSettled(o),c("All sessions closed, exiting..."),process.exit(0)},"gracefulShutdown");process.on("SIGTERM",()=>s("SIGTERM")),process.on("SIGINT",()=>s("SIGINT")),process.on("uncaughtException",e=>{d("Uncaught exception",e)}),process.on("unhandledRejection",e=>{d("Unhandled rejection",e)}),i.get("/health",e=>e.json({status:"ok"})),i.get("/info",e=>{let o={version:k("../package.json").version,uptime:Math.floor((Date.now()-D)/1e3),sessionCount:a.size,port:A};return e.json(o)}),i.get("/sessions",e=>{let o=[];for(let l of a.values())o.push(R(l));return e.json({sessions:o})}),i.get("/session",async e=>{let o=await j(e);return o?e.json(R(o)):e.json(p.sessionNotFound,404)}),i.post("/shutdown",async e=>{c("Shutdown request received, closing all sessions...");let o=[];for(let l of a.values())o.push(S(l));return await Promise.allSettled(o),c("All sessions closed, shutting down daemon server..."),setTimeout(()=>{process.exit(0)},500),e.json({status:"shutting_down"},200)}),i.post("/call",async e=>{try{I()&&await U(e);let o=await G(e);o.lastActiveAt=Date.now();let l=await e.req.json(),v=r[l.toolName];if(!v)return e.json(p.toolNotFound,404);let T;try{T=F.object(v.inputSchema()).parse(l.toolInput)}catch(g){let m=g.errors&&Array.isArray(g.errors)?g.errors.map(w=>`${w.path?.join(".")||"input"}: ${w.message}`).join("; "):"Invalid tool input";return e.json(f(400,`Invalid Tool Request: ${m}`),400)}try{let m={toolOutput:await o.toolExecutor.executeTool(v,T)};return e.json(m,200)}catch(g){let m={toolError:{code:g.code,message:g.message}};return e.json(m,500)}}catch(o){return d("Error occurred while handling tool call request",o),e.json(p.internalServerError,500)}}),i.delete("/session",async e=>{try{let o=await j(e);return o?(await S(o),e.json({ok:!0},200)):e.json(p.sessionNotFound,404)}catch(o){return d("Error occurred while deleting session",o),e.json(p.internalServerError,500)}}),i.onError((e,o)=>(d("Unhandled error in request handler",e),o.json({error:{code:500,message:"Internal Server Error"}},500))),i.notFound(e=>e.json({error:"Not Found",status:404},404)),q({fetch:i.fetch,port:n},()=>c(`Listening on port ${n}`)),L()}t(z,"startDaemonHTTPServer");var W=import.meta.url===`file://${process.argv[1]}`||import.meta.url===`file://${process.argv[1]}.mjs`||process.argv[1]?.endsWith("daemon-server.js")||process.argv[1]?.endsWith("daemon-server.mjs");if(W){let n=function(e){let o=Number(e);if(!Number.isInteger(o)||o<1||o>65535)throw new _("port must be an integer between 1 and 65535");return o};Z=n,t(n,"parsePort");let s=new N().addOption(new x("--port <number>","port for daemon HTTP server").argParser(n).default(E)).allowUnknownOption().parse(process.argv).opts();y(),c("Starting daemon HTTP server..."),z(s.port).then(()=>{c("Daemon HTTP server started")}).catch(e=>{d("Failed to start daemon HTTP server",e),process.exit(1)})}var Z;export{z as startDaemonHTTPServer};
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
1
  #!/usr/bin/env node
2
- import{a as d}from"./core-4DMVQUQB.js";import{I as P,J as b,K as y,L as n,M as u,O as c,a as t,b as T,d as v,e as h,f as C}from"./core-IV5QBQ2N.js";import{createRequire as $}from"node:module";var A=$(import.meta.url),M="browser-devtools-mcp",w=A("../package.json").version;function E(){let r=[];return r.push(d.serverInfo.instructions),r.join(`
2
+ import{a as d}from"./core-ROCTQ3TM.js";import{I as P,J as b,K as y,L as n,M as u,O as c,a as t,b as T,d as v,e as h,f as C}from"./core-IV5QBQ2N.js";import{createRequire as $}from"node:module";var A=$(import.meta.url),M="browser-devtools-mcp",w=A("../package.json").version;function E(){let r=[];return r.push(d.serverInfo.instructions),r.join(`
3
3
 
4
4
  `).trim()}t(E,"getServerInstructions");function I(){return d.serverInfo.policies}t(I,"getServerPolicies");import q from"node:crypto";import{StreamableHTTPTransport as D}from"@hono/mcp";import{serve as V}from"@hono/node-server";import{McpServer as F}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as L}from"@modelcontextprotocol/sdk/server/stdio.js";import{Hono as z}from"hono";import{cors as U}from"hono/cors";var W={jsonrpc:"2.0",error:{code:0,message:"N/A"},id:null},p={get sessionNotFound(){return S(-32001,"Session Not Found")},get unauthorized(){return S(-32001,"Unauthorized")},get internalServerError(){return S(-32603,"Internal Server Error")}},g=new Map;function S(r,e){let o={...W};return o.error.code=r,o.error.message=e,o}t(S,"_buildMCPErrorResponse");function G(r){if("image"in r&&r.image!==null&&typeof r.image=="object"&&"data"in r.image&&"mimeType"in r.image&&Buffer.isBuffer(r.image.data)&&typeof r.image.mimeType=="string"){let e=r.image;return delete r.image,e}}t(G,"_getImage");function B(r){let e=G(r),o=[];return o.push({type:"text",text:JSON.stringify(r,null,2)}),e&&(e.mimeType==="image/svg+xml"?o.push({type:"text",text:e.data.toString(),mimeType:e.mimeType}):o.push({type:"image",data:e.data.toString("base64"),mimeType:e.mimeType})),{content:o,structuredContent:r,isError:!1}}t(B,"_toResponse");function J(r){let e=new F({name:M,version:w},{capabilities:{resources:{},tools:{}},instructions:E()}),o=[],s=I();if(s)for(let a of s)o.push({role:"user",content:{type:"text",text:a}});e.registerPrompt("default_system",{title:"Default System Prompt",description:"General behavior for the AI assistant"},async()=>({description:"Defines the assistant's general reasoning and tool usage rules.",messages:o}));let i=d.toolsInfo.createToolExecutor(()=>r.sessionIdProvider?r.sessionIdProvider():""),m=t(a=>async H=>{try{let f=await i.executeTool(a,H);return B(f)}catch(f){return{content:[{type:"text",text:`Error: ${f.message}`}],isError:!0}}},"createToolCallback");return d.toolsInfo.tools.forEach(a=>{n(`Registering tool ${a.name()} ...`),e.registerTool(a.name(),{description:a.description(),inputSchema:a.inputSchema(),outputSchema:a.outputSchema()},m(a))}),e}t(J,"_createServer");async function O(r,e){let o=J({config:e.config,sessionIdProvider:t(()=>r.sessionId,"sessionIdProvider")});return await o.connect(r),o}t(O,"_createAndConnectServer");function R(){return{}}t(R,"_getConfig");function K(r,e,o){let s={transport:e,server:o,closed:!1,lastActiveAt:Date.now()},i=r.env.incoming.socket;return i._mcpRegistered||(i._mcpRegistered=!0,i.on("close",async()=>{n(`Socket, which is for MCP session with id ${e.sessionId}, has been closed`),C&&await e.close()})),Z(e,s.server),n(`Created MCP server session with id ${e.sessionId}`),s}t(K,"_createSession");async function Y(r){let e=R(),o={},s=new D({enableJsonResponse:!0,sessionIdGenerator:t(()=>q.randomUUID(),"sessionIdGenerator"),onsessioninitialized:t(async i=>{let m=K(r,s,o.server);g.set(i,m),n(`MCP session initialized with id ${i}`)},"onsessioninitialized"),onsessionclosed:t(async i=>{n(`Closing MCP session closed with id ${i} ...`),await s.close(),n(`MCP session closed with id ${i}`)},"onsessionclosed")});return o.server=await O(s,{config:e}),s}t(Y,"_createTransport");async function Q(r){let e=r.req.header("mcp-session-id");if(e){let o=g.get(e);if(o)return n(`Reusing MCP session with id ${e}`),o.transport}}t(Q,"_getTransport");async function X(r){let e=r.req.header("mcp-session-id");if(e){let o=g.get(e);if(o)return n(`Reusing MCP session with id ${e}`),o.transport;n(`No MCP session could be found with id ${e}`);return}return await Y(r)}t(X,"_getOrCreateTransport");function Z(r,e){let o=!1;r.onclose=async()=>{if(n(`Closing MCP session with id ${r.sessionId} ...`),o){n(`MCP session with id ${r.sessionId} has already been closed`);return}o=!0;try{await e.close(),n("Closed MCP server")}catch(s){c("Error occurred while closing MCP server",s)}if(r.sessionId){let s=g.get(r.sessionId);if(s&&(s.closed=!0,s.context))try{await s.context.close(),n("Closed MCP session context")}catch(i){c("Error occurred while closing MCP session context",i)}g.delete(r.sessionId)}n(`Closing MCP session with id ${r.sessionId} ...`)}}t(Z,"_registerMCPSessionClose");function ee(){setInterval(t(()=>{let e=Date.now();for(let[o,s]of g)n(`Checking whether session with id ${o} is idle or not ...`),e-s.lastActiveAt>v*1e3&&(n(`Session with id ${o} is idle, so it will be closing ...`),s.transport.close().then(()=>{n(`Session with id ${o} was idle, so it has been closed`)}).catch(i=>{c(`Unable to delete idle session with id ${o}`,i)}))},"sessionCheck"),h*1e3)}t(ee,"_scheduleIdleSessionCheck");async function re(r){let e=r.req.raw.clone();n(`Got request: ${await e.json()}`)}t(re,"_logRequest");function oe(r){let e=r.req.header("mcp-session-id");if(e){let o=g.get(e);o&&(o.lastActiveAt=Date.now())}}t(oe,"_markSessionAsActive");async function _(){let r=new L;await O(r,{config:R()})}t(_,"startStdioServer");var l=new z;async function x(r){l.use("*",U({origin:"*",allowMethods:["GET","POST","OPTIONS"],allowHeaders:["Content-Type","Authorization","MCP-Protocol-Version"]})),l.get("/health",e=>e.json({status:"ok"})),l.get("/ping",e=>e.json({status:"ok",message:"pong"})),l.get("/mcp",e=>e.json({status:"ok",protocol:"model-context-protocol",version:"1.0"})),l.post("/mcp",async e=>{try{y()&&await re(e);let o=await X(e);return o?(oe(e),await o.handleRequest(e)):e.json(p.sessionNotFound,400)}catch(o){return c("Error occurred while handling MCP request",o),e.json(p.internalServerError,500)}}),l.delete("/mcp",async e=>{try{let o=await Q(e);return o?(await o.close(),e.json({ok:!0},200)):e.json(p.sessionNotFound,400)}catch(o){return c("Error occurred while deleting MCP session",o),e.json(p.internalServerError,500)}}),l.notFound(e=>e.json({error:"Not Found",status:404},404)),V({fetch:l.fetch,port:r},()=>u(`Listening on port ${r}`)),ee()}t(x,"startStreamableHTTPServer");import{Command as te,Option as N,InvalidOptionArgumentError as se}from"commander";function ne(r){let e=Number(r);if(!Number.isInteger(e)||e<1||e>65535)throw new se("port must be an integer between 1 and 65535");return e}t(ne,"_parsePort");function ie(){return new te().addOption(new N("--transport <type>","transport type").choices(["stdio","streamable-http"]).default("stdio")).addOption(new N("--port <number>","port for Streamable HTTP transport").argParser(ne).default(T)).allowUnknownOption().parse(process.argv).opts()}t(ie,"_getOptions");async function ae(){let r=ie();r.transport==="stdio"?(b(),await _()):r.transport==="streamable-http"?(u("Starting MCP server..."),await x(r.port),u("Started MCP Server")):(c(`Invalid transport: ${r.transport}`),process.exit(1))}t(ae,"main");ae().catch(r=>{P(),c("MCP server error",r),process.exit(1)});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browser-devtools-mcp",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
4
4
  "description": "MCP Server for Browser Dev Tools",
5
5
  "private": false,
6
6
  "type": "module",