@agimon-ai/browse-tool 0.2.11 → 0.2.13

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,15 +1,15 @@
1
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require(`./playwright-test-BicczY9j.cjs`);require(`reflect-metadata/lite`);let l=require(`@modelcontextprotocol/sdk/server/stdio.js`),u=require(`@modelcontextprotocol/sdk/types.js`),d=require(`inversify`),f=require(`node:async_hooks`),p=require(`node:fs`);p=s(p);let m=require(`node:path`);m=s(m);let h=require(`@opentelemetry/api`),g=require(`@opentelemetry/api-logs`),_=require(`@opentelemetry/exporter-logs-otlp-http`),v=require(`@opentelemetry/exporter-trace-otlp-http`),y=require(`@opentelemetry/resources`),b=require(`@opentelemetry/sdk-logs`),x=require(`@opentelemetry/sdk-trace-node`),S=require(`@agimon-ai/foundation-port-registry`),C=require(`node:os`);C=s(C);let w=require(`zod`),T=require(`node:fs/promises`);T=s(T);let E=require(`node:child_process`),D=require(`node:url`),O=require(`playwright`);O=s(O);let ee=require(`node:stream`),te=require(`node:stream/promises`),ne=require(`node:module`),re=require(`esbuild`),k=require(`node:crypto`),ie=require(`node:http`),ae=require(`@modelcontextprotocol/sdk/server/streamableHttp.js`);const oe=`ProfileService`,se=`PageRegistry`,ce=`BrowserService`,le=`ElementLocatorService`,ue=`PageMonitorService`,de=`PauseController`,fe=`AutomationRunner`,pe=`SpecRunner`,me=`SpecBundlerService`,he=`SpecDiscoveryService`,ge=`SpecMetadataService`,_e=`SetupRunner`,ve=`WebServerManager`,ye=`Logger`,be=`TelemetryService`,xe=`CodeSnippetService`,Se=`HttpServerHealthCheck`,Ce=`HttpServerManager`,we=`HttpBrowserClient`,Te=`RemoteToolExecutor`,Ee=`ExtensionTaskQueue`,De=`ExtensionToolDelegator`,Oe=`ToolExecutor`,ke=`ExtensionSessionRegistry`,Ae=`ExtensionPageProxy`,je=`ExtensionSpecRunner`,Me=`StealthLauncher`,Ne=`BrowserLockManager`,Pe=`McpSessionTracker`,Fe=`ChromeForTestingService`,Ie=`WebSocketHub`,Le=`IdleCleanupService`,Re=`PortRegistryService`,ze=`Tool`,A={ProfileService:Symbol.for(`ProfileService`),PageRegistry:Symbol.for(`PageRegistry`),BrowserService:Symbol.for(`BrowserService`),ElementLocatorService:Symbol.for(`ElementLocatorService`),PageMonitorService:Symbol.for(`PageMonitorService`),PauseController:Symbol.for(`PauseController`),AutomationRunner:Symbol.for(`AutomationRunner`),SpecRunner:Symbol.for(`SpecRunner`),SpecBundlerService:Symbol.for(`SpecBundlerService`),SpecDiscoveryService:Symbol.for(`SpecDiscoveryService`),SpecMetadataService:Symbol.for(`SpecMetadataService`),SetupRunner:Symbol.for(`SetupRunner`),WebServerManager:Symbol.for(`WebServerManager`),Logger:Symbol.for(`Logger`),TelemetryService:Symbol.for(`TelemetryService`),CodeSnippetService:Symbol.for(`CodeSnippetService`),HttpServerHealthCheck:Symbol.for(`HttpServerHealthCheck`),HttpServerManager:Symbol.for(`HttpServerManager`),HttpBrowserClient:Symbol.for(`HttpBrowserClient`),RemoteToolExecutor:Symbol.for(`RemoteToolExecutor`),ExtensionTaskQueue:Symbol.for(`ExtensionTaskQueue`),ExtensionToolDelegator:Symbol.for(`ExtensionToolDelegator`),ToolExecutor:Symbol.for(`ToolExecutor`),StealthLauncher:Symbol.for(`StealthLauncher`),BrowserLockManager:Symbol.for(`BrowserLockManager`),ExtensionSessionRegistry:Symbol.for(`ExtensionSessionRegistry`),ExtensionPageProxy:Symbol.for(`ExtensionPageProxy`),ExtensionSpecRunner:Symbol.for(`ExtensionSpecRunner`),McpSessionTracker:Symbol.for(`McpSessionTracker`),ChromeForTestingService:Symbol.for(`ChromeForTestingService`),WebSocketHub:Symbol.for(`WebSocketHub`),IdleCleanupService:Symbol.for(`IdleCleanupService`),PortRegistryService:Symbol.for(`PortRegistryService`),Tool:Symbol.for(`Tool`)};function j(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function M(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}const Be=`browse-tool-http`,Ve=`log-sink-mcp-http`,He=[`pnpm-workspace.yaml`,`nx.json`,`.git`],Ue=new Set([`127.0.0.1`,`localhost`,`::1`,`0.0.0.0`]);function We(e){return e===`1`||e===`true`}function Ge(e){return Array.isArray(e)?JSON.stringify(e):typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)}function Ke(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))r!=null&&(t[n]=Ge(r));return Object.keys(t).length>0?t:void 0}function qe(e){if(!e)return;let t={};for(let n of e.split(`,`)){let[e,...r]=n.split(`=`),i=e?.trim(),a=r.join(`=`).trim();!i||!a||(t[i]=a)}return Object.keys(t).length>0?t:void 0}function Je(e){if(!e)return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function Ye(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return n.endsWith(`/v1/${t}/`)||n.endsWith(`/v1/${t}`)?e:new URL(`v1/${t}`,n).toString()}function Xe(e){return Ue.has(e)}function Ze(e=process.cwd()){let t=m.default.resolve(e);for(;;){for(let e of He)if((0,p.existsSync)(m.default.join(t,e)))return t;let e=m.default.dirname(t);if(e===t)return process.cwd();t=e}}function Qe(e,t=process.cwd()){try{let n=(0,p.readFileSync)(S.PortRegistryService.resolveRegistryPath(e.PORT_REGISTRY_PATH??S.DEFAULT_REGISTRY_PATH),`utf8`),r=S.PortRegistryStateSchema.parse(JSON.parse(n)),i=(0,S.normalizeRepositoryPath)(Ze(t)),a=e.NODE_ENV||`development`,o=e.BROWSE_TOOL_OTEL_LOG_SINK_SERVICE_NAME??`log-sink-mcp-http`,s=r.entries.find(e=>e.repositoryPath===i&&e.serviceName===o&&e.serviceType===`tool`&&(e.environment??`development`)===a);if(!s)return;let c=typeof s.metadata?.healthCheckUrl==`string`&&s.metadata.healthCheckUrl.length>0?s.metadata.healthCheckUrl:void 0;return c?new URL(c).origin:`http://${s.host===`0.0.0.0`?`127.0.0.1`:s.host}:${s.port}`}catch{return}}function $e(e,t){try{let n=new URL(e),r=new URL(t);return!Xe(n.hostname)||Xe(r.hostname)||(n.hostname=r.hostname),n.toString()}catch{return e}}function et(e,t){let n=t===`traces`?e.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:e.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;if(n)return n;let r=e.OTEL_EXPORTER_OTLP_ENDPOINT;if(r)return Ye(r,t);let i=Qe(e);return i?Ye(i,t):void 0}function tt(e,t,n){let r=t===`traces`?e.BROWSE_TOOL_OTEL_BROWSER_TRACES_ENDPOINT:e.BROWSE_TOOL_OTEL_BROWSER_LOGS_ENDPOINT;if(r)return $e(r,n);let i=e.BROWSE_TOOL_OTEL_BROWSER_ENDPOINT;if(i)return $e(Ye(i,t),n);let a=et(e,t);return a?$e(a,n):void 0}function nt(e,t){let n=e.BROWSE_TOOL_OTEL_BROWSER_SERVICE_NAME??`${e.OTEL_SERVICE_NAME??Be}-extension`,r=tt(e,`traces`,t),i=tt(e,`logs`,t);return{enabled:!!(r||i),tracesEndpoint:r,logsEndpoint:i,serviceName:n}}function rt(e,t){let n=t===`traces`?e.OTEL_EXPORTER_OTLP_TRACES_HEADERS:e.OTEL_EXPORTER_OTLP_LOGS_HEADERS,r=t===`traces`?e.OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:e.OTEL_EXPORTER_OTLP_LOGS_TIMEOUT;return{url:et(e,t),headers:qe(n??e.OTEL_EXPORTER_OTLP_HEADERS),timeoutMillis:Je(r??e.OTEL_EXPORTER_OTLP_TIMEOUT)}}function it(e){switch(e){case`trace`:return g.SeverityNumber.TRACE;case`debug`:return g.SeverityNumber.DEBUG;case`info`:return g.SeverityNumber.INFO;case`warn`:return g.SeverityNumber.WARN;case`error`:return g.SeverityNumber.ERROR;case`fatal`:return g.SeverityNumber.FATAL}}function at(e){return e instanceof Error?e.message:String(e)}function ot(e){if(e instanceof Error)return Ke({"exception.type":e.name,"exception.message":e.message,"exception.stacktrace":e.stack})}let N=class{contextStore=new f.AsyncLocalStorage;tracesEnabled;logsEnabled;tracerProvider;loggerProvider;tracer;logger;constructor(e={}){let t=e.env??process.env,n=We(t.OTEL_SDK_DISABLED),r=We(t.BROWSE_TOOL_OTEL_ENABLED),i=rt(t,`traces`),a=rt(t,`logs`);this.tracesEnabled=!n&&(r||!!i.url),this.logsEnabled=!n&&(r||!!a.url);let o=e.serviceName??t.BROWSE_TOOL_OTEL_SERVICE_NAME??t.OTEL_SERVICE_NAME??Be,s=e.serviceVersion??t.npm_package_version,c={"service.name":o};s&&(c[`service.version`]=s);let l=(0,y.resourceFromAttributes)(c);if(this.tracesEnabled){let t=e.traceExporter??new v.OTLPTraceExporter(i);this.tracerProvider=new x.NodeTracerProvider({resource:l,spanProcessors:[e.traceExporter?new x.SimpleSpanProcessor(t):new x.BatchSpanProcessor(t)]})}if(this.logsEnabled){let t=e.logExporter??new _.OTLPLogExporter(a);this.loggerProvider=new b.LoggerProvider({resource:l,processors:[e.logExporter?new b.SimpleLogRecordProcessor(t):new b.BatchLogRecordProcessor(t)]})}this.tracer=this.tracerProvider?.getTracer(o,s)??h.trace.getTracer(o,s),this.logger=this.loggerProvider?.getLogger(o,s)}isEnabled(){return this.tracesEnabled||this.logsEnabled}getActiveTraceContext(){let e=this.contextStore.getStore();if(!e)return{};let t=h.trace.getSpan(e);if(!t)return{};let n=t.spanContext();return{traceId:n.traceId,spanId:n.spanId}}async runInSpan(e,t,n){if(!this.tracesEnabled)return await n(void 0);let r=this.contextStore.getStore()??h.context.active(),i=this.tracer.startSpan(e,{kind:t.kind??h.SpanKind.INTERNAL,attributes:Ke(t.attributes)},r),a=h.trace.setSpan(r,i);return await this.contextStore.run(a,async()=>{try{return await n(i)}catch(e){throw i.recordException(e instanceof Error?e:Error(at(e))),i.setStatus({code:h.SpanStatusCode.ERROR,message:at(e)}),e}finally{i.end()}})}log(e,t,n={}){if(this.logsEnabled)try{let r=n.context??this.contextStore.getStore()??h.context.active(),i=ot(n.exception);this.logger?.emit({severityNumber:it(e),severityText:e.toUpperCase(),body:t,attributes:Ke({...n.attributes,...i}),context:r,exception:n.exception})}catch{}}async forceFlush(){await Promise.allSettled([this.tracerProvider?.forceFlush(),this.loggerProvider?.forceFlush()])}async shutdown(){await Promise.allSettled([this.tracerProvider?.shutdown(),this.loggerProvider?.shutdown()])}};N=M([(0,d.injectable)(),j(`design:paramtypes`,[Object])],N);const P=18e4;function F(e,t){return function(n,r){t(n,r,e)}}let I=class{pendingTasks=new Map;taskQueue=[];lastPollAt;lastResultAt;maxQueueSize=100;defaultTimeoutMs=P;constructor(e,t=new N){this.webSocketHub=e,this.telemetry=t}async queueTask(e,t,n=this.defaultTimeoutMs,r){if(this.pendingTasks.size>=this.maxQueueSize)throw Error(`Task queue full (max ${this.maxQueueSize} tasks)`);let i=r??t.browserId,a={id:crypto.randomUUID(),tool:e,arguments:t,createdAt:new Date,timeoutMs:n,browserId:i,pageId:typeof t.pageId==`string`?t.pageId:void 0,telemetry:this.getTaskTelemetryContext()};return new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingTasks.delete(a.id);let e=this.taskQueue.findIndex(e=>e.id===a.id);e!==-1&&this.taskQueue.splice(e,1),t(Error(`Task ${a.id} timed out after ${n}ms`))},n);if(this.pendingTasks.set(a.id,{task:a,resolve:e,reject:t,timeoutId:r}),this.webSocketHub){let e=i?this.pushTaskViaWebSocket(a,i):!1;if(e||=this.pushTaskToAnyConnection(a),e)return}this.taskQueue.push(a)})}pushTaskToAnyConnection(e){if(!this.webSocketHub)return!1;let t=this.webSocketHub.getStats();if(t.totalConnections===0)return!1;let n=t.connections[0];return n?this.pushTaskViaWebSocket(e,n.browserId):!1}pushTaskViaWebSocket(e,t){if(!this.webSocketHub)return!1;let n={type:`task:push`,id:crypto.randomUUID(),payload:{taskId:e.id,tool:e.tool,arguments:e.arguments,telemetry:e.telemetry}};return this.webSocketHub.pushTask(t,n)}getNextTask(){return this.lastPollAt=new Date,this.taskQueue.shift()}submitResult(e){this.lastResultAt=new Date;let t=this.pendingTasks.get(e.taskId);if(t)return clearTimeout(t.timeoutId),this.pendingTasks.delete(e.taskId),t.resolve(e),t.task}getConnectionStatus(){let e=new Date,t=this.lastPollAt?e.getTime()-this.lastPollAt.getTime()<5e3:!1,n=this.webSocketHub?this.webSocketHub.getStats().totalConnections>0:!1;return{connected:t||n,lastPollAt:this.lastPollAt,lastResultAt:this.lastResultAt,pendingTasks:this.pendingTasks.size}}clearAllTasks(e){for(let[t,n]of this.pendingTasks)clearTimeout(n.timeoutId),n.reject(Error(e)),this.pendingTasks.delete(t);this.taskQueue.length=0}get queueSize(){return this.taskQueue.length}get pendingCount(){return this.pendingTasks.size}getTaskTelemetryContext(){let e=this.telemetry.getActiveTraceContext();if(!(!e.traceId&&!e.spanId))return{traceId:e.traceId,parentSpanId:e.spanId}}};I=M([(0,d.injectable)(),F(0,(0,d.inject)(A.WebSocketHub)),F(0,(0,d.optional)()),F(1,(0,d.inject)(A.TelemetryService)),F(1,(0,d.optional)()),j(`design:paramtypes`,[Object,Object])],I);const st=new Set(`browser_navigate.browser_go_back.browser_go_forward.browser_reload.browser_click.browser_fill.browser_type.browser_upload_file.browser_select.browser_hover.browser_drag.browser_press_key.browser_pdf.browser_screenshot.browser_snapshot.browser_list_pages.browser_new_page.browser_select_page.browser_close_page.browser_wait_for.browser_evaluate_script.browser_resize_page.browser_handle_dialog.browser_emulate.browser_list_network_requests.browser_get_network_request.browser_list_console_messages.browser_expect`.split(`.`)),ct=new Set([`browser_launch`,`browser_list_profiles`,`browser_create_profile`,`browser_delete_profile`,`browser_save_profile_state`,`browser_start_trace`,`browser_stop_trace`,`run_spec`,`discover_specs`]);let L=class{constructor(e){this.taskQueue=e}isToolSupported(e){return st.has(e)}isToolNotApplicable(e){return ct.has(e)}async executeTool(e,t){if(this.isToolNotApplicable(e))return{content:[{type:`text`,text:`Tool "${e}" is not available in Chrome extension mode. This tool requires Playwright and cannot be run through the extension.`}],isError:!0};if(!this.isToolSupported(e))return{content:[{type:`text`,text:`Tool "${e}" is not yet implemented in Chrome extension mode.`}],isError:!0};if(!this.taskQueue.getConnectionStatus().connected)return{content:[{type:`text`,text:`Chrome extension is not connected. Please ensure the extension is running and connected to the server.`}],isError:!0};try{let n=await this.taskQueue.queueTask(e,t);return n.success?n.result?n.result:{content:[{type:`text`,text:`Tool executed successfully`}]}:{content:[{type:`text`,text:n.error||n.result?.content?.[0]?.text||`Unknown error from Chrome extension`}],isError:!0}}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}}getSupportedTools(){return Array.from(st)}getNotApplicableTools(){return Array.from(ct)}};L=M([(0,d.injectable)(),F(0,(0,d.inject)(A.ExtensionTaskQueue)),j(`design:paramtypes`,[Object])],L);const lt={width:1920,height:1080};let ut=class{sessions=new Map;sessionIdCounter=0;constructor(e,t,n,r,i,a){this.browserService=e,this.specRunner=t,this.specMetadataService=n,this.setupRunner=r,this.webServerManager=i,this.pageRegistry=a}async runSpec(e){let{specPath:t,automationId:n,keepBrowserOpen:r=!1,browserOptions:i={},recordVideo:a,browserId:o,pageId:s,windowBounds:c,hooksPath:l}=e,u=n??`spec-${++this.sessionIdCounter}`,d={id:u,scriptPath:t,status:`pending`,pageIds:[],browserId:null,error:null,createdAt:new Date,updatedAt:new Date};this.sessions.set(u,d);try{let e,n,f,p=!1;if(o&&s){let t=this.pageRegistry.get(s);if(!t)throw Error(`Page with ID ${s} not found`);if(!t.page||!t.context||!t.browser)throw Error(`Page entry is missing required Playwright instances`);e=t.page,n=t.context,f=t.browser,d.browserId=o,d.pageIds.push(s),p=!0}else{let t=await this.browserService.launch({...i,recordVideo:a,onPageClose:e=>{let t=d.pageIds.indexOf(e);t>=0&&d.pageIds.splice(t,1)}});d.browserId=t.browserInstance.id,d.pageIds.push(t.pageId),t.browserInstance.specOrigin=!0;let{context:r,browser:o}=t.browserInstance;if(!r||!o)throw Error(`Browser context or browser is not available`);e=t.page,n=r,f=o}d.status=`running`,d.updatedAt=new Date,c&&await this.applyWindowBounds(f,c);let m=await this.specRunner.executeSpec({specPath:t,sessionId:u,page:e,context:n,browser:f,hooksPath:l});return d.status=`completed`,d.updatedAt=new Date,!r&&!p&&d.browserId&&d.browserId&&await this.browserService.closeBrowser(d.browserId),{automationId:u,status:`completed`,pageIds:r||p?[...d.pageIds]:[],browserId:r||p?d.browserId:null,specResult:m}}catch(e){d.status=`failed`;let t=e instanceof Error?e.message:String(e);d.error=t,d.updatedAt=new Date,console.error(`[AutomationRunner] runSpec failed: ${t}`);try{require(`fs`).writeFileSync(`/tmp/browse-tool-error.log`,`${new Date().toISOString()} ${t}\n${e instanceof Error?e.stack:``}\n`,{flag:`a`})}catch{}let n=!!(o&&s);return!r&&!n&&d.browserId&&await this.browserService.closeBrowser(d.browserId),{automationId:u,status:`failed`,pageIds:r||n?[...d.pageIds]:[],browserId:r||n?d.browserId:null}}}async runSpecEnhanced(e){let{specPath:t,automationId:n,keepBrowserOpen:r=!1,browserOptions:i={},recordVideo:a,testFilter:o,specArgs:s,configPath:c,runSetup:l=!1,startServer:u=!1,stopServerAfter:d=!0,browserId:f,pageId:p,windowBounds:h,hooksPath:g}=e,_=n??`spec-${++this.sessionIdCounter}`,v={id:_,scriptPath:t,status:`pending`,pageIds:[],browserId:null,error:null,createdAt:new Date,updatedAt:new Date};this.sessions.set(_,v);let y,b;try{let e=c?await this.specMetadataService.loadPlaywrightConfig(c):null,n=c?(0,m.dirname)(c):process.cwd();u&&e?.webServer&&(y=await this.webServerManager.startServer(e.webServer,n));let x,S,C,w=!1;if(f&&p){let e=this.pageRegistry.get(p);if(!e)throw Error(`Page with ID ${p} not found`);if(!e.page||!e.context||!e.browser)throw Error(`Page entry is missing required Playwright instances`);x=e.page,S=e.context,C=e.browser,v.browserId=f,v.pageIds.push(p),w=!0}else{let e=await this.browserService.launch({...i,recordVideo:a,onPageClose:e=>{let t=v.pageIds.indexOf(e);t>=0&&v.pageIds.splice(t,1)}});v.browserId=e.browserInstance.id,v.pageIds.push(e.pageId),e.browserInstance.specOrigin=!0;let{context:t,browser:n}=e.browserInstance;if(!t)throw Error(`Browser context is not available`);if(!n)throw Error(`Browser instance is not available`);x=e.page,S=t,C=n}if(v.status=`running`,v.updatedAt=new Date,h&&await this.applyWindowBounds(C,h),l&&e?.setupFile){let t=e.setupFile.startsWith(`/`)?e.setupFile:`${n}/${e.setupFile}`,r=e.setupExport??`default`;if(b=await this.setupRunner.runSetup(t,r,{browser:C,context:S,page:x}),!b.success)throw Error(b.error??`Setup failed`)}let T=await this.specRunner.executeSpecEnhanced({specPath:t,sessionId:_,page:x,context:S,browser:C,testFilter:o,specArgs:{...s,...b?.state},hooksPath:g});return v.status=`completed`,v.updatedAt=new Date,d&&y?.started&&await this.webServerManager.stopServer(),!r&&!w&&v.browserId&&await this.browserService.closeBrowser(v.browserId),{automationId:_,status:`completed`,pageIds:r||w?[...v.pageIds]:[],browserId:r||w?v.browserId:null,specResult:T,serverResult:y,setupResult:b}}catch(e){v.status=`failed`,v.error=e instanceof Error?e.message:String(e),v.updatedAt=new Date,d&&y?.started&&await this.webServerManager.stopServer();let t=!!(f&&p);return!r&&!t&&v.browserId&&await this.browserService.closeBrowser(v.browserId),{automationId:_,status:`failed`,pageIds:r||t?[...v.pageIds]:[],browserId:r||t?v.browserId:null,serverResult:y,setupResult:b}}}getSession(e){return this.sessions.get(e)}listSessions(){return Array.from(this.sessions.values())}async stop(e){let t=this.sessions.get(e);return t?(t.browserId&&await this.browserService.closeBrowser(t.browserId),t.status=`completed`,t.updatedAt=new Date,!0):!1}async applyWindowBounds(e,t){let n=this.resolveWindowBounds(t),r=e.contexts();if(r.length===0)return;let i=r[0].pages();if(i.length===0)return;let a;try{a=await i[0].context().newCDPSession(i[0]);let{windowId:e}=await a.send(`Browser.getWindowForTarget`);await a.send(`Browser.setWindowBounds`,{windowId:e,bounds:{left:n.x,top:n.y,width:n.width,height:n.height}})}finally{a&&await a.detach()}}resolveWindowBounds(e){let t=e.screenDimensions??lt;if(e.preset){let n=this.calculatePresetBounds(e.preset,t);return{x:e.x??n.x,y:e.y??n.y,width:e.width??n.width,height:e.height??n.height}}return{x:e.x??0,y:e.y??0,width:e.width??t.width,height:e.height??t.height}}calculatePresetBounds(e,t){let n=Math.floor(t.width/2),r=Math.floor(t.height/2);switch(e){case`right-half`:return{x:n,y:0,width:n,height:t.height};case`left-half`:return{x:0,y:0,width:n,height:t.height};case`top-half`:return{x:0,y:0,width:t.width,height:r};case`bottom-half`:return{x:0,y:r,width:t.width,height:r};case`center`:{let e=Math.floor(t.width*.75),n=Math.floor(t.height*.75);return{x:Math.floor((t.width-e)/2),y:Math.floor((t.height-n)/2),width:e,height:n}}case`fullscreen`:return{x:0,y:0,width:t.width,height:t.height};default:return{x:0,y:0,width:t.width,height:t.height}}}};ut=M([(0,d.injectable)(),F(0,(0,d.inject)(A.BrowserService)),F(1,(0,d.inject)(A.SpecRunner)),F(2,(0,d.inject)(A.SpecMetadataService)),F(3,(0,d.inject)(A.SetupRunner)),F(4,(0,d.inject)(A.WebServerManager)),F(5,(0,d.inject)(A.PageRegistry)),j(`design:paramtypes`,[Object,Object,Object,Object,Object,Object])],ut);var dt=class extends Error{constructor(e,t,n){super(e),this.pid=t,this.userDataDir=n,this.name=`BrowserSessionConflictError`}};let ft=class{platform=C.default.platform();async checkLock(e){let t={isLocked:!1};return this.platform===`win32`?this.checkWindowsLock(e,t):this.checkUnixLock(e,t)}async cleanupOrphanedLocks(e){let t=await this.checkLock(e);if(!t.isLocked)return!0;if(t.isProcessAlive)return!1;let n=[m.default.join(e,`SingletonLock`),m.default.join(e,`SingletonCookie`),m.default.join(e,`SingletonSocket`),m.default.join(e,`lockfile`)];for(let e of n)try{p.default.existsSync(e)&&await(0,T.unlink)(e)}catch{}let r=m.default.join(e,`Default`,`LOCK`);try{p.default.existsSync(r)&&await(0,T.unlink)(r)}catch{}return!0}async ensureAvailable(e){if(!p.default.existsSync(e))return;let t=await this.checkLock(e);if(t.isLocked){if(t.isProcessAlive)throw new dt(`Browser session conflict: Another Chrome process (PID: ${t.pid}) is using this profile.\nUser data directory: ${e}\n\nTo resolve:\n1. Close the existing browser session manually\n2. Or use a different profile name\n3. Or kill the process: kill ${t.pid}`,t.pid,e);if(!await this.cleanupOrphanedLocks(e))throw Error(`Failed to clean up orphaned browser lock in ${e}`)}}async checkUnixLock(e,t){let n=m.default.join(e,`SingletonLock`),r=m.default.join(e,`SingletonSocket`);if(t.lockFilePath=n,t.socketPath=r,this.symlinkExists(n))try{let e=p.default.readlinkSync(n).match(/-(\d+)$/);e&&(t.isLocked=!0,t.pid=Number.parseInt(e[1],10),t.isProcessAlive=this.isProcessRunning(t.pid))}catch{t.isLocked=!0,t.isProcessAlive=p.default.existsSync(r)}return!t.isLocked&&p.default.existsSync(r)&&(t.isLocked=!0,t.isProcessAlive=!0),t}symlinkExists(e){try{return p.default.lstatSync(e).isSymbolicLink()}catch{return!1}}async checkWindowsLock(e,t){let n=m.default.join(e,`lockfile`);if(t.lockFilePath=n,p.default.existsSync(n))try{let e=await(0,T.readFile)(n,`utf-8`),r=Number.parseInt(e.trim(),10);Number.isNaN(r)||(t.isLocked=!0,t.pid=r,t.isProcessAlive=this.isProcessRunning(r))}catch{t.isLocked=!0,t.isProcessAlive=!0}return t}isProcessRunning(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}};ft=M([(0,d.injectable)()],ft);var pt=`147.0.7727.3`,mt=`browse-tool/chrome-for-testing:147.0.7727.3`,ht=`/usr/local/bin/google-chrome-for-testing`,gt=`linux/amd64`,_t;const vt=pt,yt=`BROWSE_TOOL_CHROME_FOR_TESTING_VERSION`,bt=`147.0.7727.3`;function xt(e,t){let n=e.split(`.`).map(e=>Number.parseInt(e,10)||0),r=t.split(`.`).map(e=>Number.parseInt(e,10)||0),i=Math.max(n.length,r.length);for(let e=0;e<i;e+=1){let t=n[e]??0,i=r[e]??0;if(t!==i)return t>i?1:-1}return 0}function St(){let e=process.env.BROWSE_TOOL_CHROME_FOR_TESTING_VERSION?.trim();return e&&e.length>0?e:vt}function Ct(e){return xt(e,`147.0.7727.3`)>=0}function wt(){return Ct(St())}let Tt=class{static{_t=this}static API_URL=`https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json`;cacheDir;constructor(){this.cacheDir=(0,m.join)((0,C.homedir)(),`.cache`,`chrome-for-testing`)}async getExecutablePath(){let e=this.getExpectedExecutablePath(),t=await this.getInstalledVersion();try{let n=this.getRequestedVersion(),r=await this.fetchVersionInfo(n);return(0,p.existsSync)(e)&&t===n?e:this.download(r)}catch(t){if((0,p.existsSync)(e))return e;throw t}}async isInstalled(){return(0,p.existsSync)(this.getExpectedExecutablePath())}async getInstalledVersion(){let e=(0,m.join)(this.cacheDir,`version.txt`);if(!(0,p.existsSync)(e))return null;try{return(await(0,T.readFile)(e,`utf-8`)).trim()}catch{return null}}async update(){let e=(0,m.join)(this.cacheDir,`chrome`);return(0,p.existsSync)(e)&&await(0,T.rm)(e,{recursive:!0,force:!0}),this.download(await this.fetchVersionInfo(this.getRequestedVersion()))}async download(e){(0,p.mkdirSync)(this.cacheDir,{recursive:!0});let t=this.getDownloadUrl(e);if(!t)throw Error(`No Chrome for Testing download available for ${this.getPlatformKey()}`);let n=(0,m.join)(this.cacheDir,`chrome.zip`),r=(0,m.join)(this.cacheDir,`chrome`);await this.downloadFile(t,n),await this.extractZip(n,r),await(0,T.rm)(n,{force:!0}),await(0,T.writeFile)((0,m.join)(this.cacheDir,`version.txt`),e.version,`utf-8`);let i=this.getExpectedExecutablePath();if(!(0,p.existsSync)(i))throw Error(`Chrome for Testing executable not found at expected path: ${i}`);return(0,C.platform)()!==`win32`&&await(0,T.chmod)(i,493),i}async fetchVersionInfo(e){let t=await fetch(_t.API_URL);if(!t.ok)throw Error(`Failed to fetch Chrome for Testing info: ${t.statusText}`);let n=(await t.json()).versions.find(t=>t.version===e);if(!n)throw Error(`Chrome for Testing version ${e} not found in feed`);return n}getRequestedVersion(){return St()}getDownloadUrl(e){let t=this.getPlatformKey();return e.downloads.chrome.find(e=>e.platform===t)?.url}getPlatformKey(){let e=(0,C.platform)(),t=(0,C.arch)();if(e===`darwin`)return t===`arm64`?`mac-arm64`:`mac-x64`;if(e===`linux`)return`linux64`;if(e===`win32`)return t===`x64`?`win64`:`win32`;throw Error(`Unsupported platform: ${e}`)}getExpectedExecutablePath(){let e=(0,C.platform)(),t=(0,m.join)(this.cacheDir,`chrome`);if(e===`darwin`)return(0,m.join)(t,`chrome-mac-${(0,C.arch)()===`arm64`?`arm64`:`x64`}`,`Google Chrome for Testing.app`,`Contents`,`MacOS`,`Google Chrome for Testing`);if(e===`linux`)return(0,m.join)(t,`chrome-linux64`,`chrome`);if(e===`win32`)return(0,m.join)(t,`chrome-win${(0,C.arch)()===`x64`?`64`:`32`}`,`chrome.exe`);throw Error(`Unsupported platform: ${e}`)}async downloadFile(e,t){let n=await fetch(e);if(!n.ok||!n.body)throw Error(`Failed to download: ${n.statusText}`);let r=`${t}.tmp`,i=(0,p.createWriteStream)(r),a=n.body.getReader();await(0,te.pipeline)(new ee.Readable({async read(){let{done:e,value:t}=await a.read();e?this.push(null):this.push(Buffer.from(t))}}),i),await(0,T.rename)(r,t)}async extractZip(e,t){let n=(0,C.platform)();return new Promise((r,i)=>{let a;n===`win32`?a=(0,E.spawn)(`powershell`,[`-NoProfile`,`-Command`,`Expand-Archive -Path "${e}" -DestinationPath "${t}" -Force`]):((0,p.mkdirSync)(t,{recursive:!0}),a=(0,E.spawn)(`unzip`,[`-o`,`-q`,e,`-d`,t])),a.on(`close`,e=>{e===0?r():i(Error(`Failed to extract zip (exit code: ${e})`))}),a.on(`error`,e=>{i(Error(`Failed to spawn extraction process: ${e.message}`))})})}};Tt=_t=M([(0,d.injectable)(),j(`design:paramtypes`,[])],Tt);const Et=[`pnpm-workspace.yaml`,`nx.json`,`.git`],Dt=mt,Ot=gt,kt=Dt.split(`:`)[0]??Dt,At=`@agimon-ai/browse-tool`;function jt(e=process.cwd()){let t=m.default.resolve(e);for(;;){for(let e of Et)if(Mt(m.default.join(t,e)))return t;let n=m.default.dirname(t);if(n===t)return e;t=n}}function Mt(e){return p.default.existsSync(e)}function Nt(){return kt}function Pt(e){return`${Nt()}:${e}`}function Ft(e){let t=m.default.resolve(e);for(let e=0;e<8;e+=1){let e=m.default.join(t,`package.json`);if(Mt(e))try{if(JSON.parse(p.default.readFileSync(e,`utf8`)).name===`@agimon-ai/browse-tool`)return t}catch{}let n=m.default.dirname(t);if(n===t)break;t=n}return m.default.resolve(e,`../..`)}function It(){let e=m.default.dirname((0,D.fileURLToPath)(require(`url`).pathToFileURL(__filename).href));return m.default.join(Ft(e),`docker/chrome-for-testing.Dockerfile`)}function Lt(){return jt(Ft(m.default.dirname((0,D.fileURLToPath)(require(`url`).pathToFileURL(__filename).href))))}function Rt(e){if(!e?.includes(`:`))return;let[,t]=e.split(`:`,2),n=t?.trim();if(!(!n||!/^\d+\.\d+\.\d+\.\d+$/.test(n)))return n}function zt(e){return(e?.trim()||Ot).toLowerCase()}function Bt(e){let t=zt(e);return t.includes(`arm64`)||t.includes(`aarch64`)?`linux-arm64`:`linux64`}function Vt(e){return e.startsWith(`${Nt()}:`)}async function Ht(e,t){return await new Promise((n,r)=>{let i=``,a=(0,E.spawn)(`docker`,e,{stdio:t===`pipe`?[`ignore`,`pipe`,`pipe`]:[`ignore`,t,t]});t===`pipe`&&a.stderr?.on(`data`,e=>{i+=e.toString(`utf8`)}),a.once(`error`,r),a.once(`close`,e=>{n({exitCode:e??1,stderr:i})})})}async function Ut(e){return(await Ht([`image`,`inspect`,e],`ignore`)).exitCode===0}async function Wt(e={}){let t=e.version?.trim()||Rt(e.image)||St(),n=e.image?.trim()||Pt(t),r=zt(e.platform),i=Bt(r),a=e.stdio??`inherit`,o=await Ht([`buildx`,`build`,`--platform`,r,`--load`,`-t`,n,`--build-arg`,`CFT_VERSION=${t}`,`--build-arg`,`CFT_ARCHIVE_PLATFORM=${i}`,`-f`,It(),Lt()],a);if(o.exitCode!==0){let e=o.stderr.trim();throw Error(e?`Failed to build Docker image ${n}: ${e}`:`Failed to build Docker image ${n}`)}return{image:n,version:t,platform:r}}async function Gt(e){return!Vt(e.image)||await Ut(e.image)?!1:(await Wt({image:e.image,platform:e.platform,stdio:`inherit`}),!0)}function Kt(){let e=new Map,t=(0,E.execSync)(`ps -axo pid=,ppid=`,{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:3e3});for(let n of t.split(`
2
- `)){let[t,r]=n.trim().split(/\s+/,2);if(!t||!r)continue;let i=Number(t),a=Number(r);if(Number.isNaN(i)||Number.isNaN(a))continue;let o=e.get(a);o?o.push(i):e.set(a,[i])}return e}function qt(e){let t=[];try{let n;try{n=(0,E.execSync)(`pgrep -P ${e}`,{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:3e3}).trim().split(`
3
- `).filter(Boolean).map(Number).filter(e=>!Number.isNaN(e))}catch{n=Kt().get(e)??[]}for(let e of n)t.push(...qt(e)),t.push(e)}catch{}return t}function Jt(e){try{return process.kill(e,0),!0}catch{return!1}}async function Yt(e,t=3e3){if(!Jt(e))return;let n=[...qt(e),e];for(let e of n)try{process.kill(e,`SIGTERM`)}catch{}let r=Date.now()+t;for(;Date.now()<r;){if(!n.some(Jt))return;await new Promise(e=>setTimeout(e,100))}for(let e of n)try{Jt(e)&&process.kill(e,`SIGKILL`)}catch{}}function Xt(e,t){let n=m.default.join(C.default.tmpdir(),`proxy-auth-ext-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);p.default.mkdirSync(n,{recursive:!0});let r={manifest_version:3,name:`Proxy Auth Helper`,version:`1.0.0`,permissions:[`webRequest`,`webRequestAuthProvider`],host_permissions:[`<all_urls>`],background:{service_worker:`background.js`}},i=[`chrome.webRequest.onAuthRequired.addListener(`,` (details) => ({ authCredentials: { username: ${JSON.stringify(e)}, password: ${JSON.stringify(t)} } }),`,` { urls: ["<all_urls>"] },`,` ["blocking"]`,`);`,``].join(`
4
- `);return p.default.writeFileSync(m.default.join(n,`manifest.json`),JSON.stringify(r,null,2)),p.default.writeFileSync(m.default.join(n,`background.js`),i),n}function Zt(e){let t=[`--proxy-server=${e.server}`];return e.bypass&&t.push(`--proxy-bypass-list=${e.bypass}`),t}var R;const Qt=new Set([`docker`,`docker-vm`,`docker-chromium`,`docker-chrome-testing`]),$t=mt,en=ht,tn=`/vm/extensions/playwright`,nn=`/vm/user-data`,rn=`2g`,an=`/tmp/runtime-seluser`,on=`1920,1080`,sn=`1920x1080x24`,cn=5e3,ln=5e3,un=12e3,dn=8e3,fn=1500,pn=100,mn=32*1024,hn=3,gn=250,_n=250,vn=1500,yn=4e3,bn=100,z=process.env.BROWSE_TOOL_DEBUG_EXTENSION_RECORDING===`1`,xn=[`Current Session`,`Current Tabs`,`Last Session`,`Last Tabs`,`Sessions`],Sn=new Set([`Default`,`Guest Profile`,`System Profile`]);let Cn=class{static{R=this}static MAX_ACTIVE_BROWSERS=15;static MAX_PAGES_PER_BROWSER=15;static chromeForTestingLaunchQueue=Promise.resolve();browsers=new Map;closingExtensionRecordings=new Map;profileToBrowserId=new Map;browserIdCounter=0;constructor(e,t,n,r,i,a,o,s){this.profileService=e,this.pageRegistry=t,this.lockManager=n,this.chromeForTesting=r,this.pageMonitor=i,this.webSocketHub=a,this.extensionSessionRegistry=o,this.extensionTaskQueue=s}getBrowserByProfile(e){let t=this.profileToBrowserId.get(e);if(t){let n=this.browsers.get(t);if(n){if(this.isBrowserAlive(n))return n;this.cleanupStaleBrowser(t,e)}else this.profileToBrowserId.delete(e)}}async launch(e={}){let{profileName:t,browserType:n=`chromium`,headless:r=!0,onPageClose:i,baseURL:a,recordVideo:o,proxy:s,browserId:c}=e;if(t){let e=this.getBrowserByProfile(t);if(e){let{pageId:t,page:n}=await this.newPage(e.id,i);return{browserInstance:e,pageId:t,page:n}}}await this.enforceMaxBrowserLimit();let l=c||(t?`browser-${t}`:`browser-${++this.browserIdCounter}`);if(c&&this.browsers.has(c))throw Error(`Browser ID "${c}" is already in use`);let u=this.getBrowserType(n),d=t?await this.profileService.get(t):null;t&&!d&&(d=await this.profileService.create({name:t,browserType:n}));let f=s?{proxy:{server:s.server,username:s.username,password:s.password,bypass:s.bypass}}:{},p;if(!r&&n===`chromium`)try{p=await u.launch({headless:r,channel:`chrome`,...f})}catch{p=await u.launch({headless:r,...f})}else p=await u.launch({headless:r,...f});let m=this.buildContextOptions(d,a,o);if(d&&t){let e=await this.profileService.loadStorageState(t);e&&(m.storageState=e)}let h=await p.newContext(m),g=await h.newPage(),_=new Date,v={id:l,mode:`playwright`,browser:p,context:h,profileName:t,pageIds:new Set,currentPageId:null,createdAt:_,lastAccessedAt:_};this.browsers.set(l,v),p.on(`disconnected`,()=>{this.cleanupStaleBrowser(l,t)}),t&&this.profileToBrowserId.set(t,l);let y=await this.pageRegistry.register({page:g,browser:p,context:h,browserId:l,profileName:t,onClose:e=>{if(v.pageIds.delete(e),v.currentPageId===e){let e=Array.from(v.pageIds);v.currentPageId=e.length>0?e[0]:null}i?.(e),v.pageIds.size===0&&this.closeBrowser(l).catch(()=>{})}});return this.pageMonitor?.startMonitoring(y,g),v.pageIds.add(y),v.currentPageId=y,{browserInstance:v,pageId:y,page:g}}async launchWithExtension(e={}){let{profileName:t,command:n,commandArgs:r=[],browserId:i,mode:a=`extension`}=e;if(t){let e=this.getBrowserByProfile(t);if(e)if(!this.canReuseExtensionBrowser(e))await this.closeBrowser(e.id).catch(()=>{this.cleanupStaleBrowser(e.id,t)});else{let t=this.getTrackedExtensionPageId(e);return this.recordBrowserActivity(e.id,t),{browserInstance:e,pageId:t,process:{pid:e.pid}}}}await this.enforceMaxBrowserLimit();let o=this.resolveExtensionPath(e.extensionPath),s=m.default.join(o,`manifest.json`);if(!p.default.existsSync(s))throw Error(`Extension manifest not found at ${s}. Please build the extension first: pnpm build:extension`);let c=i||(t?`browser-${t}`:`browser-${++this.browserIdCounter}`);if(i&&this.browsers.has(i))throw Error(`Browser ID "${i}" is already in use`);t&&(await this.profileService.get(t)||await this.profileService.create({name:t,browserType:`chromium`}));let l=this.createUserDataDir(t);l&&await this.lockManager.ensureAvailable(l);let u=await this.resolveVmRuntime({command:n,launchMode:a,useChromeForTesting:e.useChromeForTesting??a===`vm`,extensionHostPath:o,requestedRuntimeExtensionPath:e.extensionPath,userDataDir:l});if(u.kind===`docker`)try{this.ensureDockerWritableUserDataDir(l)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to prepare Docker user-data directory "${l}": ${t}`,{cause:e})}let d=[u.extensionPath],f=[];if(u.kind===`docker`&&f.push(...this.createDockerVolumeArgs(o,u.extensionPath,!0)),e.proxy?.username&&e.proxy?.password){let t=Xt(e.proxy.username,e.proxy.password);if(u.kind===`docker`){let e=`${u.docker.extensionPathInContainer}-proxy-auth-${Date.now()}`;d.push(e),f.push(...this.createDockerVolumeArgs(t,e,!0))}else d.push(t)}let h=d.join(`,`),g=process.env.BROWSE_TOOL_AUTO_SELECT_TAB_CAPTURE_SOURCE_TITLE?.trim(),_=process.env.BROWSE_TOOL_AUTO_SELECT_DESKTOP_CAPTURE_SOURCE?.trim(),v=process.env.BROWSE_TOOL_USE_FAKE_UI_FOR_MEDIA_STREAM===`1`,y=[`--user-data-dir=${u.userDataDir}`,`--load-extension=${h}`,`--disable-extensions-except=${h}`,`--enable-extensions`,`--auto-accept-this-tab-capture`,...v?[`--use-fake-ui-for-media-stream`]:[],...g?[`--auto-select-tab-capture-source-by-title=${g}`]:[],..._?[`--auto-select-desktop-capture-source=${_}`]:[],`--disable-blink-features=AutomationControlled`,`--disable-infobars`,`--no-first-run`,`--no-default-browser-check`,`--disable-background-timer-throttling`,`--disable-backgrounding-occluded-windows`,`--disable-renderer-backgrounding`,`--disable-component-update`,`--disable-features=TranslateUI`,`--disable-ipc-flooding-protection`,`--password-store=basic`,`--use-mock-keychain`,`--disable-dev-shm-usage`,...u.kind===`docker`?[`--no-sandbox`]:[],`--window-size=1920,1080`,...e.proxy?Zt(e.proxy):[],e.url??`about:blank`],b=e=>{try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`||t.protocol===`file:`}catch{return!1}},x=e=>{if(!b(e))return e;try{let t=new URL(e),n=t.pathname.endsWith(`/`)&&t.pathname!==`/`?t.pathname.slice(0,-1):t.pathname;return`${t.protocol}//${t.host}${n}${t.search}`}catch{return e}},S=x(e.url??`about:blank`),C=a===`vm`&&r.length>0?[...y,...r.filter(e=>b(e)?x(e)!==S:!0)]:r.length>0?r:y,w=u.kind===`docker`?[...this.buildDockerSpawnArgs(u.docker,l,f,e.dockerRunArgs,e.dockerEnv,e.dockerEnableVnc),...C]:C,T,E=0,D;for(let n=1;n<=3;n+=1)try{let n=()=>this.startExtensionBrowser({browserId:c,launchMode:a,profileName:t,vmRuntime:u,spawnArgs:w,recordVideo:e.recordVideo,startupDelayMs:e.startupDelayMs,launchUrl:e.url});return this.shouldSerializeChromeForTestingLaunch(u)?await this.runSerializedChromeForTestingLaunch(n):await n()}catch(e){if(T=e instanceof Error?e:Error(String(e)),!this.isRetryableExtensionLaunchError(T)||n===3){if(u.kind===`docker`&&(E>0||D)){let e=[E>0?`Docker retry cleanup attempts: ${E}.`:``,D?`Last Docker retry cleanup: ${D}.`:``].filter(Boolean).join(` `);T.message=`${T.message} ${e}`.trim()}throw T}u.kind===`docker`&&(E+=1,D=await this.prepareDockerRetryUserDataDir(l)),await this.delay(250*n)}throw T??Error(`Extension browser launch failed`)}async resolveVmRuntime(e){let{command:t,launchMode:n,useChromeForTesting:r,extensionHostPath:i,requestedRuntimeExtensionPath:a,userDataDir:o}=e;if(n===`vm`&&this.isDockerVmAlias(t)){let e=this.resolveDockerRuntimeExtensionPath(a),t=process.env.PLAYWRIGHT_VM_DOCKER_USER_DATA_DIR||`/vm/user-data`,n=process.env.PLAYWRIGHT_VM_DOCKER_IMAGE||$t,r=process.env.PLAYWRIGHT_VM_DOCKER_PLATFORM||gt;return await Gt({image:n,platform:r}),{kind:`docker`,command:`docker`,extensionPath:e,userDataDir:t,docker:{image:n,browserBinary:process.env.PLAYWRIGHT_VM_DOCKER_BROWSER_BINARY||en,platform:r,extensionPathInContainer:e,userDataDirInContainer:t}}}return{kind:`host`,command:await this.resolveLaunchCommand({command:t,launchMode:n,useChromeForTesting:r}),extensionPath:i,userDataDir:o}}resolveDockerRuntimeExtensionPath(e){return e&&!p.default.existsSync(m.default.join(e,`manifest.json`))?e:process.env.PLAYWRIGHT_VM_DOCKER_EXTENSION_PATH||`/vm/extensions/playwright`}createDockerVolumeArgs(e,t,n){return[`-v`,`${m.default.resolve(e)}:${t}${n?`:ro`:``}`]}ensureDockerWritableUserDataDir(e){p.default.mkdirSync(e,{recursive:!0,mode:511});let t=[e];for(;t.length>0;){let e=t.pop();if(!e)continue;p.default.chmodSync(e,511);let n=p.default.readdirSync(e,{withFileTypes:!0});for(let r of n){let n=m.default.join(e,r.name);p.default.chmodSync(n,r.isDirectory()?511:438),r.isDirectory()&&t.push(n)}}}buildDockerSpawnArgs(e,t,n,r,i,a){let o=[`run`,`--rm`,`--init`,`--shm-size`,process.env.PLAYWRIGHT_VM_DOCKER_SHM_SIZE||`2g`];return e.platform&&o.push(`--platform`,e.platform),process.env.PLAYWRIGHT_VM_DOCKER_NETWORK&&o.push(`--network`,process.env.PLAYWRIGHT_VM_DOCKER_NETWORK),process.platform===`linux`&&o.push(`--add-host`,`host.docker.internal:host-gateway`),o.push(...n),o.push(...this.createDockerVolumeArgs(t,e.userDataDirInContainer,!1)),o.push(...this.createDockerEnvArgs(i)),o.push(...this.parseDockerRunArgs(process.env.PLAYWRIGHT_VM_DOCKER_RUN_ARGS)),o.push(...r??[]),a?(o.push(`--entrypoint`,`/bin/bash`,e.image,`-lc`,this.buildDockerBrowserLaunchScript(e.browserBinary,{enableVnc:!0}),`_`),o):(o.push(`--entrypoint`,`/bin/bash`,e.image,`-lc`,this.buildDockerBrowserLaunchScript(e.browserBinary,{enableVnc:!1}),`_`),o)}buildDockerBrowserLaunchScript(e,t){let n=[`set -euo pipefail`,`export XDG_RUNTIME_DIR="/tmp/runtime-seluser"`,`mkdir -p "$XDG_RUNTIME_DIR" "$XDG_RUNTIME_DIR/pulse"`,`chmod 700 "$XDG_RUNTIME_DIR" || true`,`export DBUS_SESSION_BUS_ADDRESS="$(dbus-daemon --session --fork --print-address --nopidfile)"`,`pulseaudio --check >/dev/null 2>&1 || pulseaudio --daemonize=yes --exit-idle-time=-1 --disable-shm=true --log-target=stderr >/tmp/pulseaudio.log 2>&1`,`export PULSE_SERVER="unix:$XDG_RUNTIME_DIR/pulse/native"`,`Xvfb :99 -screen 0 1920x1080x24 -nolisten tcp >/tmp/xvfb.log 2>&1 &`,`for i in $(seq 1 30); do xdpyinfo -display :99 >/dev/null 2>&1 && break; sleep 0.2; done`,`export DISPLAY=:99`,`BROWSER_BIN=${JSON.stringify(e)}`,`exec "$BROWSER_BIN" "$@"`];return t.enableVnc&&n.splice(n.length-2,0,'if [ -n "${SE_VNC_PASSWORD:-}" ]; then',' x11vnc -storepasswd "${SE_VNC_PASSWORD}" /tmp/vnc-passwd >/dev/null 2>&1',` X11VNC_AUTH="-rfbauth /tmp/vnc-passwd"`,`else`,` X11VNC_AUTH=""`,`fi`,'x11vnc -forever -shared -rfbport "${SE_VNC_PORT:-5900}" -display :99 $X11VNC_AUTH >/tmp/x11vnc.log 2>&1 &',`if command -v websockify >/dev/null 2>&1; then`,' websockify --web /opt/bin/noVNC "${SE_NO_VNC_PORT:-7900}" "localhost:${SE_VNC_PORT:-5900}" >/tmp/novnc.log 2>&1 &',`fi`),n.join(`
5
- `)}createDockerEnvArgs(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))n&&t.push(`-e`,`${n}=${r}`);return t}parseDockerRunArgs(e){return e?e.split(/\s+/).map(e=>e.trim()).filter(e=>e.length>0):[]}isDockerVmAlias(e){if(!e)return!1;let t=e.trim().toLowerCase();return Qt.has(t)}async resolveLaunchCommand(e){let{command:t,launchMode:n,useChromeForTesting:r}=e;if(n===`vm`&&r){if(!t)return this.findChromeExecutable();if(this.isChromeTestingAlias(t)||this.isGenericChromeAlias(t))return this.chromeForTesting.getExecutablePath()}return t||this.findChromeExecutable()}isChromeTestingAlias(e){let t=e.trim().toLowerCase();return t===`chrome-testing`||t===`chrome-for-testing`||t===`google-chrome-for-testing`||t.endsWith(`google chrome for testing`)||t.endsWith(`google-chrome-for-testing`)||t.endsWith(`chrome-for-testing.exe`)}isGenericChromeAlias(e){let t=e.trim().toLowerCase(),n=m.default.basename(t);return n===`chrome`||n===`google-chrome`||n===`googlechrome`}resolveExtensionPath(e){if(e&&p.default.existsSync(m.default.join(e,`manifest.json`)))return e;let t=m.default.dirname((0,D.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),n=this.findPackageRoot(t),r=[n?m.default.resolve(n,`dist/extension`):``,m.default.resolve(t,`../dist/extension`),m.default.resolve(t,`../../dist/extension`)].filter(Boolean);for(let e of r)if(p.default.existsSync(m.default.join(e,`manifest.json`)))return e;let i=m.default.resolve(process.cwd(),`dist/extension`);if(p.default.existsSync(m.default.join(i,`manifest.json`)))return i;throw Error(`Chrome extension not found. Build the extension first: pnpm build:extension`)}findPackageRoot(e,t=`@agimon-ai/browse-tool`){let n=e;for(let e=0;e<8;e++){let e=m.default.join(n,`package.json`);if(p.default.existsSync(e))try{if(JSON.parse(p.default.readFileSync(e,`utf8`))?.name===t)return n}catch{}let r=m.default.dirname(n);if(r===n)break;n=r}return null}getExtensionUserDataDir(e){return m.default.join(this.profileService.getProfilesDir(),e,`extension-user-data`)}createUserDataDir(e){if(e){let t=this.getExtensionUserDataDir(e);return p.default.mkdirSync(t,{recursive:!0}),this.cleanupExtensionSessionRestoreArtifacts(t),t}return p.default.mkdtempSync(m.default.join(C.default.tmpdir(),`extension-chrome-`))}cleanupExtensionSessionRestoreArtifacts(e){for(let t of this.getSessionRestoreProfileDirs(e))for(let e of xn)try{p.default.rmSync(m.default.join(t,e),{recursive:!0,force:!0})}catch{}}getSessionRestoreProfileDirs(e){let t=[e],n=(()=>{try{return p.default.readdirSync(e,{withFileTypes:!0})}catch{return null}})();if(!n)return t;for(let r of n)r.isDirectory()&&(Sn.has(r.name)||r.name.startsWith(`Profile `))&&t.push(m.default.join(e,r.name));return t}async findChromeExecutable(){try{return await this.chromeForTesting.getExecutablePath()}catch{}let e=process.platform,t={darwin:[`/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`,`/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary`,`${C.default.homedir()}/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`],linux:[`/usr/bin/google-chrome`,`/usr/bin/google-chrome-stable`,`/usr/bin/chromium`,`/usr/bin/chromium-browser`,`/snap/bin/chromium`],win32:[`${process.env.LOCALAPPDATA}\\Google\\Chrome\\Application\\chrome.exe`,`${process.env.PROGRAMFILES}\\Google\\Chrome\\Application\\chrome.exe`,`${process.env[`PROGRAMFILES(X86)`]}\\Google\\Chrome\\Application\\chrome.exe`]};for(let n of t[e]??[])if(p.default.existsSync(n))return n;throw Error(`Chrome not found. Install Google Chrome or run with Chrome for Testing.`)}async newPage(e,t){let n=this.browsers.get(e);if(!n)throw Error(`Browser "${e}" not found`);if(n.mode===`extension`||n.mode===`vm`)throw Error(`Cannot create new page in extension mode browser. Use extension APIs directly.`);if(!n.context||!n.browser)throw Error(`Browser "${e}" has no Playwright context`);await this.enforceMaxPageLimit(n);let r=await n.context.newPage(),i=await this.pageRegistry.register({page:r,browser:n.browser,context:n.context,browserId:e,profileName:n.profileName,onClose:r=>{if(n.pageIds.delete(r),n.currentPageId===r){let e=Array.from(n.pageIds);n.currentPageId=e.length>0?e[0]:null}t?.(r),n.pageIds.size===0&&this.closeBrowser(e).catch(()=>{})}});return this.pageMonitor?.startMonitoring(i,r),n.pageIds.add(i),{pageId:i,page:r}}getBrowser(e){return this.browsers.get(e)}getDefaultBrowser(){let e=this.listBrowsers();for(let t of e){if(this.isBrowserAlive(t))return t;this.cleanupStaleBrowser(t.id,t.profileName)}}async getOrCreateDefaultBrowser(e){return this.getDefaultBrowser()||(await this.launch(e)).browserInstance}setCurrentPage(e,t){let n=this.browsers.get(e);if(!n)throw Error(`Browser "${e}" not found`);if(!n.pageIds.has(t))throw Error(`Page "${t}" does not belong to browser "${e}"`);n.extensionRecording?.active&&n.extensionRecording.pageId!==t&&console.warn(`[BrowserService] Extension recording for browser "${e}" remains pinned to initial page "${n.extensionRecording.pageId}"`),n.currentPageId=t}async closeBrowser(e){let t=this.browsers.get(e);if(t){let n,r=t.extensionRecording,i=r?.outputPath,a=r?.active===!0,o=!1;if(r&&this.closingExtensionRecordings.set(e,r),a)try{if(n=(await this.attemptExtensionRecordingFinalization(e)).error,n&&r&&this.shouldCloseRecordedExtensionPageFirst(t)&&(await this.closeRecordedExtensionPage(t,r),i)){if(!await this.waitForExtensionRecordingArtifact(i))throw Error(`Extension recording for browser "${e}" was not persisted after the recorded tab closed`);r.active=!1,n=void 0}}catch(e){n=e instanceof Error?e:Error(String(e))}else try{await this.finalizeExtensionRecording(e)}catch(e){n=e instanceof Error?e:Error(String(e))}if(t.browser)await t.browser.close();else if(t.context)if(t.pid)try{await Yt(t.pid)}catch{try{let e=t.context.pages();await Promise.all(e.map(e=>e.close().catch(e=>{}))),await t.context.close()}catch{}}else{let e=t.context.pages();await Promise.all(e.map(e=>e.close().catch(e=>{}))),await t.context.close()}else if(t.pid)try{await Yt(t.pid)}catch{}if(i&&r&&!p.default.existsSync(i)){let t=await this.waitForExtensionRecordingArtifactOrChunks(r),a=t.artifactReady;!a&&t.chunkReady&&(a=await this.persistExtensionRecordingArtifact(e)||p.default.existsSync(i)),a?n=void 0:r&&(o=!0)}if(t.profileName&&this.profileToBrowserId.delete(t.profileName),this.browsers.delete(e),o?this.finalizeClosingExtensionRecording(e):this.closingExtensionRecordings.delete(e),n)throw n}}async closeAll(){let e=Array.from(this.browsers.keys());await Promise.all(e.map(e=>this.closeBrowser(e).catch(()=>{}))),this.browsers.clear(),this.profileToBrowserId.clear(),this.pageRegistry.clear()}listBrowsers(){return Array.from(this.browsers.values())}touchBrowser(e){let t=this.browsers.get(e);t&&(t.lastAccessedAt=new Date)}recordBrowserActivity(e,t){let n=this.browsers.get(e);return n?(n.lastAccessedAt=new Date,t&&this.pageRegistry.touchPage(t),!0):!1}registerExtensionBrowser(){let e=`browser-${++this.browserIdCounter}`,t=new Date,n={id:e,mode:`extension`,browser:void 0,context:void 0,pageIds:new Set,currentPageId:null,createdAt:t,lastAccessedAt:t};return this.browsers.set(e,n),e}registerExtensionBrowserWithId(e){if(this.browsers.has(e))return;let t=new Date,n={id:e,mode:`extension`,browser:void 0,context:void 0,pageIds:new Set,currentPageId:null,createdAt:t,lastAccessedAt:t};this.browsers.set(e,n)}async ensureExtensionRecordingActive(e,t){let n=this.browsers.get(e),r=n?.extensionRecording;!n||!r||r.pageId!==t||r.active||(r.startPromise||=this.startExtensionRecording(n,r).finally(()=>{n.extensionRecording===r&&(n.extensionRecording.startPromise=void 0)}),await r.startPromise)}async startPageRecording(e,t,n){let r=this.browsers.get(e);if(!r)throw Error(`Browser "${e}" not found`);if(r.mode!==`extension`&&r.mode!==`vm`)throw Error(`Browser "${e}" does not support extension recording in "${r.mode}" mode`);let i=r.extensionRecording;if(i&&i.pageId!==t){if(i.active)throw Error(`Browser "${e}" is already recording page "${i.pageId}". Stop the current recording before starting another one.`);r.extensionRecording=void 0,i=void 0}let a=n?m.default.resolve(n):i?.outputPath??m.default.join(C.default.tmpdir(),`browse-tool-recordings`,`recording-${this.toSafeRecordingId(e)}-${Date.now()}.webm`);if(!i)this.initializeExtensionRecordingAtPath(r,t,a),i=r.extensionRecording;else if(i.outputPath!==a){if(i.active)throw Error(`Browser "${e}" is already recording to "${i.outputPath}". Stop the current recording before changing output path.`);i.outputPath=a,i.chunkPath=`${a}.part`,this.clearExtensionRecordingChunkState(i)}if(!i)throw Error(`Failed to initialize recording for browser "${e}"`);return await this.ensureExtensionRecordingActive(e,t),{outputPath:i.outputPath}}async finalizeExtensionRecording(e,t){let n=this.browsers.get(e),r=n?.extensionRecording;if(!n||!r||t&&r.pageId!==t||!r.active)return;if(!this.extensionTaskQueue)throw Error(`Extension recording task queue is unavailable for browser "${e}"`);let i=wt();z&&console.log(`[ExtensionRecordingDebug] queue stop browser=${e} page=${r.pageId} active=${r.active} cleanupUi=${i}`);let a;try{a=await this.extensionTaskQueue.queueTask(`browser_stop_recording`,{pageId:r.pageId,cleanupUi:i},P,e)}finally{r.active=!1}z&&console.log(`[ExtensionRecordingDebug] stop result browser=${e} success=${a?.success===!0} isError=${a?.result?.isError===!0}`);let o;try{o=this.parseExtensionRecordingPayload(a)}catch(t){if(await this.persistExtensionRecordingArtifact(e))return;throw t}if(o.videoBase64){p.default.mkdirSync(m.default.dirname(r.outputPath),{recursive:!0}),p.default.writeFileSync(r.outputPath,Buffer.from(o.videoBase64,`base64`)),this.clearExtensionRecordingChunkState(r),r.active=!1;return}if(!await this.persistExtensionRecordingArtifact(e))throw Error(`Extension recording for browser "${e}" stopped without video data`)}async stopPageRecording(e,t,n={}){let r=this.browsers.get(e)?.extensionRecording??this.closingExtensionRecordings.get(e);if(!r)throw Error(`Browser "${e}" has no recording session`);if(t&&r.pageId!==t)throw Error(`Page "${t}" does not match the active recording for browser "${e}"`);this.closingExtensionRecordings.set(e,r);let i;try{i=(await this.attemptExtensionRecordingFinalization(e)).error}catch(e){i=e instanceof Error?e:Error(String(e))}if(!p.default.existsSync(r.outputPath)){let t=await this.waitForExtensionRecordingArtifactOrChunks(r),n=t.artifactReady;if(!n&&t.chunkReady&&(n=await this.persistExtensionRecordingArtifact(e)||p.default.existsSync(r.outputPath)),!n&&i)throw i}if(!p.default.existsSync(r.outputPath))throw Error(`Recording artifact for browser "${e}" was not written to "${r.outputPath}"`);let a=p.default.readFileSync(r.outputPath);return this.closingExtensionRecordings.delete(e),{outputPath:r.outputPath,fileSizeBytes:a.byteLength,...n.includeBase64?{videoBase64:a.toString(`base64`)}:{}}}async persistExtensionRecordingArtifact(e,t){let n=this.getExtensionRecordingSession(e);if(!n)return!1;if(!t&&this.hasPersistedExtensionRecordingArtifact(n))return n.active=!1,this.closingExtensionRecordings.delete(e),!0;if(p.default.mkdirSync(m.default.dirname(n.outputPath),{recursive:!0}),t)p.default.writeFileSync(n.outputPath,Buffer.from(t,`base64`)),this.clearExtensionRecordingChunkState(n);else if(!this.persistExtensionRecordingChunksToArtifact(n))return!1;return n.active=!1,this.closingExtensionRecordings.delete(e),!0}async persistExtensionRecordingChunk(e,t){let n=this.getExtensionRecordingSession(e);if(!n||!t)return null;let r=Buffer.from(t,`base64`);return r.length===0?null:(p.default.mkdirSync(m.default.dirname(n.chunkPath),{recursive:!0}),p.default.appendFileSync(n.chunkPath,r),n.chunkCount+=1,n.chunkBytes+=r.length,{chunkBytes:r.length,totalBytes:n.chunkBytes,chunkCount:n.chunkCount})}async enforceMaxPageLimit(e){if(e.pageIds.size<R.MAX_PAGES_PER_BROWSER)return;let t=this.pageRegistry.findByBrowser(e.id);t.sort((e,t)=>e.createdAt.getTime()-t.createdAt.getTime());let n=t[0];n&&(n.page?await n.page.close():(this.pageRegistry.remove(n.id),e.pageIds.delete(n.id)))}async enforceMaxBrowserLimit(){if(this.browsers.size>=R.MAX_ACTIVE_BROWSERS){let e=Array.from(this.browsers.values());e.sort((e,t)=>e.createdAt.getTime()-t.createdAt.getTime());let t=e[0];t&&await this.closeBrowser(t.id)}}isBrowserAlive(e){try{if(e.mode===`playwright`)return e.browser?.isConnected()??!1;if(e.mode===`extension`||e.mode===`vm`){if(!e.pid||!this.isProcessRunning(e.pid))return!1;if(!e.context)return!0;try{return e.context.pages(),!0}catch{return!1}}return!1}catch{return!1}}isProcessRunning(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}captureProcessOutput(){let e=[],t=0,n=(n,r)=>{if(typeof r!=`string`&&!Buffer.isBuffer(r))return;let i=typeof r==`string`?r:r.toString(`utf8`);if(!i)return;let a=32768-t;if(a<=0)return;let o=Buffer.from(i,`utf8`).subarray(0,a).toString(`utf8`);t+=Buffer.byteLength(o,`utf8`),e.push(`[${n}] ${o}`)};return{attach:e=>{e.stdout?.on(`data`,e=>n(`stdout`,e)),e.stderr?.on(`data`,e=>n(`stderr`,e))},snapshot:()=>e.join(``)}}async startExtensionBrowser(e){let{browserId:t,launchMode:n,profileName:r,vmRuntime:i,spawnArgs:a,recordVideo:o,startupDelayMs:s,launchUrl:c}=e,l=this.captureProcessOutput(),u=(0,E.spawn)(i.command,a,{detached:!1,stdio:[`ignore`,`pipe`,`pipe`],env:i.kind===`docker`?process.env:{...process.env,DISPLAY:process.env.DISPLAY}});if(!u.pid)throw Error(`Failed to start Chrome process`);l.attach(u);let d=new Date,f={id:t,mode:n,browser:void 0,context:void 0,profileName:r,pageIds:new Set,currentPageId:null,pid:u.pid,createdAt:d,lastAccessedAt:d};u.on(`exit`,()=>this.cleanupStaleBrowser(t,r)),u.on(`error`,()=>this.cleanupStaleBrowser(t,r)),this.browsers.set(t,f),r&&this.profileToBrowserId.set(r,t);let p=this.pageRegistry.registerExtensionPage(t);f.pageIds.add(p),f.currentPageId=p;try{if(await this.waitForExtensionReady(t,u,l,{vmRuntimeKind:i.kind,launchUrl:c}),o){z&&console.log(`[ExtensionRecordingDebug] initialize recording browser=${f.id} page=${p} dir=${o.dir}`),this.initializeExtensionRecording(f,p,o);let e=f.extensionRecording;e&&this.startExtensionRecording(f,e).catch(e=>{console.warn(`[BrowserService] Failed to eagerly start extension recording for browser "${f.id}" on page "${p}":`,e)})}}catch(e){throw await this.closeBrowser(t).catch(()=>{}),e}return s&&s>0&&await this.delay(s),{browserInstance:f,pageId:p,process:u}}async waitForExtensionReady(e,t,n,r){if(!this.webSocketHub&&!this.extensionSessionRegistry)return;let i=null,a=null,o;t.once(`exit`,(e,t)=>{i=e,a=t}),t.once(`error`,e=>{o=e});let s=null,c=!1,l=0,u=0,d=null,f=!1,p=Date.now(),m=this.getExtensionStartupTimeoutMs(r.vmRuntimeKind),h=this.getExtensionStartupGraceTimeoutMs(r.vmRuntimeKind),g=this.getExtensionReadyStabilityMs(),_=this.getExtensionStartupPollIntervalMs(),v=p+m;for(;;){let t=Date.now();if(t>=v){if(!f&&o===void 0&&i===null&&a===null){f=!0,v=t+h;continue}break}let n=this.getExtensionReadyState(e);if(n.connected){if(c=!0,n.explicit||(s??=t,d??=t,u=Math.max(u,t-s),t-s>=g))return}else s!==null&&(l+=1,u=Math.max(u,t-s)),s=null;if(o||i!==null||a!==null)break;await new Promise(e=>setTimeout(e,_))}let y=this.getExtensionReadyState(e);if(y.connected&&(y.explicit||s!==null&&Date.now()-s>=g))return;let b=n.snapshot(),x=this.writeLaunchFailureLog(e,b),S=[`Chrome extension browser "${e}" failed to become ready within ${m+(f?h:0)}ms.`,`Ready state requires a stable session for ${g}ms.`,`Observed connection: ${c?`yes`:`no`}.`,c&&d!==null?`First connection observed after ${Math.max(0,d-p)}ms.`:void 0,`Longest stable connection: ${u}ms.`,l>0?`Connection flaps: ${l}.`:void 0,f?`Startup grace applied: ${h}ms.`:void 0,r.launchUrl?`Launch URL: ${r.launchUrl}.`:void 0,o?`Error: ${o.message}`:void 0,i===null?void 0:`Exit code: ${i}`,a?`Signal: ${a}`:void 0,x?`Launch log: ${x}`:void 0].filter(Boolean).join(` `);throw Error(S)}getExtensionStartupTimeoutMs(e){return e===`docker`?12e3:5e3}getExtensionStartupGraceTimeoutMs(e){return e===`docker`?8e3:5e3}getExtensionReadyStabilityMs(){return 1500}getExtensionStartupPollIntervalMs(){return 100}isRetryableExtensionLaunchError(e){return/failed to become ready/i.test(e.message)||/Failed to start Chrome process/i.test(e.message)}shouldSerializeChromeForTestingLaunch(e){return process.platform===`darwin`&&e.kind===`host`&&this.isChromeTestingAlias(e.command)}async runSerializedChromeForTestingLaunch(e){let t,n=R.chromeForTestingLaunchQueue;R.chromeForTestingLaunchQueue=new Promise(e=>{t=e}),await n;try{return await e()}finally{t?.()}}async delay(e){await new Promise(t=>setTimeout(t,e))}getExtensionReadyState(e){return this.extensionSessionRegistry?{connected:!!this.extensionSessionRegistry.getSessionByBrowserId(e),explicit:!0}:{connected:!!this.webSocketHub?.hasConnection(e),explicit:!1}}hasExtensionConnection(e){return this.getExtensionReadyState(e).connected}canReuseExtensionBrowser(e){return e.mode!==`extension`&&e.mode!==`vm`||!e.pid?!1:this.isProcessRunning(e.pid)&&this.hasExtensionConnection(e.id)}getTrackedExtensionPageId(e){let t=e.currentPageId&&this.pageRegistry.get(e.currentPageId)?e.currentPageId:Array.from(e.pageIds).find(e=>this.pageRegistry.get(e));if(t)return e.currentPageId=t,t;let n=this.pageRegistry.registerExtensionPage(e.id);return e.pageIds.add(n),e.currentPageId=n,n}writeLaunchFailureLog(e,t){if(t.trim())try{let n=m.default.join(C.default.tmpdir(),`${e}-launch.log`);return p.default.writeFileSync(n,t,`utf8`),n}catch{return}}async prepareDockerRetryUserDataDir(e){await this.delay(250);try{let t=await this.lockManager.cleanupOrphanedLocks(e);return this.cleanupExtensionSingletonArtifacts(e),`${t?`cleaned`:`checked`} ${e}`}catch(t){let n=t instanceof Error?t.message:String(t);return this.cleanupExtensionSingletonArtifacts(e),`lock-manager cleanup failed (${n}); singleton artifacts removed directly from ${e}`}}cleanupExtensionSingletonArtifacts(e){let t=[m.default.join(e,`SingletonLock`),m.default.join(e,`SingletonCookie`),m.default.join(e,`SingletonSocket`),m.default.join(e,`lockfile`),m.default.join(e,`Default`,`LOCK`)];for(let e of t)try{p.default.rmSync(e,{force:!0})}catch{}}cleanupStaleBrowser(e,t){if(t){let e=this.getExtensionUserDataDir(t);this.cleanupExtensionSingletonArtifacts(e),this.lockManager.cleanupOrphanedLocks(e).catch(()=>{})}this.browsers.delete(e),t&&this.profileToBrowserId.delete(t)}initializeExtensionRecording(e,t,n){let r=m.default.join(n.dir,`recording-${this.toSafeRecordingId(e.id)}-${e.createdAt.getTime()}.webm`);this.initializeExtensionRecordingAtPath(e,t,r)}initializeExtensionRecordingAtPath(e,t,n){e.extensionRecording={pageId:t,outputPath:n,chunkPath:`${n}.part`,active:!1,chunkCount:0,chunkBytes:0}}async startExtensionRecording(e,t){if(!this.extensionTaskQueue)throw Error(`Extension recording task queue is unavailable for browser "${e.id}"`);z&&console.log(`[ExtensionRecordingDebug] queue start browser=${e.id} page=${t.pageId} active=${t.active}`);let n=await this.extensionTaskQueue.queueTask(`browser_start_recording`,{pageId:t.pageId},P,e.id);if(z&&console.log(`[ExtensionRecordingDebug] start result browser=${e.id} success=${n?.success===!0} isError=${n?.result?.isError===!0}`),!n.success||n.result?.isError){let r=this.getExtensionTaskError(n);if(this.isExtensionRecordingAlreadyActiveError(r)){t.active=!0;return}throw Error(r??`Failed to start extension recording for "${e.id}"`)}t.active=!0}isExtensionRecordingAlreadyActiveError(e){return e?/active stream/i.test(e)||/recording already in progress/i.test(e):!1}async attemptExtensionRecordingFinalization(e){let t=this.finalizeExtensionRecording(e).then(()=>({completed:!0})).catch(e=>({completed:!0,error:e instanceof Error?e:Error(String(e))})),n=this.delay(1500).then(()=>({completed:!1}));return Promise.race([t,n])}async waitForExtensionRecordingArtifact(e){let t=Date.now();for(;Date.now()-t<yn;){try{let t=p.default.statSync(e);if(t.isFile()&&t.size>0)return!0}catch{}await this.delay(100)}return!1}async waitForExtensionRecordingArtifactOrChunks(e){let t=Date.now();for(;Date.now()-t<yn;){try{let t=p.default.statSync(e.outputPath);if(t.isFile()&&t.size>0)return{artifactReady:!0,chunkReady:!1}}catch{}try{let t=p.default.statSync(e.chunkPath);if(t.isFile()&&t.size>0)return{artifactReady:!1,chunkReady:!0}}catch{}await this.delay(100)}return{artifactReady:!1,chunkReady:!1}}getExtensionRecordingSession(e){return this.browsers.get(e)?.extensionRecording??this.closingExtensionRecordings.get(e)}async finalizeClosingExtensionRecording(e){let t=this.closingExtensionRecordings.get(e);if(t)try{let n=await this.waitForExtensionRecordingArtifactOrChunks(t);!n.artifactReady&&n.chunkReady&&await this.persistExtensionRecordingArtifact(e)}finally{this.closingExtensionRecordings.delete(e)}}shouldCloseRecordedExtensionPageFirst(e){return(e.mode===`extension`||e.mode===`vm`)&&!!e.extensionRecording&&!!this.extensionTaskQueue}async closeRecordedExtensionPage(e,t){if(!this.extensionTaskQueue)throw Error(`Extension recording task queue is unavailable for browser "${e.id}"`);if(e.pageIds.size<=1){let t=await this.extensionTaskQueue.queueTask(`browser_new_page`,{url:`about:blank`,setAsCurrent:!1},P,e.id);if(!t.success||t.result?.isError)throw Error(this.getExtensionTaskError(t)??`Failed to create a keepalive tab for browser "${e.id}" before closing the recorded page`)}let n=await this.extensionTaskQueue.queueTask(`browser_close_page`,{pageId:t.pageId},P,e.id);if(!n.success||n.result?.isError)throw Error(this.getExtensionTaskError(n)??`Failed to close the recorded page "${t.pageId}" for browser "${e.id}"`)}parseExtensionRecordingPayload(e){if(!e.success||e.result?.isError)throw Error(this.getExtensionTaskError(e)??`Extension recording task failed`);let t=e.result?.content[0],n=t?.type===`text`?t.text:void 0;if(!n)return{};try{return JSON.parse(n)}catch{throw Error(`Extension recording task returned invalid JSON payload`)}}getExtensionTaskError(e){if(e.error)return e.error;let t=e.result?.content[0];if(t?.type===`text`)return t.text}toSafeRecordingId(e){return e.replace(/[^a-zA-Z0-9_-]+/g,`-`)}persistExtensionRecordingChunksToArtifact(e){try{let t=p.default.statSync(e.chunkPath);if(!t.isFile()||t.size<=0)return!1}catch{return!1}if(p.default.existsSync(e.outputPath)){let t=p.default.statSync(e.outputPath);if(t.isFile()&&t.size>0)return this.clearExtensionRecordingChunkState(e),!0}return p.default.renameSync(e.chunkPath,e.outputPath),e.chunkCount=0,e.chunkBytes=0,!0}hasPersistedExtensionRecordingArtifact(e){try{let t=p.default.statSync(e.outputPath);return t.isFile()&&t.size>0}catch{return!1}}clearExtensionRecordingChunkState(e){e.chunkCount=0,e.chunkBytes=0;try{p.default.existsSync(e.chunkPath)&&p.default.rmSync(e.chunkPath,{force:!0})}catch{}}getBrowserType(e){switch(e){case`chromium`:return O.chromium;case`firefox`:return O.firefox;case`webkit`:return O.webkit}}buildContextOptions(e,t,n){let r={};return t&&(r.baseURL=t),n&&(r.recordVideo=n),e?(e.viewport&&(r.viewport=e.viewport),e.userAgent&&(r.userAgent=e.userAgent),e.locale&&(r.locale=e.locale),e.timezone&&(r.timezoneId=e.timezone),e.geolocation&&(r.geolocation=e.geolocation),e.permissions&&(r.permissions=e.permissions),e.colorScheme&&(r.colorScheme=e.colorScheme),r):r}};Cn=R=M([(0,d.injectable)(),F(0,(0,d.inject)(A.ProfileService)),F(1,(0,d.inject)(A.PageRegistry)),F(2,(0,d.inject)(A.BrowserLockManager)),F(3,(0,d.inject)(A.ChromeForTestingService)),F(4,(0,d.inject)(A.PageMonitorService)),F(4,(0,d.optional)()),F(5,(0,d.inject)(A.WebSocketHub)),F(5,(0,d.optional)()),F(6,(0,d.inject)(A.ExtensionSessionRegistry)),F(6,(0,d.optional)()),F(7,(0,d.inject)(A.ExtensionTaskQueue)),F(7,(0,d.optional)()),j(`design:paramtypes`,[Object,Object,Object,Object,Object,Object,Object,Object])],Cn);function wn(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`snippet`}function Tn(e){return e.replace(/\r\n/g,`
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));const c=require(`./playwright-test-DfpyCIc0.cjs`);require(`reflect-metadata/lite`);let l=require(`@modelcontextprotocol/sdk/server/stdio.js`),u=require(`@modelcontextprotocol/sdk/types.js`),d=require(`inversify`),f=require(`node:async_hooks`),p=require(`node:fs`);p=s(p);let m=require(`node:path`);m=s(m);let h=require(`@opentelemetry/api`),g=require(`@opentelemetry/exporter-trace-otlp-http`),_=require(`@opentelemetry/resources`),v=require(`@opentelemetry/sdk-trace-node`),y=require(`@agimon-ai/foundation-port-registry`),b=require(`@agimon-ai/log-sink-mcp`),x=require(`node:os`);x=s(x);let S=require(`zod`),C=require(`@agimon-ai/foundation-process-registry`),w=require(`node:fs/promises`);w=s(w);let T=require(`node:child_process`),E=require(`node:url`),D=require(`playwright`);D=s(D);let ee=require(`node:stream`),te=require(`node:stream/promises`),ne=require(`node:module`),re=require(`esbuild`),O=require(`node:crypto`),ie=require(`node:http`),ae=require(`@modelcontextprotocol/sdk/server/streamableHttp.js`);const oe=`ProfileService`,se=`PageRegistry`,ce=`BrowserService`,le=`ElementLocatorService`,ue=`PageMonitorService`,de=`PauseController`,fe=`AutomationRunner`,pe=`SpecRunner`,me=`SpecBundlerService`,he=`SpecDiscoveryService`,ge=`SpecMetadataService`,_e=`SetupRunner`,ve=`WebServerManager`,ye=`Logger`,be=`TelemetryService`,xe=`CodeSnippetService`,Se=`HttpServerHealthCheck`,Ce=`HttpServerManager`,we=`HttpBrowserClient`,Te=`RemoteToolExecutor`,Ee=`ProcessRegistryService`,De=`ExtensionTaskQueue`,Oe=`ExtensionToolDelegator`,ke=`ToolExecutor`,Ae=`ExtensionSessionRegistry`,je=`ExtensionPageProxy`,Me=`ExtensionSpecRunner`,Ne=`StealthLauncher`,Pe=`BrowserLockManager`,Fe=`McpSessionTracker`,Ie=`ChromeForTestingService`,Le=`WebSocketHub`,Re=`IdleCleanupService`,ze=`PortRegistryService`,Be=`Tool`,k={ProfileService:Symbol.for(`ProfileService`),PageRegistry:Symbol.for(`PageRegistry`),BrowserService:Symbol.for(`BrowserService`),ElementLocatorService:Symbol.for(`ElementLocatorService`),PageMonitorService:Symbol.for(`PageMonitorService`),PauseController:Symbol.for(`PauseController`),AutomationRunner:Symbol.for(`AutomationRunner`),SpecRunner:Symbol.for(`SpecRunner`),SpecBundlerService:Symbol.for(`SpecBundlerService`),SpecDiscoveryService:Symbol.for(`SpecDiscoveryService`),SpecMetadataService:Symbol.for(`SpecMetadataService`),SetupRunner:Symbol.for(`SetupRunner`),WebServerManager:Symbol.for(`WebServerManager`),Logger:Symbol.for(`Logger`),TelemetryService:Symbol.for(`TelemetryService`),CodeSnippetService:Symbol.for(`CodeSnippetService`),HttpServerHealthCheck:Symbol.for(`HttpServerHealthCheck`),HttpServerManager:Symbol.for(`HttpServerManager`),HttpBrowserClient:Symbol.for(`HttpBrowserClient`),RemoteToolExecutor:Symbol.for(`RemoteToolExecutor`),ExtensionTaskQueue:Symbol.for(`ExtensionTaskQueue`),ExtensionToolDelegator:Symbol.for(`ExtensionToolDelegator`),ToolExecutor:Symbol.for(`ToolExecutor`),StealthLauncher:Symbol.for(`StealthLauncher`),BrowserLockManager:Symbol.for(`BrowserLockManager`),ExtensionSessionRegistry:Symbol.for(`ExtensionSessionRegistry`),ExtensionPageProxy:Symbol.for(`ExtensionPageProxy`),ExtensionSpecRunner:Symbol.for(`ExtensionSpecRunner`),McpSessionTracker:Symbol.for(`McpSessionTracker`),ChromeForTestingService:Symbol.for(`ChromeForTestingService`),WebSocketHub:Symbol.for(`WebSocketHub`),IdleCleanupService:Symbol.for(`IdleCleanupService`),PortRegistryService:Symbol.for(`PortRegistryService`),ProcessRegistryService:Symbol.for(`ProcessRegistryService`),Tool:Symbol.for(`Tool`)};function A(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function j(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}const Ve=`browse-tool-http`,He=`log-sink-mcp-http`,Ue=[`pnpm-workspace.yaml`,`nx.json`,`.git`],We=new Set([`127.0.0.1`,`localhost`,`::1`,`0.0.0.0`]);function Ge(e){return e===`1`||e===`true`}function Ke(e){return Array.isArray(e)?JSON.stringify(e):typeof e==`string`||typeof e==`number`||typeof e==`boolean`?e:JSON.stringify(e)}function qe(e){if(!e)return;let t={};for(let[n,r]of Object.entries(e))r!=null&&(t[n]=Ke(r));return Object.keys(t).length>0?t:void 0}function Je(e){if(!e)return;let t={};for(let n of e.split(`,`)){let[e,...r]=n.split(`=`),i=e?.trim(),a=r.join(`=`).trim();!i||!a||(t[i]=a)}return Object.keys(t).length>0?t:void 0}function Ye(e){if(!e)return;let t=Number(e);return Number.isFinite(t)&&t>0?t:void 0}function Xe(e,t){let n=e.endsWith(`/`)?e:`${e}/`;return n.endsWith(`/v1/${t}/`)||n.endsWith(`/v1/${t}`)?e:new URL(`v1/${t}`,n).toString()}function Ze(e){return We.has(e)}function Qe(e=process.cwd()){let t=m.default.resolve(e);for(;;){for(let e of Ue)if((0,p.existsSync)(m.default.join(t,e)))return t;let e=m.default.dirname(t);if(e===t)return process.cwd();t=e}}function $e(e,t=process.cwd()){try{let n=(0,p.readFileSync)(y.PortRegistryService.resolveRegistryPath(e.PORT_REGISTRY_PATH??y.DEFAULT_REGISTRY_PATH),`utf8`),r=y.PortRegistryStateSchema.parse(JSON.parse(n)),i=(0,y.normalizeRepositoryPath)(Qe(t)),a=e.NODE_ENV||`development`,o=e.BROWSE_TOOL_OTEL_LOG_SINK_SERVICE_NAME??`log-sink-mcp-http`,s=r.entries.find(e=>e.repositoryPath===i&&e.serviceName===o&&e.serviceType===`tool`&&(e.environment??`development`)===a);if(!s)return;let c=typeof s.metadata?.healthCheckUrl==`string`&&s.metadata.healthCheckUrl.length>0?s.metadata.healthCheckUrl:void 0;return c?new URL(c).origin:`http://${s.host===`0.0.0.0`?`127.0.0.1`:s.host}:${s.port}`}catch{return}}function et(e,t){try{let n=new URL(e),r=new URL(t);return!Ze(n.hostname)||Ze(r.hostname)||(n.hostname=r.hostname),n.toString()}catch{return e}}function tt(e,t){let n=t===`traces`?e.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT:e.OTEL_EXPORTER_OTLP_LOGS_ENDPOINT;if(n)return n;let r=e.OTEL_EXPORTER_OTLP_ENDPOINT;if(r)return Xe(r,t);let i=$e(e);return i?Xe(i,t):void 0}function nt(e,t,n){let r=t===`traces`?e.BROWSE_TOOL_OTEL_BROWSER_TRACES_ENDPOINT:e.BROWSE_TOOL_OTEL_BROWSER_LOGS_ENDPOINT;if(r)return et(r,n);let i=e.BROWSE_TOOL_OTEL_BROWSER_ENDPOINT;if(i)return et(Xe(i,t),n);let a=tt(e,t);return a?et(a,n):void 0}function rt(e,t){let n=e.BROWSE_TOOL_OTEL_BROWSER_SERVICE_NAME??`${e.OTEL_SERVICE_NAME??Ve}-extension`,r=nt(e,`traces`,t),i=nt(e,`logs`,t);return{enabled:!!(r||i),tracesEndpoint:r,logsEndpoint:i,serviceName:n}}function it(e,t){let n=t===`traces`?e.OTEL_EXPORTER_OTLP_TRACES_HEADERS:e.OTEL_EXPORTER_OTLP_LOGS_HEADERS,r=t===`traces`?e.OTEL_EXPORTER_OTLP_TRACES_TIMEOUT:e.OTEL_EXPORTER_OTLP_LOGS_TIMEOUT;return{url:tt(e,t),headers:Je(n??e.OTEL_EXPORTER_OTLP_HEADERS),timeoutMillis:Ye(r??e.OTEL_EXPORTER_OTLP_TIMEOUT)}}function at(e){return e instanceof Error?e.message:String(e)}function ot(e){if(e instanceof Error)return qe({"exception.type":e.name,"exception.message":e.message,"exception.stacktrace":e.stack})}let M=class{contextStore=new f.AsyncLocalStorage;tracesEnabled;logsEnabled;tracerProvider;tracer;logSinkReady;constructor(e={}){let t=e.env??process.env,n=Ge(t.OTEL_SDK_DISABLED),r=Ge(t.BROWSE_TOOL_OTEL_ENABLED),i=it(t,`traces`);this.tracesEnabled=!n&&(r||!!i.url),this.logsEnabled=!n;let a=e.serviceName??t.BROWSE_TOOL_OTEL_SERVICE_NAME??t.OTEL_SERVICE_NAME??Ve,o=e.serviceVersion??t.npm_package_version,s={"service.name":a};o&&(s[`service.version`]=o);let c=(0,_.resourceFromAttributes)(s);if(this.tracesEnabled){let t=e.traceExporter??new g.OTLPTraceExporter(i);this.tracerProvider=new v.NodeTracerProvider({resource:c,spanProcessors:[e.traceExporter?new v.SimpleSpanProcessor(t):new v.BatchSpanProcessor(t)]})}this.tracer=this.tracerProvider?.getTracer(a,o)??h.trace.getTracer(a,o),this.logSinkReady=this.logsEnabled?(0,b.createNodeTelemetry)({env:t,serviceName:a,serviceVersion:o,workspaceRoot:Qe(),enableTraces:!1,enableLogs:!0}).catch(()=>null):Promise.resolve(null)}isEnabled(){return this.tracesEnabled||this.logsEnabled}getActiveTraceContext(){let e=this.contextStore.getStore();if(!e)return{};let t=h.trace.getSpan(e);if(!t)return{};let n=t.spanContext();return{traceId:n.traceId,spanId:n.spanId}}async runInSpan(e,t,n){if(!this.tracesEnabled)return await n(void 0);let r=this.contextStore.getStore()??h.context.active(),i=this.tracer.startSpan(e,{kind:t.kind??h.SpanKind.INTERNAL,attributes:qe(t.attributes)},r),a=h.trace.setSpan(r,i);return await this.contextStore.run(a,async()=>{try{return await n(i)}catch(e){throw i.recordException(e instanceof Error?e:Error(at(e))),i.setStatus({code:h.SpanStatusCode.ERROR,message:at(e)}),e}finally{i.end()}})}log(e,t,n={}){this.logsEnabled&&this.logSinkReady.then(r=>{if(!r)return;let i=n.context??this.contextStore.getStore()??h.context.active(),a=ot(n.exception);r.logger[e](t,{attributes:qe({...n.attributes,...a}),context:i,exception:n.exception})})}async forceFlush(){let e=await this.logSinkReady;await Promise.allSettled([this.tracerProvider?.forceFlush(),e?.flush()])}async shutdown(){let e=await this.logSinkReady;await Promise.allSettled([this.tracerProvider?.shutdown(),e?.shutdown()])}};M=j([(0,d.injectable)(),A(`design:paramtypes`,[Object])],M);const N=18e4;function P(e,t){return function(n,r){t(n,r,e)}}let F=class{pendingTasks=new Map;taskQueue=[];lastPollAt;lastResultAt;maxQueueSize=100;defaultTimeoutMs=N;constructor(e,t=new M){this.webSocketHub=e,this.telemetry=t}async queueTask(e,t,n=this.defaultTimeoutMs,r){if(this.pendingTasks.size>=this.maxQueueSize)throw Error(`Task queue full (max ${this.maxQueueSize} tasks)`);let i=r??t.browserId,a={id:crypto.randomUUID(),tool:e,arguments:t,createdAt:new Date,timeoutMs:n,browserId:i,pageId:typeof t.pageId==`string`?t.pageId:void 0,telemetry:this.getTaskTelemetryContext()};return new Promise((e,t)=>{let r=setTimeout(()=>{this.pendingTasks.delete(a.id);let e=this.taskQueue.findIndex(e=>e.id===a.id);e!==-1&&this.taskQueue.splice(e,1),t(Error(`Task ${a.id} timed out after ${n}ms`))},n);if(this.pendingTasks.set(a.id,{task:a,resolve:e,reject:t,timeoutId:r}),this.webSocketHub){let e=i?this.pushTaskViaWebSocket(a,i):!1;if(e||=this.pushTaskToAnyConnection(a),e)return}this.taskQueue.push(a)})}pushTaskToAnyConnection(e){if(!this.webSocketHub)return!1;let t=this.webSocketHub.getStats();if(t.totalConnections===0)return!1;let n=t.connections[0];return n?this.pushTaskViaWebSocket(e,n.browserId):!1}pushTaskViaWebSocket(e,t){if(!this.webSocketHub)return!1;let n={type:`task:push`,id:crypto.randomUUID(),payload:{taskId:e.id,tool:e.tool,arguments:e.arguments,telemetry:e.telemetry}};return this.webSocketHub.pushTask(t,n)}getNextTask(){return this.lastPollAt=new Date,this.taskQueue.shift()}submitResult(e){this.lastResultAt=new Date;let t=this.pendingTasks.get(e.taskId);if(t)return clearTimeout(t.timeoutId),this.pendingTasks.delete(e.taskId),t.resolve(e),t.task}getConnectionStatus(){let e=new Date,t=this.lastPollAt?e.getTime()-this.lastPollAt.getTime()<5e3:!1,n=this.webSocketHub?this.webSocketHub.getStats().totalConnections>0:!1;return{connected:t||n,lastPollAt:this.lastPollAt,lastResultAt:this.lastResultAt,pendingTasks:this.pendingTasks.size}}clearAllTasks(e){for(let[t,n]of this.pendingTasks)clearTimeout(n.timeoutId),n.reject(Error(e)),this.pendingTasks.delete(t);this.taskQueue.length=0}get queueSize(){return this.taskQueue.length}get pendingCount(){return this.pendingTasks.size}getTaskTelemetryContext(){let e=this.telemetry.getActiveTraceContext();if(!(!e.traceId&&!e.spanId))return{traceId:e.traceId,parentSpanId:e.spanId}}};F=j([(0,d.injectable)(),P(0,(0,d.inject)(k.WebSocketHub)),P(0,(0,d.optional)()),P(1,(0,d.inject)(k.TelemetryService)),P(1,(0,d.optional)()),A(`design:paramtypes`,[Object,Object])],F);const st=new Set(`browser_navigate.browser_go_back.browser_go_forward.browser_reload.browser_click.browser_fill.browser_type.browser_upload_file.browser_select.browser_hover.browser_drag.browser_press_key.browser_pdf.browser_screenshot.browser_snapshot.browser_list_pages.browser_new_page.browser_select_page.browser_close_page.browser_wait_for.browser_evaluate_script.browser_resize_page.browser_handle_dialog.browser_emulate.browser_list_network_requests.browser_get_network_request.browser_list_console_messages.browser_expect`.split(`.`)),ct=new Set([`browser_launch`,`browser_list_profiles`,`browser_create_profile`,`browser_delete_profile`,`browser_save_profile_state`,`browser_start_trace`,`browser_stop_trace`,`run_spec`,`discover_specs`]);let I=class{constructor(e){this.taskQueue=e}isToolSupported(e){return st.has(e)}isToolNotApplicable(e){return ct.has(e)}async executeTool(e,t){if(this.isToolNotApplicable(e))return{content:[{type:`text`,text:`Tool "${e}" is not available in Chrome extension mode. This tool requires Playwright and cannot be run through the extension.`}],isError:!0};if(!this.isToolSupported(e))return{content:[{type:`text`,text:`Tool "${e}" is not yet implemented in Chrome extension mode.`}],isError:!0};if(!this.taskQueue.getConnectionStatus().connected)return{content:[{type:`text`,text:`Chrome extension is not connected. Please ensure the extension is running and connected to the server.`}],isError:!0};try{let n=await this.taskQueue.queueTask(e,t);return n.success?n.result?n.result:{content:[{type:`text`,text:`Tool executed successfully`}]}:{content:[{type:`text`,text:n.error||n.result?.content?.[0]?.text||`Unknown error from Chrome extension`}],isError:!0}}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}}getSupportedTools(){return Array.from(st)}getNotApplicableTools(){return Array.from(ct)}};I=j([(0,d.injectable)(),P(0,(0,d.inject)(k.ExtensionTaskQueue)),A(`design:paramtypes`,[Object])],I);const lt={width:1920,height:1080};let ut=class{sessions=new Map;sessionIdCounter=0;constructor(e,t,n,r,i,a){this.browserService=e,this.specRunner=t,this.specMetadataService=n,this.setupRunner=r,this.webServerManager=i,this.pageRegistry=a}async runSpec(e){let{specPath:t,automationId:n,keepBrowserOpen:r=!1,browserOptions:i={},recordVideo:a,browserId:o,pageId:s,windowBounds:c,hooksPath:l}=e,u=n??`spec-${++this.sessionIdCounter}`,d={id:u,scriptPath:t,status:`pending`,pageIds:[],browserId:null,error:null,createdAt:new Date,updatedAt:new Date};this.sessions.set(u,d);try{let e,n,f,p=!1;if(o&&s){let t=this.pageRegistry.get(s);if(!t)throw Error(`Page with ID ${s} not found`);if(!t.page||!t.context||!t.browser)throw Error(`Page entry is missing required Playwright instances`);e=t.page,n=t.context,f=t.browser,d.browserId=o,d.pageIds.push(s),p=!0}else{let t=await this.browserService.launch({...i,recordVideo:a,onPageClose:e=>{let t=d.pageIds.indexOf(e);t>=0&&d.pageIds.splice(t,1)}});d.browserId=t.browserInstance.id,d.pageIds.push(t.pageId),t.browserInstance.specOrigin=!0;let{context:r,browser:o}=t.browserInstance;if(!r||!o)throw Error(`Browser context or browser is not available`);e=t.page,n=r,f=o}d.status=`running`,d.updatedAt=new Date,c&&await this.applyWindowBounds(f,c);let m=await this.specRunner.executeSpec({specPath:t,sessionId:u,page:e,context:n,browser:f,hooksPath:l,baseURL:i.baseURL});return d.status=`completed`,d.updatedAt=new Date,!r&&!p&&d.browserId&&d.browserId&&await this.browserService.closeBrowser(d.browserId),{automationId:u,status:`completed`,pageIds:r||p?[...d.pageIds]:[],browserId:r||p?d.browserId:null,specResult:m}}catch(e){d.status=`failed`,d.error=e instanceof Error?e.message:String(e),d.updatedAt=new Date;let t=!!(o&&s);return!r&&!t&&d.browserId&&await this.browserService.closeBrowser(d.browserId),{automationId:u,status:`failed`,pageIds:r||t?[...d.pageIds]:[],browserId:r||t?d.browserId:null}}}async runSpecEnhanced(e){let{specPath:t,automationId:n,keepBrowserOpen:r=!1,browserOptions:i={},recordVideo:a,testFilter:o,specArgs:s,configPath:c,runSetup:l=!1,startServer:u=!1,stopServerAfter:d=!0,browserId:f,pageId:p,windowBounds:h,hooksPath:g}=e,_=n??`spec-${++this.sessionIdCounter}`,v={id:_,scriptPath:t,status:`pending`,pageIds:[],browserId:null,error:null,createdAt:new Date,updatedAt:new Date};this.sessions.set(_,v);let y,b;try{let e=c?await this.specMetadataService.loadPlaywrightConfig(c):null,n=c?(0,m.dirname)(c):process.cwd();u&&e?.webServer&&(y=await this.webServerManager.startServer(e.webServer,n));let x,S,C,w=!1;if(f&&p){let e=this.pageRegistry.get(p);if(!e)throw Error(`Page with ID ${p} not found`);if(!e.page||!e.context||!e.browser)throw Error(`Page entry is missing required Playwright instances`);x=e.page,S=e.context,C=e.browser,v.browserId=f,v.pageIds.push(p),w=!0}else{let e=await this.browserService.launch({...i,recordVideo:a,onPageClose:e=>{let t=v.pageIds.indexOf(e);t>=0&&v.pageIds.splice(t,1)}});v.browserId=e.browserInstance.id,v.pageIds.push(e.pageId),e.browserInstance.specOrigin=!0;let{context:t,browser:n}=e.browserInstance;if(!t)throw Error(`Browser context is not available`);if(!n)throw Error(`Browser instance is not available`);x=e.page,S=t,C=n}if(v.status=`running`,v.updatedAt=new Date,h&&await this.applyWindowBounds(C,h),l&&e?.setupFile){let t=e.setupFile.startsWith(`/`)?e.setupFile:`${n}/${e.setupFile}`,r=e.setupExport??`default`;if(b=await this.setupRunner.runSetup(t,r,{browser:C,context:S,page:x}),!b.success)throw Error(b.error??`Setup failed`)}let T=await this.specRunner.executeSpecEnhanced({specPath:t,sessionId:_,page:x,context:S,browser:C,testFilter:o,specArgs:{...s,...b?.state},hooksPath:g,baseURL:i.baseURL});return v.status=`completed`,v.updatedAt=new Date,d&&y?.started&&await this.webServerManager.stopServer(),!r&&!w&&v.browserId&&await this.browserService.closeBrowser(v.browserId),{automationId:_,status:`completed`,pageIds:r||w?[...v.pageIds]:[],browserId:r||w?v.browserId:null,specResult:T,serverResult:y,setupResult:b}}catch(e){v.status=`failed`,v.error=e instanceof Error?e.message:String(e),v.updatedAt=new Date,d&&y?.started&&await this.webServerManager.stopServer();let t=!!(f&&p);return!r&&!t&&v.browserId&&await this.browserService.closeBrowser(v.browserId),{automationId:_,status:`failed`,pageIds:r||t?[...v.pageIds]:[],browserId:r||t?v.browserId:null,serverResult:y,setupResult:b}}}getSession(e){return this.sessions.get(e)}listSessions(){return Array.from(this.sessions.values())}async stop(e){let t=this.sessions.get(e);return t?(t.browserId&&await this.browserService.closeBrowser(t.browserId),t.status=`completed`,t.updatedAt=new Date,!0):!1}async applyWindowBounds(e,t){let n=this.resolveWindowBounds(t),r=e.contexts();if(r.length===0)return;let i=r[0].pages();if(i.length===0)return;let a;try{a=await i[0].context().newCDPSession(i[0]);let{windowId:e}=await a.send(`Browser.getWindowForTarget`);await a.send(`Browser.setWindowBounds`,{windowId:e,bounds:{left:n.x,top:n.y,width:n.width,height:n.height}})}finally{a&&await a.detach()}}resolveWindowBounds(e){let t=e.screenDimensions??lt;if(e.preset){let n=this.calculatePresetBounds(e.preset,t);return{x:e.x??n.x,y:e.y??n.y,width:e.width??n.width,height:e.height??n.height}}return{x:e.x??0,y:e.y??0,width:e.width??t.width,height:e.height??t.height}}calculatePresetBounds(e,t){let n=Math.floor(t.width/2),r=Math.floor(t.height/2);switch(e){case`right-half`:return{x:n,y:0,width:n,height:t.height};case`left-half`:return{x:0,y:0,width:n,height:t.height};case`top-half`:return{x:0,y:0,width:t.width,height:r};case`bottom-half`:return{x:0,y:r,width:t.width,height:r};case`center`:{let e=Math.floor(t.width*.75),n=Math.floor(t.height*.75);return{x:Math.floor((t.width-e)/2),y:Math.floor((t.height-n)/2),width:e,height:n}}case`fullscreen`:return{x:0,y:0,width:t.width,height:t.height};default:return{x:0,y:0,width:t.width,height:t.height}}}};ut=j([(0,d.injectable)(),P(0,(0,d.inject)(k.BrowserService)),P(1,(0,d.inject)(k.SpecRunner)),P(2,(0,d.inject)(k.SpecMetadataService)),P(3,(0,d.inject)(k.SetupRunner)),P(4,(0,d.inject)(k.WebServerManager)),P(5,(0,d.inject)(k.PageRegistry)),A(`design:paramtypes`,[Object,Object,Object,Object,Object,Object])],ut);var dt=class extends Error{constructor(e,t,n){super(e),this.pid=t,this.userDataDir=n,this.name=`BrowserSessionConflictError`}};let ft=class{platform=x.default.platform();async checkLock(e){let t={isLocked:!1};return this.platform===`win32`?this.checkWindowsLock(e,t):this.checkUnixLock(e,t)}async cleanupOrphanedLocks(e){let t=await this.checkLock(e);if(!t.isLocked)return!0;if(t.isProcessAlive)return!1;let n=[m.default.join(e,`SingletonLock`),m.default.join(e,`SingletonCookie`),m.default.join(e,`SingletonSocket`),m.default.join(e,`lockfile`)];for(let e of n)try{p.default.existsSync(e)&&await(0,w.unlink)(e)}catch{}let r=m.default.join(e,`Default`,`LOCK`);try{p.default.existsSync(r)&&await(0,w.unlink)(r)}catch{}return!0}async ensureAvailable(e){if(!p.default.existsSync(e))return;let t=await this.checkLock(e);if(t.isLocked){if(t.isProcessAlive)throw new dt(`Browser session conflict: Another Chrome process (PID: ${t.pid}) is using this profile.\nUser data directory: ${e}\n\nTo resolve:\n1. Close the existing browser session manually\n2. Or use a different profile name\n3. Or kill the process: kill ${t.pid}`,t.pid,e);if(!await this.cleanupOrphanedLocks(e))throw Error(`Failed to clean up orphaned browser lock in ${e}`)}}async checkUnixLock(e,t){let n=m.default.join(e,`SingletonLock`),r=m.default.join(e,`SingletonSocket`);if(t.lockFilePath=n,t.socketPath=r,this.symlinkExists(n))try{let e=p.default.readlinkSync(n).match(/-(\d+)$/);e&&(t.isLocked=!0,t.pid=Number.parseInt(e[1],10),t.isProcessAlive=this.isProcessRunning(t.pid))}catch{t.isLocked=!0,t.isProcessAlive=p.default.existsSync(r)}return!t.isLocked&&p.default.existsSync(r)&&(t.isLocked=!0,t.isProcessAlive=!0),t}symlinkExists(e){try{return p.default.lstatSync(e).isSymbolicLink()}catch{return!1}}async checkWindowsLock(e,t){let n=m.default.join(e,`lockfile`);if(t.lockFilePath=n,p.default.existsSync(n))try{let e=await(0,w.readFile)(n,`utf-8`),r=Number.parseInt(e.trim(),10);Number.isNaN(r)||(t.isLocked=!0,t.pid=r,t.isProcessAlive=this.isProcessRunning(r))}catch{t.isLocked=!0,t.isProcessAlive=!0}return t}isProcessRunning(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}};ft=j([(0,d.injectable)()],ft);var pt=`147.0.7727.3`,mt=`browse-tool/chrome-for-testing:147.0.7727.3`,ht=`/usr/local/bin/google-chrome-for-testing`,gt=`linux/amd64`,_t;const vt=pt,yt=`BROWSE_TOOL_CHROME_FOR_TESTING_VERSION`,bt=`147.0.7727.3`;function xt(e,t){let n=e.split(`.`).map(e=>Number.parseInt(e,10)||0),r=t.split(`.`).map(e=>Number.parseInt(e,10)||0),i=Math.max(n.length,r.length);for(let e=0;e<i;e+=1){let t=n[e]??0,i=r[e]??0;if(t!==i)return t>i?1:-1}return 0}function St(){let e=process.env.BROWSE_TOOL_CHROME_FOR_TESTING_VERSION?.trim();return e&&e.length>0?e:vt}function Ct(e){return xt(e,`147.0.7727.3`)>=0}function wt(){return Ct(St())}let Tt=class{static{_t=this}static API_URL=`https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json`;cacheDir;constructor(){this.cacheDir=(0,m.join)((0,x.homedir)(),`.cache`,`chrome-for-testing`)}async getExecutablePath(){let e=this.getExpectedExecutablePath(),t=await this.getInstalledVersion();try{let n=this.getRequestedVersion(),r=await this.fetchVersionInfo(n);return(0,p.existsSync)(e)&&t===n?e:this.download(r)}catch(t){if((0,p.existsSync)(e))return e;throw t}}async isInstalled(){return(0,p.existsSync)(this.getExpectedExecutablePath())}async getInstalledVersion(){let e=(0,m.join)(this.cacheDir,`version.txt`);if(!(0,p.existsSync)(e))return null;try{return(await(0,w.readFile)(e,`utf-8`)).trim()}catch{return null}}async update(){let e=(0,m.join)(this.cacheDir,`chrome`);return(0,p.existsSync)(e)&&await(0,w.rm)(e,{recursive:!0,force:!0}),this.download(await this.fetchVersionInfo(this.getRequestedVersion()))}async download(e){(0,p.mkdirSync)(this.cacheDir,{recursive:!0});let t=this.getDownloadUrl(e);if(!t)throw Error(`No Chrome for Testing download available for ${this.getPlatformKey()}`);let n=(0,m.join)(this.cacheDir,`chrome.zip`),r=(0,m.join)(this.cacheDir,`chrome`);await this.downloadFile(t,n),await this.extractZip(n,r),await(0,w.rm)(n,{force:!0}),await(0,w.writeFile)((0,m.join)(this.cacheDir,`version.txt`),e.version,`utf-8`);let i=this.getExpectedExecutablePath();if(!(0,p.existsSync)(i))throw Error(`Chrome for Testing executable not found at expected path: ${i}`);return(0,x.platform)()!==`win32`&&await(0,w.chmod)(i,493),i}async fetchVersionInfo(e){let t=await fetch(_t.API_URL);if(!t.ok)throw Error(`Failed to fetch Chrome for Testing info: ${t.statusText}`);let n=(await t.json()).versions.find(t=>t.version===e);if(!n)throw Error(`Chrome for Testing version ${e} not found in feed`);return n}getRequestedVersion(){return St()}getDownloadUrl(e){let t=this.getPlatformKey();return e.downloads.chrome.find(e=>e.platform===t)?.url}getPlatformKey(){let e=(0,x.platform)(),t=(0,x.arch)();if(e===`darwin`)return t===`arm64`?`mac-arm64`:`mac-x64`;if(e===`linux`)return`linux64`;if(e===`win32`)return t===`x64`?`win64`:`win32`;throw Error(`Unsupported platform: ${e}`)}getExpectedExecutablePath(){let e=(0,x.platform)(),t=(0,m.join)(this.cacheDir,`chrome`);if(e===`darwin`)return(0,m.join)(t,`chrome-mac-${(0,x.arch)()===`arm64`?`arm64`:`x64`}`,`Google Chrome for Testing.app`,`Contents`,`MacOS`,`Google Chrome for Testing`);if(e===`linux`)return(0,m.join)(t,`chrome-linux64`,`chrome`);if(e===`win32`)return(0,m.join)(t,`chrome-win${(0,x.arch)()===`x64`?`64`:`32`}`,`chrome.exe`);throw Error(`Unsupported platform: ${e}`)}async downloadFile(e,t){let n=await fetch(e);if(!n.ok||!n.body)throw Error(`Failed to download: ${n.statusText}`);let r=`${t}.tmp`,i=(0,p.createWriteStream)(r),a=n.body.getReader();await(0,te.pipeline)(new ee.Readable({async read(){let{done:e,value:t}=await a.read();e?this.push(null):this.push(Buffer.from(t))}}),i),await(0,w.rename)(r,t)}async extractZip(e,t){let n=(0,x.platform)();return new Promise((r,i)=>{let a;n===`win32`?a=(0,T.spawn)(`powershell`,[`-NoProfile`,`-Command`,`Expand-Archive -Path "${e}" -DestinationPath "${t}" -Force`]):((0,p.mkdirSync)(t,{recursive:!0}),a=(0,T.spawn)(`unzip`,[`-o`,`-q`,e,`-d`,t])),a.on(`close`,e=>{e===0?r():i(Error(`Failed to extract zip (exit code: ${e})`))}),a.on(`error`,e=>{i(Error(`Failed to spawn extraction process: ${e.message}`))})})}};Tt=_t=j([(0,d.injectable)(),A(`design:paramtypes`,[])],Tt);const Et=[`pnpm-workspace.yaml`,`nx.json`,`.git`],Dt=mt,Ot=gt,kt=Dt.split(`:`)[0]??Dt,At=`@agimon-ai/browse-tool`;function jt(e=process.cwd()){let t=m.default.resolve(e);for(;;){for(let e of Et)if(Mt(m.default.join(t,e)))return t;let n=m.default.dirname(t);if(n===t)return e;t=n}}function Mt(e){return p.default.existsSync(e)}function Nt(){return kt}function Pt(e){return`${Nt()}:${e}`}function Ft(e){let t=m.default.resolve(e);for(let e=0;e<8;e+=1){let e=m.default.join(t,`package.json`);if(Mt(e))try{if(JSON.parse(p.default.readFileSync(e,`utf8`)).name===`@agimon-ai/browse-tool`)return t}catch{}let n=m.default.dirname(t);if(n===t)break;t=n}return m.default.resolve(e,`../..`)}function It(){let e=m.default.dirname((0,E.fileURLToPath)(require(`url`).pathToFileURL(__filename).href));return m.default.join(Ft(e),`docker/chrome-for-testing.Dockerfile`)}function Lt(){return jt(Ft(m.default.dirname((0,E.fileURLToPath)(require(`url`).pathToFileURL(__filename).href))))}function Rt(e){if(!e?.includes(`:`))return;let[,t]=e.split(`:`,2),n=t?.trim();if(!(!n||!/^\d+\.\d+\.\d+\.\d+$/.test(n)))return n}function zt(e){return(e?.trim()||Ot).toLowerCase()}function Bt(e){let t=zt(e);return t.includes(`arm64`)||t.includes(`aarch64`)?`linux-arm64`:`linux64`}function Vt(e){return e.startsWith(`${Nt()}:`)}async function Ht(e,t){return await new Promise((n,r)=>{let i=``,a=(0,T.spawn)(`docker`,e,{stdio:t===`pipe`?[`ignore`,`pipe`,`pipe`]:[`ignore`,t,t]});t===`pipe`&&a.stderr?.on(`data`,e=>{i+=e.toString(`utf8`)}),a.once(`error`,r),a.once(`close`,e=>{n({exitCode:e??1,stderr:i})})})}async function Ut(e){return(await Ht([`image`,`inspect`,e],`ignore`)).exitCode===0}async function Wt(e={}){let t=e.version?.trim()||Rt(e.image)||St(),n=e.image?.trim()||Pt(t),r=zt(e.platform),i=Bt(r),a=e.stdio??`inherit`,o=await Ht([`buildx`,`build`,`--platform`,r,`--load`,`-t`,n,`--build-arg`,`CFT_VERSION=${t}`,`--build-arg`,`CFT_ARCHIVE_PLATFORM=${i}`,`-f`,It(),Lt()],a);if(o.exitCode!==0){let e=o.stderr.trim();throw Error(e?`Failed to build Docker image ${n}: ${e}`:`Failed to build Docker image ${n}`)}return{image:n,version:t,platform:r}}async function Gt(e){return!Vt(e.image)||await Ut(e.image)?!1:(await Wt({image:e.image,platform:e.platform,stdio:`inherit`}),!0)}function Kt(){let e=new Map,t=(0,T.execSync)(`ps -axo pid=,ppid=`,{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:3e3});for(let n of t.split(`
2
+ `)){let[t,r]=n.trim().split(/\s+/,2);if(!t||!r)continue;let i=Number(t),a=Number(r);if(Number.isNaN(i)||Number.isNaN(a))continue;let o=e.get(a);o?o.push(i):e.set(a,[i])}return e}function qt(e){let t=[];try{let n;try{n=(0,T.execSync)(`pgrep -P ${e}`,{encoding:`utf-8`,stdio:[`ignore`,`pipe`,`ignore`],timeout:3e3}).trim().split(`
3
+ `).filter(Boolean).map(Number).filter(e=>!Number.isNaN(e))}catch{n=Kt().get(e)??[]}for(let e of n)t.push(...qt(e)),t.push(e)}catch{}return t}function Jt(e){try{return process.kill(e,0),!0}catch{return!1}}async function Yt(e,t=3e3){if(!Jt(e))return;let n=[...qt(e),e];for(let e of n)try{process.kill(e,`SIGTERM`)}catch{}let r=Date.now()+t;for(;Date.now()<r;){if(!n.some(Jt))return;await new Promise(e=>setTimeout(e,100))}for(let e of n)try{Jt(e)&&process.kill(e,`SIGKILL`)}catch{}}function Xt(e,t){let n=m.default.join(x.default.tmpdir(),`proxy-auth-ext-${Date.now()}-${Math.random().toString(36).slice(2,8)}`);p.default.mkdirSync(n,{recursive:!0});let r={manifest_version:3,name:`Proxy Auth Helper`,version:`1.0.0`,permissions:[`webRequest`,`webRequestAuthProvider`],host_permissions:[`<all_urls>`],background:{service_worker:`background.js`}},i=[`chrome.webRequest.onAuthRequired.addListener(`,` (details) => ({ authCredentials: { username: ${JSON.stringify(e)}, password: ${JSON.stringify(t)} } }),`,` { urls: ["<all_urls>"] },`,` ["blocking"]`,`);`,``].join(`
4
+ `);return p.default.writeFileSync(m.default.join(n,`manifest.json`),JSON.stringify(r,null,2)),p.default.writeFileSync(m.default.join(n,`background.js`),i),n}function Zt(e){let t=[`--proxy-server=${e.server}`];return e.bypass&&t.push(`--proxy-bypass-list=${e.bypass}`),t}var L;const Qt=new Set([`docker`,`docker-vm`,`docker-chromium`,`docker-chrome-testing`]),$t=mt,en=ht,tn=`/vm/extensions/playwright`,nn=`/vm/user-data`,rn=`2g`,an=`/tmp/runtime-seluser`,on=`1920,1080`,sn=`1920x1080x24`,cn=5e3,ln=5e3,un=12e3,dn=8e3,fn=1500,pn=100,mn=32*1024,hn=3,gn=250,_n=250,vn=1500,yn=4e3,bn=100,R=process.env.BROWSE_TOOL_DEBUG_EXTENSION_RECORDING===`1`,xn=[`Current Session`,`Current Tabs`,`Last Session`,`Last Tabs`,`Sessions`],Sn=new Set([`Default`,`Guest Profile`,`System Profile`]);let Cn=class{static{L=this}static MAX_ACTIVE_BROWSERS=15;static MAX_PAGES_PER_BROWSER=15;static chromeForTestingLaunchQueue=Promise.resolve();browsers=new Map;closingExtensionRecordings=new Map;profileToBrowserId=new Map;browserIdCounter=0;constructor(e,t,n,r,i,a,o,s){this.profileService=e,this.pageRegistry=t,this.lockManager=n,this.chromeForTesting=r,this.pageMonitor=i,this.webSocketHub=a,this.extensionSessionRegistry=o,this.extensionTaskQueue=s}getBrowserByProfile(e){let t=this.profileToBrowserId.get(e);if(t){let n=this.browsers.get(t);if(n){if(this.isBrowserAlive(n))return n;this.cleanupStaleBrowser(t,e)}else this.profileToBrowserId.delete(e)}}async launch(e={}){let{profileName:t,browserType:n=`chromium`,headless:r=!0,onPageClose:i,baseURL:a,recordVideo:o,proxy:s,browserId:c}=e;if(t){let e=this.getBrowserByProfile(t);if(e){let{pageId:t,page:n}=await this.newPage(e.id,i);return{browserInstance:e,pageId:t,page:n}}}await this.enforceMaxBrowserLimit();let l=c||(t?`browser-${t}`:`browser-${++this.browserIdCounter}`);if(c&&this.browsers.has(c))throw Error(`Browser ID "${c}" is already in use`);let u=this.getBrowserType(n),d=t?await this.profileService.get(t):null;t&&!d&&(d=await this.profileService.create({name:t,browserType:n}));let f=s?{proxy:{server:s.server,username:s.username,password:s.password,bypass:s.bypass}}:{},p;if(!r&&n===`chromium`)try{p=await u.launch({headless:r,channel:`chrome`,...f})}catch{p=await u.launch({headless:r,...f})}else p=await u.launch({headless:r,...f});let m=this.buildContextOptions(d,a,o);if(d&&t){let e=await this.profileService.loadStorageState(t);e&&(m.storageState=e)}let h=await p.newContext(m),g=await h.newPage(),_=new Date,v={id:l,mode:`playwright`,browser:p,context:h,profileName:t,pageIds:new Set,currentPageId:null,createdAt:_,lastAccessedAt:_};this.browsers.set(l,v),p.on(`disconnected`,()=>{this.cleanupStaleBrowser(l,t)}),t&&this.profileToBrowserId.set(t,l);let y=await this.pageRegistry.register({page:g,browser:p,context:h,browserId:l,profileName:t,onClose:e=>{if(v.pageIds.delete(e),v.currentPageId===e){let e=Array.from(v.pageIds);v.currentPageId=e.length>0?e[0]:null}i?.(e),v.pageIds.size===0&&this.closeBrowser(l).catch(()=>{})}});return this.pageMonitor?.startMonitoring(y,g),v.pageIds.add(y),v.currentPageId=y,{browserInstance:v,pageId:y,page:g}}async launchWithExtension(e={}){let{profileName:t,command:n,commandArgs:r=[],browserId:i,mode:a=`extension`}=e;if(t){let e=this.getBrowserByProfile(t);if(e)if(!this.canReuseExtensionBrowser(e))await this.closeBrowser(e.id).catch(()=>{this.cleanupStaleBrowser(e.id,t)});else{let t=this.getTrackedExtensionPageId(e);return this.recordBrowserActivity(e.id,t),{browserInstance:e,pageId:t,process:{pid:e.pid}}}}await this.enforceMaxBrowserLimit();let o=this.resolveExtensionPath(e.extensionPath),s=m.default.join(o,`manifest.json`);if(!p.default.existsSync(s))throw Error(`Extension manifest not found at ${s}. Please build the extension first: pnpm build:extension`);let c=i||(t?`browser-${t}`:`browser-${++this.browserIdCounter}`);if(i&&this.browsers.has(i))throw Error(`Browser ID "${i}" is already in use`);t&&(await this.profileService.get(t)||await this.profileService.create({name:t,browserType:`chromium`}));let l=this.createUserDataDir(t);l&&await this.lockManager.ensureAvailable(l);let u=await this.resolveVmRuntime({command:n,launchMode:a,useChromeForTesting:e.useChromeForTesting??a===`vm`,extensionHostPath:o,requestedRuntimeExtensionPath:e.extensionPath,userDataDir:l});if(u.kind===`docker`)try{this.ensureDockerWritableUserDataDir(l)}catch(e){let t=e instanceof Error?e.message:String(e);throw Error(`Failed to prepare Docker user-data directory "${l}": ${t}`,{cause:e})}let d=[u.extensionPath],f=[];if(u.kind===`docker`&&f.push(...this.createDockerVolumeArgs(o,u.extensionPath,!0)),e.proxy?.username&&e.proxy?.password){let t=Xt(e.proxy.username,e.proxy.password);if(u.kind===`docker`){let e=`${u.docker.extensionPathInContainer}-proxy-auth-${Date.now()}`;d.push(e),f.push(...this.createDockerVolumeArgs(t,e,!0))}else d.push(t)}let h=d.join(`,`),g=process.env.BROWSE_TOOL_AUTO_SELECT_TAB_CAPTURE_SOURCE_TITLE?.trim(),_=process.env.BROWSE_TOOL_AUTO_SELECT_DESKTOP_CAPTURE_SOURCE?.trim(),v=process.env.BROWSE_TOOL_USE_FAKE_UI_FOR_MEDIA_STREAM===`1`,y=[`--user-data-dir=${u.userDataDir}`,`--load-extension=${h}`,`--disable-extensions-except=${h}`,`--enable-extensions`,`--auto-accept-this-tab-capture`,...v?[`--use-fake-ui-for-media-stream`]:[],...g?[`--auto-select-tab-capture-source-by-title=${g}`]:[],..._?[`--auto-select-desktop-capture-source=${_}`]:[],`--disable-blink-features=AutomationControlled`,`--disable-infobars`,`--no-first-run`,`--no-default-browser-check`,`--disable-background-timer-throttling`,`--disable-backgrounding-occluded-windows`,`--disable-renderer-backgrounding`,`--disable-component-update`,`--disable-features=TranslateUI`,`--disable-ipc-flooding-protection`,`--password-store=basic`,`--use-mock-keychain`,`--disable-dev-shm-usage`,...u.kind===`docker`?[`--no-sandbox`]:[],`--window-size=1920,1080`,...e.proxy?Zt(e.proxy):[],e.url??`about:blank`],b=e=>{try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`||t.protocol===`file:`}catch{return!1}},x=e=>{if(!b(e))return e;try{let t=new URL(e),n=t.pathname.endsWith(`/`)&&t.pathname!==`/`?t.pathname.slice(0,-1):t.pathname;return`${t.protocol}//${t.host}${n}${t.search}`}catch{return e}},S=x(e.url??`about:blank`),C=a===`vm`&&r.length>0?[...y,...r.filter(e=>b(e)?x(e)!==S:!0)]:r.length>0?r:y,w=u.kind===`docker`?[...this.buildDockerSpawnArgs(u.docker,l,f,e.dockerRunArgs,e.dockerEnv,e.dockerEnableVnc),...C]:C,T,E=0,D;for(let n=1;n<=3;n+=1)try{let n=()=>this.startExtensionBrowser({browserId:c,launchMode:a,profileName:t,vmRuntime:u,spawnArgs:w,recordVideo:e.recordVideo,startupDelayMs:e.startupDelayMs,launchUrl:e.url});return this.shouldSerializeChromeForTestingLaunch(u)?await this.runSerializedChromeForTestingLaunch(n):await n()}catch(e){if(T=e instanceof Error?e:Error(String(e)),!this.isRetryableExtensionLaunchError(T)||n===3){if(u.kind===`docker`&&(E>0||D)){let e=[E>0?`Docker retry cleanup attempts: ${E}.`:``,D?`Last Docker retry cleanup: ${D}.`:``].filter(Boolean).join(` `);T.message=`${T.message} ${e}`.trim()}throw T}u.kind===`docker`&&(E+=1,D=await this.prepareDockerRetryUserDataDir(l)),await this.delay(250*n)}throw T??Error(`Extension browser launch failed`)}async resolveVmRuntime(e){let{command:t,launchMode:n,useChromeForTesting:r,extensionHostPath:i,requestedRuntimeExtensionPath:a,userDataDir:o}=e;if(n===`vm`&&this.isDockerVmAlias(t)){let e=this.resolveDockerRuntimeExtensionPath(a),t=process.env.PLAYWRIGHT_VM_DOCKER_USER_DATA_DIR||`/vm/user-data`,n=process.env.PLAYWRIGHT_VM_DOCKER_IMAGE||$t,r=process.env.PLAYWRIGHT_VM_DOCKER_PLATFORM||gt;return await Gt({image:n,platform:r}),{kind:`docker`,command:`docker`,extensionPath:e,userDataDir:t,docker:{image:n,browserBinary:process.env.PLAYWRIGHT_VM_DOCKER_BROWSER_BINARY||en,platform:r,extensionPathInContainer:e,userDataDirInContainer:t}}}return{kind:`host`,command:await this.resolveLaunchCommand({command:t,launchMode:n,useChromeForTesting:r}),extensionPath:i,userDataDir:o}}resolveDockerRuntimeExtensionPath(e){return e&&!p.default.existsSync(m.default.join(e,`manifest.json`))?e:process.env.PLAYWRIGHT_VM_DOCKER_EXTENSION_PATH||`/vm/extensions/playwright`}createDockerVolumeArgs(e,t,n){return[`-v`,`${m.default.resolve(e)}:${t}${n?`:ro`:``}`]}ensureDockerWritableUserDataDir(e){p.default.mkdirSync(e,{recursive:!0,mode:511});let t=[e];for(;t.length>0;){let e=t.pop();if(!e)continue;p.default.chmodSync(e,511);let n=p.default.readdirSync(e,{withFileTypes:!0});for(let r of n){let n=m.default.join(e,r.name);p.default.chmodSync(n,r.isDirectory()?511:438),r.isDirectory()&&t.push(n)}}}buildDockerSpawnArgs(e,t,n,r,i,a){let o=[`run`,`--rm`,`--init`,`--shm-size`,process.env.PLAYWRIGHT_VM_DOCKER_SHM_SIZE||`2g`];return e.platform&&o.push(`--platform`,e.platform),process.env.PLAYWRIGHT_VM_DOCKER_NETWORK&&o.push(`--network`,process.env.PLAYWRIGHT_VM_DOCKER_NETWORK),process.platform===`linux`&&o.push(`--add-host`,`host.docker.internal:host-gateway`),o.push(...n),o.push(...this.createDockerVolumeArgs(t,e.userDataDirInContainer,!1)),o.push(...this.createDockerEnvArgs(i)),o.push(...this.parseDockerRunArgs(process.env.PLAYWRIGHT_VM_DOCKER_RUN_ARGS)),o.push(...r??[]),a?(o.push(`--entrypoint`,`/bin/bash`,e.image,`-lc`,this.buildDockerBrowserLaunchScript(e.browserBinary,{enableVnc:!0}),`_`),o):(o.push(`--entrypoint`,`/bin/bash`,e.image,`-lc`,this.buildDockerBrowserLaunchScript(e.browserBinary,{enableVnc:!1}),`_`),o)}buildDockerBrowserLaunchScript(e,t){let n=[`set -euo pipefail`,`export XDG_RUNTIME_DIR="/tmp/runtime-seluser"`,`mkdir -p "$XDG_RUNTIME_DIR" "$XDG_RUNTIME_DIR/pulse"`,`chmod 700 "$XDG_RUNTIME_DIR" || true`,`export DBUS_SESSION_BUS_ADDRESS="$(dbus-daemon --session --fork --print-address --nopidfile)"`,`pulseaudio --check >/dev/null 2>&1 || pulseaudio --daemonize=yes --exit-idle-time=-1 --disable-shm=true --log-target=stderr >/tmp/pulseaudio.log 2>&1`,`export PULSE_SERVER="unix:$XDG_RUNTIME_DIR/pulse/native"`,`Xvfb :99 -screen 0 1920x1080x24 -nolisten tcp >/tmp/xvfb.log 2>&1 &`,`for i in $(seq 1 30); do xdpyinfo -display :99 >/dev/null 2>&1 && break; sleep 0.2; done`,`export DISPLAY=:99`,`BROWSER_BIN=${JSON.stringify(e)}`,`exec "$BROWSER_BIN" "$@"`];return t.enableVnc&&n.splice(n.length-2,0,'if [ -n "${SE_VNC_PASSWORD:-}" ]; then',' x11vnc -storepasswd "${SE_VNC_PASSWORD}" /tmp/vnc-passwd >/dev/null 2>&1',` X11VNC_AUTH="-rfbauth /tmp/vnc-passwd"`,`else`,` X11VNC_AUTH=""`,`fi`,'x11vnc -forever -shared -rfbport "${SE_VNC_PORT:-5900}" -display :99 $X11VNC_AUTH >/tmp/x11vnc.log 2>&1 &',`if command -v websockify >/dev/null 2>&1; then`,' websockify --web /opt/bin/noVNC "${SE_NO_VNC_PORT:-7900}" "localhost:${SE_VNC_PORT:-5900}" >/tmp/novnc.log 2>&1 &',`fi`),n.join(`
5
+ `)}createDockerEnvArgs(e){if(!e)return[];let t=[];for(let[n,r]of Object.entries(e))n&&t.push(`-e`,`${n}=${r}`);return t}parseDockerRunArgs(e){return e?e.split(/\s+/).map(e=>e.trim()).filter(e=>e.length>0):[]}isDockerVmAlias(e){if(!e)return!1;let t=e.trim().toLowerCase();return Qt.has(t)}async resolveLaunchCommand(e){let{command:t,launchMode:n,useChromeForTesting:r}=e;if(n===`vm`&&r){if(!t)return this.findChromeExecutable();if(this.isChromeTestingAlias(t)||this.isGenericChromeAlias(t))return this.chromeForTesting.getExecutablePath()}return t||this.findChromeExecutable()}isChromeTestingAlias(e){let t=e.trim().toLowerCase();return t===`chrome-testing`||t===`chrome-for-testing`||t===`google-chrome-for-testing`||t.endsWith(`google chrome for testing`)||t.endsWith(`google-chrome-for-testing`)||t.endsWith(`chrome-for-testing.exe`)}isGenericChromeAlias(e){let t=e.trim().toLowerCase(),n=m.default.basename(t);return n===`chrome`||n===`google-chrome`||n===`googlechrome`}resolveExtensionPath(e){if(e&&p.default.existsSync(m.default.join(e,`manifest.json`)))return e;let t=m.default.dirname((0,E.fileURLToPath)(require(`url`).pathToFileURL(__filename).href)),n=this.findPackageRoot(t),r=[n?m.default.resolve(n,`dist/extension`):``,m.default.resolve(t,`../dist/extension`),m.default.resolve(t,`../../dist/extension`)].filter(Boolean);for(let e of r)if(p.default.existsSync(m.default.join(e,`manifest.json`)))return e;let i=m.default.resolve(process.cwd(),`dist/extension`);if(p.default.existsSync(m.default.join(i,`manifest.json`)))return i;throw Error(`Chrome extension not found. Build the extension first: pnpm build:extension`)}findPackageRoot(e,t=`@agimon-ai/browse-tool`){let n=e;for(let e=0;e<8;e++){let e=m.default.join(n,`package.json`);if(p.default.existsSync(e))try{if(JSON.parse(p.default.readFileSync(e,`utf8`))?.name===t)return n}catch{}let r=m.default.dirname(n);if(r===n)break;n=r}return null}getExtensionUserDataDir(e){return m.default.join(this.profileService.getProfilesDir(),e,`extension-user-data`)}createUserDataDir(e){if(e){let t=this.getExtensionUserDataDir(e);return p.default.mkdirSync(t,{recursive:!0}),this.cleanupExtensionSessionRestoreArtifacts(t),t}return p.default.mkdtempSync(m.default.join(x.default.tmpdir(),`extension-chrome-`))}cleanupExtensionSessionRestoreArtifacts(e){for(let t of this.getSessionRestoreProfileDirs(e))for(let e of xn)try{p.default.rmSync(m.default.join(t,e),{recursive:!0,force:!0})}catch{}}getSessionRestoreProfileDirs(e){let t=[e],n=(()=>{try{return p.default.readdirSync(e,{withFileTypes:!0})}catch{return null}})();if(!n)return t;for(let r of n)r.isDirectory()&&(Sn.has(r.name)||r.name.startsWith(`Profile `))&&t.push(m.default.join(e,r.name));return t}async findChromeExecutable(){try{return await this.chromeForTesting.getExecutablePath()}catch{}let e=process.platform,t={darwin:[`/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`,`/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary`,`${x.default.homedir()}/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`],linux:[`/usr/bin/google-chrome`,`/usr/bin/google-chrome-stable`,`/usr/bin/chromium`,`/usr/bin/chromium-browser`,`/snap/bin/chromium`],win32:[`${process.env.LOCALAPPDATA}\\Google\\Chrome\\Application\\chrome.exe`,`${process.env.PROGRAMFILES}\\Google\\Chrome\\Application\\chrome.exe`,`${process.env[`PROGRAMFILES(X86)`]}\\Google\\Chrome\\Application\\chrome.exe`]};for(let n of t[e]??[])if(p.default.existsSync(n))return n;throw Error(`Chrome not found. Install Google Chrome or run with Chrome for Testing.`)}async newPage(e,t){let n=this.browsers.get(e);if(!n)throw Error(`Browser "${e}" not found`);if(n.mode===`extension`||n.mode===`vm`)throw Error(`Cannot create new page in extension mode browser. Use extension APIs directly.`);if(!n.context||!n.browser)throw Error(`Browser "${e}" has no Playwright context`);await this.enforceMaxPageLimit(n);let r=await n.context.newPage(),i=await this.pageRegistry.register({page:r,browser:n.browser,context:n.context,browserId:e,profileName:n.profileName,onClose:r=>{if(n.pageIds.delete(r),n.currentPageId===r){let e=Array.from(n.pageIds);n.currentPageId=e.length>0?e[0]:null}t?.(r),n.pageIds.size===0&&this.closeBrowser(e).catch(()=>{})}});return this.pageMonitor?.startMonitoring(i,r),n.pageIds.add(i),{pageId:i,page:r}}getBrowser(e){return this.browsers.get(e)}getDefaultBrowser(){let e=this.listBrowsers();for(let t of e){if(this.isBrowserAlive(t))return t;this.cleanupStaleBrowser(t.id,t.profileName)}}async getOrCreateDefaultBrowser(e){return this.getDefaultBrowser()||(await this.launch(e)).browserInstance}setCurrentPage(e,t){let n=this.browsers.get(e);if(!n)throw Error(`Browser "${e}" not found`);if(!n.pageIds.has(t))throw Error(`Page "${t}" does not belong to browser "${e}"`);n.extensionRecording?.active&&n.extensionRecording.pageId!==t&&console.warn(`[BrowserService] Extension recording for browser "${e}" remains pinned to initial page "${n.extensionRecording.pageId}"`),n.currentPageId=t}async closeBrowser(e){let t=this.browsers.get(e);if(t){let n,r=t.extensionRecording,i=r?.outputPath,a=r?.active===!0,o=!1;if(r&&this.closingExtensionRecordings.set(e,r),a)try{if(n=(await this.attemptExtensionRecordingFinalization(e)).error,n&&r&&this.shouldCloseRecordedExtensionPageFirst(t)&&(await this.closeRecordedExtensionPage(t,r),i)){if(!await this.waitForExtensionRecordingArtifact(i))throw Error(`Extension recording for browser "${e}" was not persisted after the recorded tab closed`);r.active=!1,n=void 0}}catch(e){n=e instanceof Error?e:Error(String(e))}else try{await this.finalizeExtensionRecording(e)}catch(e){n=e instanceof Error?e:Error(String(e))}if(t.browser)await t.browser.close();else if(t.context)if(t.pid)try{await Yt(t.pid)}catch{try{let e=t.context.pages();await Promise.all(e.map(e=>e.close().catch(e=>{}))),await t.context.close()}catch{}}else{let e=t.context.pages();await Promise.all(e.map(e=>e.close().catch(e=>{}))),await t.context.close()}else if(t.pid)try{await Yt(t.pid)}catch{}if(i&&r&&!p.default.existsSync(i)){let t=await this.waitForExtensionRecordingArtifactOrChunks(r),a=t.artifactReady;!a&&t.chunkReady&&(a=await this.persistExtensionRecordingArtifact(e)||p.default.existsSync(i)),a?n=void 0:r&&(o=!0)}if(t.profileName&&this.profileToBrowserId.delete(t.profileName),this.browsers.delete(e),o?this.finalizeClosingExtensionRecording(e):this.closingExtensionRecordings.delete(e),n)throw n}}async closeAll(){let e=Array.from(this.browsers.keys());await Promise.all(e.map(e=>this.closeBrowser(e).catch(()=>{}))),this.browsers.clear(),this.profileToBrowserId.clear(),this.pageRegistry.clear()}listBrowsers(){return Array.from(this.browsers.values())}touchBrowser(e){let t=this.browsers.get(e);t&&(t.lastAccessedAt=new Date)}recordBrowserActivity(e,t){let n=this.browsers.get(e);return n?(n.lastAccessedAt=new Date,t&&this.pageRegistry.touchPage(t),!0):!1}registerExtensionBrowser(){let e=`browser-${++this.browserIdCounter}`,t=new Date,n={id:e,mode:`extension`,browser:void 0,context:void 0,pageIds:new Set,currentPageId:null,createdAt:t,lastAccessedAt:t};return this.browsers.set(e,n),e}registerExtensionBrowserWithId(e){if(this.browsers.has(e))return;let t=new Date,n={id:e,mode:`extension`,browser:void 0,context:void 0,pageIds:new Set,currentPageId:null,createdAt:t,lastAccessedAt:t};this.browsers.set(e,n)}async ensureExtensionRecordingActive(e,t){let n=this.browsers.get(e),r=n?.extensionRecording;!n||!r||r.pageId!==t||r.active||(r.startPromise||=this.startExtensionRecording(n,r).finally(()=>{n.extensionRecording===r&&(n.extensionRecording.startPromise=void 0)}),await r.startPromise)}async startPageRecording(e,t,n){let r=this.browsers.get(e);if(!r)throw Error(`Browser "${e}" not found`);if(r.mode!==`extension`&&r.mode!==`vm`)throw Error(`Browser "${e}" does not support extension recording in "${r.mode}" mode`);let i=r.extensionRecording;if(i&&i.pageId!==t){if(i.active)throw Error(`Browser "${e}" is already recording page "${i.pageId}". Stop the current recording before starting another one.`);r.extensionRecording=void 0,i=void 0}let a=n?m.default.resolve(n):i?.outputPath??m.default.join(x.default.tmpdir(),`browse-tool-recordings`,`recording-${this.toSafeRecordingId(e)}-${Date.now()}.webm`);if(!i)this.initializeExtensionRecordingAtPath(r,t,a),i=r.extensionRecording;else if(i.outputPath!==a){if(i.active)throw Error(`Browser "${e}" is already recording to "${i.outputPath}". Stop the current recording before changing output path.`);i.outputPath=a,i.chunkPath=`${a}.part`,this.clearExtensionRecordingChunkState(i)}if(!i)throw Error(`Failed to initialize recording for browser "${e}"`);return await this.ensureExtensionRecordingActive(e,t),{outputPath:i.outputPath}}async finalizeExtensionRecording(e,t){let n=this.browsers.get(e),r=n?.extensionRecording;if(!n||!r||t&&r.pageId!==t||!r.active)return;if(!this.extensionTaskQueue)throw Error(`Extension recording task queue is unavailable for browser "${e}"`);let i=wt();R&&console.log(`[ExtensionRecordingDebug] queue stop browser=${e} page=${r.pageId} active=${r.active} cleanupUi=${i}`);let a;try{a=await this.extensionTaskQueue.queueTask(`browser_stop_recording`,{pageId:r.pageId,cleanupUi:i},N,e)}finally{r.active=!1}R&&console.log(`[ExtensionRecordingDebug] stop result browser=${e} success=${a?.success===!0} isError=${a?.result?.isError===!0}`);let o;try{o=this.parseExtensionRecordingPayload(a)}catch(t){if(await this.persistExtensionRecordingArtifact(e))return;throw t}if(o.videoBase64){p.default.mkdirSync(m.default.dirname(r.outputPath),{recursive:!0}),p.default.writeFileSync(r.outputPath,Buffer.from(o.videoBase64,`base64`)),this.clearExtensionRecordingChunkState(r),r.active=!1;return}if(!await this.persistExtensionRecordingArtifact(e))throw Error(`Extension recording for browser "${e}" stopped without video data`)}async stopPageRecording(e,t,n={}){let r=this.browsers.get(e)?.extensionRecording??this.closingExtensionRecordings.get(e);if(!r)throw Error(`Browser "${e}" has no recording session`);if(t&&r.pageId!==t)throw Error(`Page "${t}" does not match the active recording for browser "${e}"`);this.closingExtensionRecordings.set(e,r);let i;try{i=(await this.attemptExtensionRecordingFinalization(e)).error}catch(e){i=e instanceof Error?e:Error(String(e))}if(!p.default.existsSync(r.outputPath)){let t=await this.waitForExtensionRecordingArtifactOrChunks(r),n=t.artifactReady;if(!n&&t.chunkReady&&(n=await this.persistExtensionRecordingArtifact(e)||p.default.existsSync(r.outputPath)),!n&&i)throw i}if(!p.default.existsSync(r.outputPath))throw Error(`Recording artifact for browser "${e}" was not written to "${r.outputPath}"`);let a=p.default.readFileSync(r.outputPath);return this.closingExtensionRecordings.delete(e),{outputPath:r.outputPath,fileSizeBytes:a.byteLength,...n.includeBase64?{videoBase64:a.toString(`base64`)}:{}}}async persistExtensionRecordingArtifact(e,t){let n=this.getExtensionRecordingSession(e);if(!n)return!1;if(!t&&this.hasPersistedExtensionRecordingArtifact(n))return n.active=!1,this.closingExtensionRecordings.delete(e),!0;if(p.default.mkdirSync(m.default.dirname(n.outputPath),{recursive:!0}),t)p.default.writeFileSync(n.outputPath,Buffer.from(t,`base64`)),this.clearExtensionRecordingChunkState(n);else if(!this.persistExtensionRecordingChunksToArtifact(n))return!1;return n.active=!1,this.closingExtensionRecordings.delete(e),!0}async persistExtensionRecordingChunk(e,t){let n=this.getExtensionRecordingSession(e);if(!n||!t)return null;let r=Buffer.from(t,`base64`);return r.length===0?null:(p.default.mkdirSync(m.default.dirname(n.chunkPath),{recursive:!0}),p.default.appendFileSync(n.chunkPath,r),n.chunkCount+=1,n.chunkBytes+=r.length,{chunkBytes:r.length,totalBytes:n.chunkBytes,chunkCount:n.chunkCount})}async enforceMaxPageLimit(e){if(e.pageIds.size<L.MAX_PAGES_PER_BROWSER)return;let t=this.pageRegistry.findByBrowser(e.id);t.sort((e,t)=>e.createdAt.getTime()-t.createdAt.getTime());let n=t[0];n&&(n.page?await n.page.close():(this.pageRegistry.remove(n.id),e.pageIds.delete(n.id)))}async enforceMaxBrowserLimit(){if(this.browsers.size>=L.MAX_ACTIVE_BROWSERS){let e=Array.from(this.browsers.values());e.sort((e,t)=>e.createdAt.getTime()-t.createdAt.getTime());let t=e[0];t&&await this.closeBrowser(t.id)}}isBrowserAlive(e){try{if(e.mode===`playwright`)return e.browser?.isConnected()??!1;if(e.mode===`extension`||e.mode===`vm`){if(!e.pid||!this.isProcessRunning(e.pid))return!1;if(!e.context)return!0;try{return e.context.pages(),!0}catch{return!1}}return!1}catch{return!1}}isProcessRunning(e){try{return process.kill(e,0),!0}catch(e){return e.code===`EPERM`}}captureProcessOutput(){let e=[],t=0,n=(n,r)=>{if(typeof r!=`string`&&!Buffer.isBuffer(r))return;let i=typeof r==`string`?r:r.toString(`utf8`);if(!i)return;let a=32768-t;if(a<=0)return;let o=Buffer.from(i,`utf8`).subarray(0,a).toString(`utf8`);t+=Buffer.byteLength(o,`utf8`),e.push(`[${n}] ${o}`)};return{attach:e=>{e.stdout?.on(`data`,e=>n(`stdout`,e)),e.stderr?.on(`data`,e=>n(`stderr`,e))},snapshot:()=>e.join(``)}}async startExtensionBrowser(e){let{browserId:t,launchMode:n,profileName:r,vmRuntime:i,spawnArgs:a,recordVideo:o,startupDelayMs:s,launchUrl:c}=e,l=this.captureProcessOutput(),u=(0,T.spawn)(i.command,a,{detached:!1,stdio:[`ignore`,`pipe`,`pipe`],env:i.kind===`docker`?process.env:{...process.env,DISPLAY:process.env.DISPLAY}});if(!u.pid)throw Error(`Failed to start Chrome process`);l.attach(u);let d=new Date,f={id:t,mode:n,browser:void 0,context:void 0,profileName:r,pageIds:new Set,currentPageId:null,pid:u.pid,createdAt:d,lastAccessedAt:d};u.on(`exit`,()=>this.cleanupStaleBrowser(t,r)),u.on(`error`,()=>this.cleanupStaleBrowser(t,r)),this.browsers.set(t,f),r&&this.profileToBrowserId.set(r,t);let p=this.pageRegistry.registerExtensionPage(t);f.pageIds.add(p),f.currentPageId=p;try{if(await this.waitForExtensionReady(t,u,l,{vmRuntimeKind:i.kind,launchUrl:c}),o){R&&console.log(`[ExtensionRecordingDebug] initialize recording browser=${f.id} page=${p} dir=${o.dir}`),this.initializeExtensionRecording(f,p,o);let e=f.extensionRecording;e&&this.startExtensionRecording(f,e).catch(e=>{console.warn(`[BrowserService] Failed to eagerly start extension recording for browser "${f.id}" on page "${p}":`,e)})}}catch(e){throw await this.closeBrowser(t).catch(()=>{}),e}return s&&s>0&&await this.delay(s),{browserInstance:f,pageId:p,process:u}}async waitForExtensionReady(e,t,n,r){if(!this.webSocketHub&&!this.extensionSessionRegistry)return;let i=null,a=null,o;t.once(`exit`,(e,t)=>{i=e,a=t}),t.once(`error`,e=>{o=e});let s=null,c=!1,l=0,u=0,d=null,f=!1,p=Date.now(),m=this.getExtensionStartupTimeoutMs(r.vmRuntimeKind),h=this.getExtensionStartupGraceTimeoutMs(r.vmRuntimeKind),g=this.getExtensionReadyStabilityMs(),_=this.getExtensionStartupPollIntervalMs(),v=p+m;for(;;){let t=Date.now();if(t>=v){if(!f&&o===void 0&&i===null&&a===null){f=!0,v=t+h;continue}break}let n=this.getExtensionReadyState(e);if(n.connected){if(c=!0,n.explicit||(s??=t,d??=t,u=Math.max(u,t-s),t-s>=g))return}else s!==null&&(l+=1,u=Math.max(u,t-s)),s=null;if(o||i!==null||a!==null)break;await new Promise(e=>setTimeout(e,_))}let y=this.getExtensionReadyState(e);if(y.connected&&(y.explicit||s!==null&&Date.now()-s>=g))return;let b=n.snapshot(),x=this.writeLaunchFailureLog(e,b),S=[`Chrome extension browser "${e}" failed to become ready within ${m+(f?h:0)}ms.`,`Ready state requires a stable session for ${g}ms.`,`Observed connection: ${c?`yes`:`no`}.`,c&&d!==null?`First connection observed after ${Math.max(0,d-p)}ms.`:void 0,`Longest stable connection: ${u}ms.`,l>0?`Connection flaps: ${l}.`:void 0,f?`Startup grace applied: ${h}ms.`:void 0,r.launchUrl?`Launch URL: ${r.launchUrl}.`:void 0,o?`Error: ${o.message}`:void 0,i===null?void 0:`Exit code: ${i}`,a?`Signal: ${a}`:void 0,x?`Launch log: ${x}`:void 0].filter(Boolean).join(` `);throw Error(S)}getExtensionStartupTimeoutMs(e){return e===`docker`?12e3:5e3}getExtensionStartupGraceTimeoutMs(e){return e===`docker`?8e3:5e3}getExtensionReadyStabilityMs(){return 1500}getExtensionStartupPollIntervalMs(){return 100}isRetryableExtensionLaunchError(e){return/failed to become ready/i.test(e.message)||/Failed to start Chrome process/i.test(e.message)}shouldSerializeChromeForTestingLaunch(e){return process.platform===`darwin`&&e.kind===`host`&&this.isChromeTestingAlias(e.command)}async runSerializedChromeForTestingLaunch(e){let t,n=L.chromeForTestingLaunchQueue;L.chromeForTestingLaunchQueue=new Promise(e=>{t=e}),await n;try{return await e()}finally{t?.()}}async delay(e){await new Promise(t=>setTimeout(t,e))}getExtensionReadyState(e){return this.extensionSessionRegistry?{connected:!!this.extensionSessionRegistry.getSessionByBrowserId(e),explicit:!0}:{connected:!!this.webSocketHub?.hasConnection(e),explicit:!1}}hasExtensionConnection(e){return this.getExtensionReadyState(e).connected}canReuseExtensionBrowser(e){return e.mode!==`extension`&&e.mode!==`vm`||!e.pid?!1:this.isProcessRunning(e.pid)&&this.hasExtensionConnection(e.id)}getTrackedExtensionPageId(e){let t=e.currentPageId&&this.pageRegistry.get(e.currentPageId)?e.currentPageId:Array.from(e.pageIds).find(e=>this.pageRegistry.get(e));if(t)return e.currentPageId=t,t;let n=this.pageRegistry.registerExtensionPage(e.id);return e.pageIds.add(n),e.currentPageId=n,n}writeLaunchFailureLog(e,t){if(t.trim())try{let n=m.default.join(x.default.tmpdir(),`${e}-launch.log`);return p.default.writeFileSync(n,t,`utf8`),n}catch{return}}async prepareDockerRetryUserDataDir(e){await this.delay(250);try{let t=await this.lockManager.cleanupOrphanedLocks(e);return this.cleanupExtensionSingletonArtifacts(e),`${t?`cleaned`:`checked`} ${e}`}catch(t){let n=t instanceof Error?t.message:String(t);return this.cleanupExtensionSingletonArtifacts(e),`lock-manager cleanup failed (${n}); singleton artifacts removed directly from ${e}`}}cleanupExtensionSingletonArtifacts(e){let t=[m.default.join(e,`SingletonLock`),m.default.join(e,`SingletonCookie`),m.default.join(e,`SingletonSocket`),m.default.join(e,`lockfile`),m.default.join(e,`Default`,`LOCK`)];for(let e of t)try{p.default.rmSync(e,{force:!0})}catch{}}cleanupStaleBrowser(e,t){if(t){let e=this.getExtensionUserDataDir(t);this.cleanupExtensionSingletonArtifacts(e),this.lockManager.cleanupOrphanedLocks(e).catch(()=>{})}this.browsers.delete(e),t&&this.profileToBrowserId.delete(t)}initializeExtensionRecording(e,t,n){let r=m.default.join(n.dir,`recording-${this.toSafeRecordingId(e.id)}-${e.createdAt.getTime()}.webm`);this.initializeExtensionRecordingAtPath(e,t,r)}initializeExtensionRecordingAtPath(e,t,n){e.extensionRecording={pageId:t,outputPath:n,chunkPath:`${n}.part`,active:!1,chunkCount:0,chunkBytes:0}}async startExtensionRecording(e,t){if(!this.extensionTaskQueue)throw Error(`Extension recording task queue is unavailable for browser "${e.id}"`);R&&console.log(`[ExtensionRecordingDebug] queue start browser=${e.id} page=${t.pageId} active=${t.active}`);let n=await this.extensionTaskQueue.queueTask(`browser_start_recording`,{pageId:t.pageId},N,e.id);if(R&&console.log(`[ExtensionRecordingDebug] start result browser=${e.id} success=${n?.success===!0} isError=${n?.result?.isError===!0}`),!n.success||n.result?.isError){let r=this.getExtensionTaskError(n);if(this.isExtensionRecordingAlreadyActiveError(r)){t.active=!0;return}throw Error(r??`Failed to start extension recording for "${e.id}"`)}t.active=!0}isExtensionRecordingAlreadyActiveError(e){return e?/active stream/i.test(e)||/recording already in progress/i.test(e):!1}async attemptExtensionRecordingFinalization(e){let t=this.finalizeExtensionRecording(e).then(()=>({completed:!0})).catch(e=>({completed:!0,error:e instanceof Error?e:Error(String(e))})),n=this.delay(1500).then(()=>({completed:!1}));return Promise.race([t,n])}async waitForExtensionRecordingArtifact(e){let t=Date.now();for(;Date.now()-t<yn;){try{let t=p.default.statSync(e);if(t.isFile()&&t.size>0)return!0}catch{}await this.delay(100)}return!1}async waitForExtensionRecordingArtifactOrChunks(e){let t=Date.now();for(;Date.now()-t<yn;){try{let t=p.default.statSync(e.outputPath);if(t.isFile()&&t.size>0)return{artifactReady:!0,chunkReady:!1}}catch{}try{let t=p.default.statSync(e.chunkPath);if(t.isFile()&&t.size>0)return{artifactReady:!1,chunkReady:!0}}catch{}await this.delay(100)}return{artifactReady:!1,chunkReady:!1}}getExtensionRecordingSession(e){return this.browsers.get(e)?.extensionRecording??this.closingExtensionRecordings.get(e)}async finalizeClosingExtensionRecording(e){let t=this.closingExtensionRecordings.get(e);if(t)try{let n=await this.waitForExtensionRecordingArtifactOrChunks(t);!n.artifactReady&&n.chunkReady&&await this.persistExtensionRecordingArtifact(e)}finally{this.closingExtensionRecordings.delete(e)}}shouldCloseRecordedExtensionPageFirst(e){return(e.mode===`extension`||e.mode===`vm`)&&!!e.extensionRecording&&!!this.extensionTaskQueue}async closeRecordedExtensionPage(e,t){if(!this.extensionTaskQueue)throw Error(`Extension recording task queue is unavailable for browser "${e.id}"`);if(e.pageIds.size<=1){let t=await this.extensionTaskQueue.queueTask(`browser_new_page`,{url:`about:blank`,setAsCurrent:!1},N,e.id);if(!t.success||t.result?.isError)throw Error(this.getExtensionTaskError(t)??`Failed to create a keepalive tab for browser "${e.id}" before closing the recorded page`)}let n=await this.extensionTaskQueue.queueTask(`browser_close_page`,{pageId:t.pageId},N,e.id);if(!n.success||n.result?.isError)throw Error(this.getExtensionTaskError(n)??`Failed to close the recorded page "${t.pageId}" for browser "${e.id}"`)}parseExtensionRecordingPayload(e){if(!e.success||e.result?.isError)throw Error(this.getExtensionTaskError(e)??`Extension recording task failed`);let t=e.result?.content[0],n=t?.type===`text`?t.text:void 0;if(!n)return{};try{return JSON.parse(n)}catch{throw Error(`Extension recording task returned invalid JSON payload`)}}getExtensionTaskError(e){if(e.error)return e.error;let t=e.result?.content[0];if(t?.type===`text`)return t.text}toSafeRecordingId(e){return e.replace(/[^a-zA-Z0-9_-]+/g,`-`)}persistExtensionRecordingChunksToArtifact(e){try{let t=p.default.statSync(e.chunkPath);if(!t.isFile()||t.size<=0)return!1}catch{return!1}if(p.default.existsSync(e.outputPath)){let t=p.default.statSync(e.outputPath);if(t.isFile()&&t.size>0)return this.clearExtensionRecordingChunkState(e),!0}return p.default.renameSync(e.chunkPath,e.outputPath),e.chunkCount=0,e.chunkBytes=0,!0}hasPersistedExtensionRecordingArtifact(e){try{let t=p.default.statSync(e.outputPath);return t.isFile()&&t.size>0}catch{return!1}}clearExtensionRecordingChunkState(e){e.chunkCount=0,e.chunkBytes=0;try{p.default.existsSync(e.chunkPath)&&p.default.rmSync(e.chunkPath,{force:!0})}catch{}}getBrowserType(e){switch(e){case`chromium`:return D.chromium;case`firefox`:return D.firefox;case`webkit`:return D.webkit}}buildContextOptions(e,t,n){let r={};return t&&(r.baseURL=t),n&&(r.recordVideo=n),e?(e.viewport&&(r.viewport=e.viewport),e.userAgent&&(r.userAgent=e.userAgent),e.locale&&(r.locale=e.locale),e.timezone&&(r.timezoneId=e.timezone),e.geolocation&&(r.geolocation=e.geolocation),e.permissions&&(r.permissions=e.permissions),e.colorScheme&&(r.colorScheme=e.colorScheme),r):r}};Cn=L=j([(0,d.injectable)(),P(0,(0,d.inject)(k.ProfileService)),P(1,(0,d.inject)(k.PageRegistry)),P(2,(0,d.inject)(k.BrowserLockManager)),P(3,(0,d.inject)(k.ChromeForTestingService)),P(4,(0,d.inject)(k.PageMonitorService)),P(4,(0,d.optional)()),P(5,(0,d.inject)(k.WebSocketHub)),P(5,(0,d.optional)()),P(6,(0,d.inject)(k.ExtensionSessionRegistry)),P(6,(0,d.optional)()),P(7,(0,d.inject)(k.ExtensionTaskQueue)),P(7,(0,d.optional)()),A(`design:paramtypes`,[Object,Object,Object,Object,Object,Object,Object,Object])],Cn);function wn(e){return e.trim().toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``)||`snippet`}function Tn(e){return e.replace(/\r\n/g,`
6
6
  `).split(`
7
7
  `).map(e=>e.length>0?` ${e}`:e).join(`
8
8
  `)}function En(e){return[`export const name = ${JSON.stringify(e.name)};`,`export const description = ${JSON.stringify(e.description)};`,`export const run = async ({ page, context, browser }) => {`,Tn(e.code),`};`,``].join(`
9
- `)}async function Dn(e){let t=(0,ne.stripTypeScriptTypes)(await(0,T.readFile)(e,`utf8`),{mode:`strip`});return await import(`data:text/javascript;base64,${Buffer.from(t,`utf8`).toString(`base64`)}`)}var On=class{constructor(e=process.env.BROWSE_TOOL_SNIPPETS_DIR){this.snippetsDir=e}getDirectory(){return this.snippetsDir?m.default.resolve(this.snippetsDir):void 0}async listSnippets(){let e=this.requireDirectory();await(0,T.mkdir)(e,{recursive:!0});let t=await(0,T.readdir)(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile()||!r.name.endsWith(`.ts`))continue;let t=r.name,i=await Dn(m.default.join(e,r.name)),a=typeof i.name==`string`&&i.name.trim().length>0?i.name:r.name.replace(/\.ts$/,``),o=typeof i.description==`string`?i.description:``;n.push({name:a,description:o,snippetPath:t})}return n.sort((e,t)=>e.name.localeCompare(t.name)),n}async loadSnippet(e){let t=await this.resolveSnippetPath(e),n=await Dn(t.filePath);if(typeof n.run!=`function`)throw Error(`Snippet "${t.snippetPath}" must export a "run" function`);return{name:typeof n.name==`string`&&n.name.trim().length>0?n.name:t.snippetPath.replace(/\.ts$/,``),description:typeof n.description==`string`?n.description:``,snippetPath:t.snippetPath,run:n.run}}async saveSnippet(e){let t=this.requireDirectory();await(0,T.mkdir)(t,{recursive:!0});let n=`${wn(e.name)}.ts`;return await(0,T.writeFile)(m.default.join(t,n),En(e),`utf8`),{name:e.name,description:e.description,snippetPath:n}}requireDirectory(){let e=this.getDirectory();if(!e)throw Error(`Snippet storage is not configured. Start browse-tool with --snippets-dir.`);return e}async resolveSnippetPath(e){let t=this.requireDirectory(),n=e.endsWith(`.ts`)?e:`${e}.ts`,r=m.default.resolve(t,n);if(!r.startsWith(`${t}${m.default.sep}`)&&r!==m.default.join(t,n))throw Error(`Snippet path must stay within the configured snippets directory`);if(!(await(0,T.stat)(r).catch(()=>null))?.isFile())throw Error(`Snippet "${e}" not found`);return{filePath:r,snippetPath:m.default.relative(t,r)}}};let kn=class{async locate(e,t){let n=await this.getFrameContext(e,t.frame),r=this.buildLocator(n,t);if(await r.count()===0)throw Error(`Element not found: ${this.describeSelector(t)}`);return r.first()}async locateAll(e,t){let n=await this.getFrameContext(e,t.frame);return this.buildLocator(n,t)}async waitForElement(e,t,n={}){let r=await this.getFrameContext(e,t.frame),i=this.buildLocator(r,t);return await i.waitFor({timeout:n.timeout??P,state:n.state??`visible`}),i.first()}async getFrameContext(e,t){return t?e.frameLocator(t):e}buildLocator(e,t){if(t.uid)return e.locator(`[data-uid="${t.uid}"]`);if(t.xpath)return e.locator(`xpath=${t.xpath}`);if(t.text)return e.locator(`text=${t.text}`);if(t.selector)return e.locator(t.selector);throw Error(`No selector provided. Specify one of: selector, xpath, text, or uid.`)}describeSelector(e){let t=[];return e.uid&&t.push(`uid="${e.uid}"`),e.selector&&t.push(`selector="${e.selector}"`),e.xpath&&t.push(`xpath="${e.xpath}"`),e.text&&t.push(`text="${e.text}"`),e.frame&&t.push(`frame="${e.frame}"`),t.length>0?t.join(`, `):`empty selector`}};kn=M([(0,d.injectable)()],kn);const An=process.env.BROWSE_TOOL_DEBUG_CUSTOM_TOOLS===`1`;function jn(e){return JSON.stringify(e,(e,t)=>typeof t==`string`&&t.length>240?`${t.slice(0,240)}...<trimmed>`:t)}function B(e,t){if(An){if(t){console.error(`[ExtensionPageProxy] ${e}`,t);return}console.error(`[ExtensionPageProxy] ${e}`)}}function Mn(e){return typeof e==`object`&&e&&`value`in e?e.value:e}let Nn=class{[c._]=!0;currentUrl=`about:blank`;defaultTimeoutMs=P;_pageId;_browserId;constructor(e){this.taskQueue=e}setTarget(e,t){this._pageId=e,this._browserId=t}get pageId(){return this._pageId}get browserId(){return this._browserId}async goto(e,t){let n=await this.executeTask(`browser_navigate`,{url:e,waitUntil:t?.waitUntil,timeout:t?.timeout});if(!n.success)throw Error(n.error??`Navigation failed`);this.currentUrl=e}async click(e,t){let n=await this.executeTask(`browser_click`,{selector:e,clickCount:t?.clickCount,delay:t?.delay,button:t?.button,modifiers:t?.modifiers});if(!n.success)throw Error(n.error??`Click failed on ${e}`)}async fill(e,t,n){let r=await this.executeTask(`browser_fill`,{selector:e,text:t,force:n?.force});if(!r.success)throw Error(r.error??`Fill failed on ${e}`)}async type(e,t,n){let r=await this.executeTask(`browser_type`,{selector:e,text:t,delay:n?.delay});if(!r.success)throw Error(r.error??`Type failed on ${e}`)}async press(e){let t=await this.executeTask(`browser_press_key`,{key:e});if(!t.success)throw Error(t.error??`Press key failed: ${e}`)}async hover(e){let t=await this.executeTask(`browser_hover`,{selector:e});if(!t.success)throw Error(t.error??`Hover failed on ${e}`)}async selectOption(e,t){let n=await this.executeTask(`browser_select`,{selector:e,values:Array.isArray(t)?t:[t]});if(!n.success)throw Error(n.error??`Select option failed on ${e}`)}async waitForSelector(e,t){let n=await this.executeTask(`browser_wait_for`,{selector:e,state:t?.state??`visible`,timeout:t?.timeout});if(!n.success)throw Error(n.error??`Wait for selector failed: ${e}`)}async waitForTimeout(e){let t=await this.executeTask(`browser_wait_for`,{timeout:e});if(!t.success)throw Error(t.error??`Wait for timeout failed`)}async screenshot(e){let t=await this.executeTask(`browser_screenshot`,{path:e?.path,fullPage:e?.fullPage,type:e?.type});if(!t.success)throw Error(t.error??`Screenshot failed`);return t.result?.path??``}async content(){let e=await this.executeTask(`browser_evaluate_script`,{script:`document.documentElement.outerHTML`});if(!e.success)throw Error(e.error??`Get content failed`);return Mn(e.result)??``}async title(){let e=await this.executeTask(`browser_evaluate_script`,{script:`document.title`});if(!e.success)throw Error(e.error??`Get title failed`);return Mn(e.result)??``}async textContent(e){return this.locator(e).textContent()}async innerText(e){return this.locator(e).innerText()}async inputValue(e){return this.locator(e).inputValue()}url(){return this.currentUrl}async evaluate(e,...t){let n=typeof e==`function`?`(${e.toString()})(${t.map(e=>JSON.stringify(e)).join(`,`)})`:e,r=await this.executeTask(`browser_evaluate_script`,{script:n});if(!r.success)throw Error(r.error??`Evaluate failed`);return Mn(r.result)}async getSnapshot(){let e=await this.executeTask(`browser_snapshot`,{});if(!e.success)throw Error(e.error??`Get snapshot failed`);let t=Mn(e.result);return typeof t==`string`?t:t==null?``:JSON.stringify(t,null,2)}getByRole(e,t){return new c.v(this,[{type:`role`,role:e,options:t}])}getByText(e,t){return new c.v(this,[{type:`text`,text:e,options:t}])}getByLabel(e,t){return new c.v(this,[{type:`label`,text:e,options:t}])}getByPlaceholder(e,t){return new c.v(this,[{type:`placeholder`,text:e,options:t}])}getByTestId(e){return new c.v(this,[{type:`testId`,testId:e}])}locator(e){return new c.v(this,[{type:`css`,selector:e}])}context(){return{clearCookies:async()=>{await this.clearStorageState()}}}async reload(e){let t=await this.executeTask(`browser_reload`,{waitUntil:e?.waitUntil,timeout:e?.timeout});if(!t.success)throw Error(t.error??`Reload failed`)}async currentUrlAsync(){let e=await this.evaluate(`window.location.href`);return e&&(this.currentUrl=e),this.currentUrl}async waitForResponse(e,t){let n=typeof e==`string`?{url:e}:e instanceof RegExp?{urlPattern:{source:e.source,flags:e.flags}}:null;if(!n)throw Error(`Extension mode only supports waitForResponse with a string or RegExp target`);let r=await this.executeTask(`browser_wait_for_response`,{...n,timeout:t?.timeout??this.defaultTimeoutMs});if(!r.success)throw Error(r.error??`Wait for response failed`)}async getStorageState(){let e=await this.executeTask(`browser_get_storage_state`,{});if(!e.success)throw Error(e.error??`Get storage state failed`);return e.result??{}}async clearStorageState(){let e=await this.executeTask(`browser_clear_storage_state`,{});if(!e.success)throw Error(e.error??`Clear storage state failed`)}async startRecording(){let e=await this.executeTask(`browser_start_recording`,{});if(!e.success)throw Error(e.error??`Start recording failed`)}async stopRecording(){let e=await this.executeTask(`browser_stop_recording`,{});if(!e.success)throw Error(e.error??`Stop recording failed`);return e.result?.videoBase64??``}async executeTask(e,t){if(!this._pageId||!this._browserId)return{success:!1,error:`Extension page proxy target is not initialized`};let n={...t,pageId:this._pageId};B(`Queueing extension task`,{tool:e,browserId:this._browserId,pageId:this._pageId,args:jn(n)});let r;try{r=await this.taskQueue.queueTask(e,n,this.defaultTimeoutMs,this._browserId)}catch(t){let n=t instanceof Error?t.message:String(t);return B(`Extension task threw before result`,{tool:e,browserId:this._browserId,pageId:this._pageId,error:n}),{success:!1,error:`Extension task "${e}" threw for page "${this._pageId}" in browser "${this._browserId}": ${n}`}}if(!r.success)return B(`Extension task returned unsuccessful result`,{tool:e,browserId:this._browserId,pageId:this._pageId,taskError:r.error??`Task failed`,taskResult:r}),{success:!1,error:r.error??`Extension task "${e}" failed for page "${this._pageId}" in browser "${this._browserId}"`};let i=r.result?.content?.[0];if(i?.type===`text`&&i.text)try{let t=JSON.parse(i.text);return B(`Extension task completed with JSON text result`,{tool:e,browserId:this._browserId,pageId:this._pageId}),{success:!0,result:t}}catch{return B(`Extension task completed with plain text result`,{tool:e,browserId:this._browserId,pageId:this._pageId,textPreview:i.text.slice(0,240)}),{success:!0,result:{value:i.text}}}return B(`Extension task completed with non-text result payload`,{tool:e,browserId:this._browserId,pageId:this._pageId,taskResult:r}),{success:!0,result:r.result}}};Nn=M([(0,d.injectable)(),F(0,(0,d.inject)(A.ExtensionTaskQueue)),j(`design:paramtypes`,[Object])],Nn);let Pn=class{sessions=new Map;browserIdToSessionId=new Map;sessionIdCounter=0;defaultStaleThresholdMs=6e4;register(e){let t=this.browserIdToSessionId.get(e.browserId);t&&(this.sessions.delete(t),this.browserIdToSessionId.delete(e.browserId));let n=`session-${++this.sessionIdCounter}-${Date.now()}`,r=new Date,i={id:n,browserId:e.browserId,tabId:e.tabId,currentUrl:e.url,createdAt:r,lastHeartbeatAt:r,controlMode:`manual`,handoffRequested:!1,metadata:e.metadata};return this.sessions.set(n,i),this.browserIdToSessionId.set(e.browserId,n),i}heartbeat(e){let t=this.sessions.get(e.sessionId);if(t)return t.lastHeartbeatAt=new Date,e.tabId!==void 0&&(t.tabId=e.tabId),e.url!==void 0&&(t.currentUrl=e.url),e.state&&(t.metadata={...t.metadata,...e.state}),t}requestHandoff(e){let t=this.sessions.get(e.sessionId);if(t)return t.handoffRequested=!0,e.pageState&&(t.currentUrl=e.pageState.url,t.metadata={...t.metadata,handoffReason:e.reason,handoffPageState:e.pageState}),t}acknowledgeHandoff(e){let t=this.sessions.get(e);if(!(!t||!t.handoffRequested))return t.handoffRequested=!1,t.controlMode=`ai`,t.activeSpecPath=void 0,t}getSession(e){return this.sessions.get(e)}getSessionByBrowserId(e){let t=this.browserIdToSessionId.get(e);if(t)return this.sessions.get(t)}listSessions(){return Array.from(this.sessions.values())}removeSession(e){let t=this.sessions.get(e);return t?(this.browserIdToSessionId.delete(t.browserId),this.sessions.delete(e),!0):!1}setControlMode(e,t){let n=this.sessions.get(e);if(n)return n.controlMode=t,n}setActiveSpec(e,t){let n=this.sessions.get(e);if(n)return n.activeSpecPath=t,t&&(n.controlMode=`spec`),n}cleanupStaleSessions(e=this.defaultStaleThresholdMs){let t=Date.now(),n=0;for(let[r,i]of this.sessions)t-i.lastHeartbeatAt.getTime()>e&&(this.browserIdToSessionId.delete(i.browserId),this.sessions.delete(r),n++);return n}};Pn=M([(0,d.injectable)()],Pn);let Fn=class{constructor(e,t,n){this.bundler=e,this.pageProxy=t,this.sessionRegistry=n}async loadSpec(e){let t=await this.bundler.bundle(e);try{c.c(e);let n=process,r=n.__pw_initiator__;return n.__pw_initiator__=void 0,await import(`${t.outputPath}?t=${Date.now()}`),n.__pw_initiator__=r,c.s()}catch(t){throw c.p(),Error(`Failed to load spec "${e}": ${t instanceof Error?t.message:String(t)}`,{cause:t})}finally{await t.cleanup()}}async executeSpec(e){let{specPath:t,sessionId:n,testFilter:r,specArgs:i,onHandoff:a}=e,o=Date.now(),s=[],c=0,l=0,u=!1;this.sessionRegistry.setActiveSpec(n,t);try{let e=await this.loadSpec(t),d=r?this.filterTests(e.allTests,r):e.allTests,f={page:this.pageProxy,requestHandoff:async e=>{if(!this.sessionRegistry.getSession(n))throw Error(`Session ${n} not found`);let t=await this.pageProxy.getSnapshot(),r=this.pageProxy.url();this.sessionRegistry.requestHandoff({sessionId:n,reason:e,pageState:{url:r,snapshot:t}}),u=!0,a&&await a(n)},specArgs:i};for(let e of d){if(e.skip){s.push({title:e.title,fullTitle:e.fullTitle,passed:!0,error:null,duration:0}),c++;continue}let t=this.sessionRegistry.getSession(n);if(t?.handoffRequested)break;let r=Date.now();try{await e.fn(f),s.push({title:e.title,fullTitle:e.fullTitle,passed:!0,error:null,duration:Date.now()-r,handoffTriggered:t?.handoffRequested}),c++}catch(t){let n=t instanceof Error?t.message:String(t);s.push({title:e.title,fullTitle:e.fullTitle,passed:!1,error:n,duration:Date.now()-r}),l++}}return{specPath:t,totalTests:d.length,passed:c,failed:l,testResults:s,success:l===0,duration:Date.now()-o,handoffOccurred:u,sessionId:n}}catch(e){return{specPath:t,totalTests:0,passed:0,failed:1,testResults:[{title:`Spec Loading`,fullTitle:`Failed to load: ${t}`,passed:!1,error:e instanceof Error?e.message:String(e),duration:Date.now()-o}],success:!1,duration:Date.now()-o,handoffOccurred:!1,sessionId:n}}finally{this.sessionRegistry.setActiveSpec(n,void 0)}}filterTests(e,t){let n=[...e];if(t.onlyMarked){let e=n.filter(e=>e.only);e.length>0&&(n=e)}if(t.testName&&(n=n.filter(e=>e.title===t.testName)),t.testPattern){let e=new RegExp(t.testPattern,`i`);n=n.filter(t=>e.test(t.fullTitle))}if(t.describeFilter){let e=new RegExp(t.describeFilter,`i`);n=n.filter(t=>e.test(t.fullTitle))}return n}};Fn=M([(0,d.injectable)(),F(0,(0,d.inject)(A.SpecBundlerService)),F(1,(0,d.inject)(A.ExtensionPageProxy)),F(2,(0,d.inject)(A.ExtensionSessionRegistry)),j(`design:paramtypes`,[Object,Object,Object])],Fn);const In=`localhost`,Ln=3200,Rn=`PLAYWRIGHT_HOST`,zn=`PLAYWRIGHT_PORT`;function V(){return process.env.PLAYWRIGHT_HOST?.trim()||`localhost`}function Bn(){let e=process.env[zn];if(!e)return Ln;let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<=0||t>65535)throw Error(`Invalid ${zn} value: ${e}`);return t}function H(e=void 0,t){return`http://${typeof e==`string`?e:e?.host??V()}:${e&&typeof e!=`string`?e.port:t??Bn()}`}let Vn=class{baseUrl;defaultTimeout=P;constructor(){this.baseUrl=H()}setBaseUrl(e){this.baseUrl=e}getBaseUrl(){return this.baseUrl}async execute(e,t={}){let n=`${this.baseUrl}/execute`,r=new AbortController,i=setTimeout(()=>r.abort(),this.defaultTimeout);try{let a={tool:e,arguments:t},o=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a),signal:r.signal});if(clearTimeout(i),!o.ok){let e=await o.text();return{content:[{type:`text`,text:`HTTP error ${o.status}: ${e}`}],isError:!0}}let s=await o.json();return s.success?s.result||{content:[{type:`text`,text:`No result returned`}]}:{content:[{type:`text`,text:s.error||s.result?.content?.[0]?.text||`Unknown error`}],isError:!0}}catch(e){return clearTimeout(i),e instanceof Error&&e.name===`AbortError`?{content:[{type:`text`,text:`Request timed out after ${this.defaultTimeout}ms`}],isError:!0}:{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}}async isHealthy(){try{let e=await fetch(`${this.baseUrl}/health`,{headers:{"Content-Type":`application/json`}});return e.ok?(await e.json()).status===`healthy`:!1}catch{return!1}}};Vn=M([(0,d.injectable)(),j(`design:paramtypes`,[])],Vn);let U=class{defaultTimeout=5e3;async check(e,t=this.defaultTimeout){try{let n=`${H(V(),e)}/health`,r=new AbortController,i=setTimeout(()=>r.abort(),t);try{let t=await fetch(n,{signal:r.signal,headers:{"Content-Type":`application/json`}});if(clearTimeout(i),!t.ok)return{healthy:!1,error:`HTTP error ${t.status}: ${t.statusText}`};let a=await t.json();return a.status===`healthy`?{healthy:!0,port:e,serviceName:a.service,browserCount:a.browsers?.count}:{healthy:!1,error:`Unexpected health status: ${a.status||`unknown`}`}}catch(e){return clearTimeout(i),e instanceof Error?e.name===`AbortError`?{healthy:!1,error:`Health check timed out after ${t}ms`}:`code`in e&&e.code===`ECONNREFUSED`?{healthy:!1,error:`Connection refused - server not running`}:{healthy:!1,error:`Network error: ${e.message}`}:{healthy:!1,error:`Unknown error: ${String(e)}`}}}catch(e){return{healthy:!1,error:e instanceof Error?e.message:String(e)}}}};U=M([(0,d.injectable)()],U);const Hn=(0,D.fileURLToPath)(require(`url`).pathToFileURL(__filename).href),Un=m.dirname(Hn),Wn=`PLAYWRIGHT_SKIP_DYNAMIC_TOOL_COMMANDS`,Gn=`1`,Kn=[`pnpm-workspace.yaml`,`nx.json`,`.git`],W=`browse-tool-http`,qn=`tool`,Jn=`http-serve`,Yn=3,Xn=1e4,Zn=100,Qn=1e3,$n=`ESRCH`,er=`SIGTERM`,tr=`SIGKILL`,nr=`--port`,rr=`--host`,ir=`development`,ar=`node`,or=`bun`,sr=`run`,cr=`cli.mjs`,lr=`cli.ts`,ur=`dist`,dr=`src`,fr=`HTTP_SERVER_STALE_ENTRY`,pr=`HTTP_SERVER_NOT_REGISTERED`,mr=`Server registered but not healthy`,hr=`No HTTP server registered`,gr=`Run ensureRunning() to start a fresh server or clean up stale entries.`,_r=`Call ensureRunning() to discover or spawn a server.`,vr=`No matching registry entry`,G=`[HttpServerManager]`;var yr=class extends Error{code=`HTTP_SERVER_PORT_ERROR`;recovery=`Check if other services are occupying ports in the configured range.`;constructor(e,t){super(e,t),this.name=`HttpServerPortError`}},K=class extends Error{code=`HTTP_SERVER_STARTUP_ERROR`;recovery=`Check server logs, ensure CLI binary exists, and verify port availability.`;constructor(e,t){super(e,t),this.name=`HttpServerStartupError`}},br=class extends Error{code=`HTTP_SERVER_STOP_ERROR`;recovery=`Manually kill the process and clean up the port registry.`;causes;constructor(e,t=[],n){super(e,n),this.name=`HttpServerStopError`,this.causes=t}};async function q(e){try{return await T.access(e),!0}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!1;throw e}}async function xr(e=process.cwd()){let t=m.resolve(e);for(;;){for(let e of Kn)if(await q(m.join(t,e)))return t;let e=m.dirname(t);if(e===t)return process.cwd();t=e}}let Sr=class{repositoryPath;environment;host;constructor(e,t){this.healthCheck=e,this.portRegistry=t,this.environment=process.env.NODE_ENV||`development`,this.host=V()}async getRepositoryPath(){return this.repositoryPath||=await xr(process.cwd()),this.repositoryPath}buildErrorStatus(e){return{running:!1,error:e instanceof Error?e.message:String(e),errorCode:e instanceof Error&&`code`in e?e.code:void 0,errorRecovery:e instanceof Error&&`recovery`in e?e.recovery:void 0,errorCause:e instanceof Error&&e.cause instanceof Error?e.cause.message:void 0}}async listServiceEntries(){return this.portRegistry.listAllocations({serviceName:W,serviceType:qn,environment:this.environment})}async releaseEntry(e){let t=await this.portRegistry.releasePort({repositoryPath:e.repositoryPath,serviceName:W,serviceType:qn,environment:e.environment,pid:e.pid});!t.success&&!t.error?.includes(`No matching registry entry`)&&console.error(`${G} Failed to release entry for port ${e.port}: ${t.error}`)}async discoverHealthyService(){let e=await this.listServiceEntries();for(let t of e)try{let e=await this.healthCheck.check(t.port);if(e.healthy&&e.serviceName===W)return{entry:t,browserCount:e.browserCount}}catch(e){console.error(`${G} Health check threw for port ${t.port}: ${e instanceof Error?e.message:String(e)}`)}return null}async discoverHealthyServiceOnPort(e){let t=await this.findRegistrationByPort(e);if(!t)return null;try{let n=await this.healthCheck.check(e);if(n.healthy&&n.serviceName===W)return{entry:t,browserCount:n.browserCount}}catch(t){console.error(`${G} Health check threw for requested port ${e}: ${t instanceof Error?t.message:String(t)}`)}return null}async cleanupStaleEntries(){let e=await this.listServiceEntries(),t=[];for(let n of e)try{let e;try{e=await this.healthCheck.check(n.port)}catch(e){console.error(`${G} Health check threw for port ${n.port}, skipping cleanup: ${e instanceof Error?e.message:String(e)}`);continue}e.healthy&&e.serviceName===W||(n.pid&&await this.killProcess(n.pid),await this.releaseEntry(n))}catch(e){let r=`Failed to clean up entry on port ${n.port}: ${e instanceof Error?e.message:String(e)}`;console.error(`${G} ${r}`),t.push(r)}t.length>0&&console.error(`${G} ${t.length} entry cleanup failure(s) during stale entry removal`)}async findRegistrationByPort(e){return(await this.listServiceEntries()).find(t=>t.port===e)??null}async findAvailablePort(e){let t=await this.getRepositoryPath(),n=await this.portRegistry.findAvailablePort({repositoryPath:t,serviceName:W,serviceType:qn,environment:this.environment,host:this.host,preferredPort:e});if(!n.success||!n.port)throw new yr(`No available port found from ${e}: ${n.error}`);return n.port}async ensureExactPortAvailable(e){let t=await this.findAvailablePort(e);if(t!==e)throw new yr(`Requested port ${e} is unavailable; next available port is ${t}`)}async resolveCliCommand(e){let t=m.resolve(Un,cr),n=m.resolve(Un,`..`,lr),r=[`--port`,e.toString(),`--host`,this.host];if(await q(t))return[ar,[t,Jn,...r]];if(await q(n))return[`bun`,[`run`,n,Jn,...r]];let i=m.resolve(Un,`..`,`..`),a=m.join(i,`dist`,cr),o=m.join(i,`src`,lr);if(await q(a))return[ar,[a,Jn,...r]];if(await q(o))return[`bun`,[`run`,o,Jn,...r]];throw new K(`Cannot find CLI at ${t}, ${n}, ${a}, or ${o}`)}async startHttpServer(e){let[t,n]=await this.resolveCliCommand(e),r=(0,E.spawn)(t,n,{detached:!0,stdio:`ignore`,env:{...process.env,NODE_ENV:this.environment,PLAYWRIGHT_SKIP_DYNAMIC_TOOL_COMMANDS:`1`}}),i=await new Promise(e=>{let t=setTimeout(()=>{r.removeAllListeners(`error`),e(null)},100);r.once(`error`,n=>{clearTimeout(t),e(n)})});if(i)throw new K(`Failed to spawn HTTP server process: ${i.message}`,{cause:i});r.unref();let a=r.pid;if(!a)throw new K(`Failed to spawn HTTP server - no PID returned`);return a}async killProcess(e){try{process.kill(e,0),process.kill(e,`SIGTERM`)}catch(t){if((t instanceof Error&&`code`in t?t.code:void 0)===$n){console.error(`${G} Process ${e} does not exist — skipping kill`);return}throw t}await new Promise(e=>setTimeout(e,1e3));try{process.kill(e,0),process.kill(e,`SIGKILL`)}catch(t){if((t instanceof Error&&`code`in t?t.code:void 0)===$n){console.error(`${G} Process ${e} exited after SIGTERM`);return}throw t}}async cleanupFailedSpawn(e,t){await this.killProcess(e);let n=await this.findRegistrationByPort(t);n&&n.pid===e&&await this.releaseEntry(n)}async attemptSpawn(e){let t=await this.findAvailablePort(e),n=await this.startHttpServer(t);await new Promise(e=>setTimeout(e,1e4));let r;try{r=await this.healthCheck.check(t)}catch(e){let r=e instanceof Error?e.message:String(e);return console.error(`${G} Health check threw on port ${t}: ${r}`),await this.cleanupFailedSpawn(n,t),{success:!1,reason:`health_check_error`,port:t,error:r}}if(!r.healthy)return await this.cleanupFailedSpawn(n,t),{success:!1,reason:`health_check_failed`,port:t,error:r.error};if(r.serviceName!==W)return await this.cleanupFailedSpawn(n,t),{success:!1,reason:`service_name_mismatch`,port:t,error:`Expected ${W}, got ${r.serviceName}`};let i=await this.findRegistrationByPort(t);return!i||i.pid!==n?(console.error(`${G} Ownership mismatch on port ${t}: expected pid ${n}, found ${i?.pid}`),await this.cleanupFailedSpawn(n,t),{success:!1,reason:`ownership_mismatch`,port:t}):(console.error(`${G} Server self-registered on port ${t} (pid: ${i.pid})`),{success:!0,port:t,pid:n,browserCount:r.browserCount})}async ensureRunning(e=Bn(),t={}){try{if(t.exactPort){let t=await this.discoverHealthyServiceOnPort(e);if(t)return{running:!0,port:t.entry.port,pid:t.entry.pid,browserCount:t.browserCount,spawned:!1};await this.cleanupStaleEntries(),await this.ensureExactPortAvailable(e);let n=await this.attemptSpawn(e);if(n.success)return{running:!0,port:n.port,pid:n.pid,browserCount:n.browserCount,spawned:!0};let r=new K(`Failed to start browse-tool HTTP server on requested port ${e}: ${n.reason}`);return this.buildErrorStatus(r)}let n=await this.discoverHealthyService();if(n)return{running:!0,port:n.entry.port,pid:n.entry.pid,browserCount:n.browserCount,spawned:!1};await this.cleanupStaleEntries();let r=e;for(let e=0;e<3;e+=1){let t=await this.attemptSpawn(r);if(t.success)return{running:!0,port:t.port,pid:t.pid,browserCount:t.browserCount,spawned:!0};console.error(`${G} Spawn attempt ${e+1} failed: ${t.reason} on port ${t.port}`),r=t.port+1}let i=new K(`Failed to start browse-tool HTTP server after 3 attempts`);return this.buildErrorStatus(i)}catch(e){return this.buildErrorStatus(e)}}async stop(){let e=await this.listServiceEntries();if(e.length===0)return!1;let t=[];for(let n of e)try{n.pid&&await this.killProcess(n.pid),await this.releaseEntry(n)}catch(e){let r=e instanceof Error?e:Error(`Failed to stop entry on port ${n.port}: ${String(e)}`);console.error(`${G} ${r.message}`),t.push(r)}if(t.length>0){let n=t.map(e=>e.message);throw new br(`Failed to stop ${t.length} of ${e.length} server(s): ${n.join(`; `)}`,t,{cause:t[0]})}return!0}async getStatus(){try{let e=await this.discoverHealthyService();if(e)return{running:!0,port:e.entry.port,pid:e.entry.pid,browserCount:e.browserCount};let t=await this.listServiceEntries();if(t.length>0){let e=t[0];return{running:!1,port:e.port,pid:e.pid,error:`Server registered but not healthy`,errorCode:`HTTP_SERVER_STALE_ENTRY`,errorRecovery:`Run ensureRunning() to start a fresh server or clean up stale entries.`}}return{running:!1,error:`No HTTP server registered`,errorCode:`HTTP_SERVER_NOT_REGISTERED`,errorRecovery:`Call ensureRunning() to discover or spawn a server.`}}catch(e){return this.buildErrorStatus(e)}}};Sr=M([(0,d.injectable)(),F(0,(0,d.inject)(A.HttpServerHealthCheck)),F(1,(0,d.inject)(A.PortRegistryService)),j(`design:paramtypes`,[Object,Object])],Sr);const Cr=900*1e3,wr=1800*1e3,Tr=60*1e3,Er=`PLAYWRIGHT_BROWSER_IDLE_TIMEOUT_MINUTES`;function Dr(){let e=process.env[Er];if(!e)return wr;let t=Number.parseFloat(e);return!Number.isFinite(t)||t<=0?wr:Math.round(t*60*1e3)}let Or=class{intervalId=null;browserIdleTimeoutMs=Dr();constructor(e,t){this.browserService=e,this.pageRegistry=t}start(){this.intervalId||(this.intervalId=setInterval(()=>{this.cleanup().catch(e=>{console.warn(`[IdleCleanup] Error during cleanup:`,e)})},6e4),this.intervalId&&typeof this.intervalId==`object`&&`unref`in this.intervalId&&this.intervalId.unref(),console.warn(`[IdleCleanup] Started (page timeout: ${Cr/6e4}min, browser timeout: ${this.browserIdleTimeoutMs/6e4}min)`))}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,console.warn(`[IdleCleanup] Stopped`))}async cleanup(){let e=Date.now();await this.cleanupIdlePages(e),await this.cleanupIdleBrowsers(e)}async cleanupIdlePages(e){let t=this.pageRegistry.list();for(let n of t){let t=e-n.lastAccessedAt.getTime();if(!(t<Cr)){console.warn(`[IdleCleanup] Closing idle page "${n.id}" (idle ${Math.round(t/6e4)}min)`);try{if(n.page)await n.page.close();else{let e=this.browserService.getBrowser(n.browserId);if(e&&(e.pageIds.delete(n.id),e.currentPageId===n.id)){let t=Array.from(e.pageIds);e.currentPageId=t.length>0?t[0]:null}this.pageRegistry.remove(n.id)}}catch(e){console.warn(`[IdleCleanup] Failed to close page "${n.id}":`,e)}}}}async cleanupIdleBrowsers(e){let t=this.browserService.listBrowsers();for(let n of t){let t=n.specOrigin?Cr:this.browserIdleTimeoutMs,r=e-n.lastAccessedAt.getTime();if(!(r<t)){console.warn(`[IdleCleanup] Closing idle browser "${n.id}" (idle ${Math.round(r/6e4)}min)`);try{await this.browserService.closeBrowser(n.id)}catch(e){console.warn(`[IdleCleanup] Failed to close browser "${n.id}":`,e)}}}}};Or=M([(0,d.injectable)(),F(0,(0,d.inject)(A.BrowserService)),F(1,(0,d.inject)(A.PageRegistry)),j(`design:paramtypes`,[Object,Object])],Or);let J=class{browsers=new Map;pages=new Map;trackBrowser(e,t){this.browsers.has(e)||this.browsers.set(e,{browserId:e,mode:t,createdAt:new Date,pageIds:new Set})}trackPage(e,t,n){if(this.pages.has(e))return;this.pages.set(e,{pageId:e,browserId:t,url:n,createdAt:new Date});let r=this.browsers.get(t);r&&r.pageIds.add(e)}untrackBrowser(e){let t=this.browsers.get(e);if(t){for(let e of t.pageIds)this.pages.delete(e);this.browsers.delete(e)}}untrackPage(e){let t=this.pages.get(e);if(t){let n=this.browsers.get(t.browserId);n&&n.pageIds.delete(e),this.pages.delete(e)}}getBrowserIds(){return Array.from(this.browsers.keys())}getPageIds(){return Array.from(this.pages.keys())}getPageIdsForBrowser(e){let t=this.browsers.get(e);return t?Array.from(t.pageIds):[]}getSessionState(){return{browsers:Array.from(this.browsers.values()).map(e=>({browserId:e.browserId,mode:e.mode,createdAt:e.createdAt.toISOString(),pageIds:Array.from(e.pageIds)})),pages:Array.from(this.pages.values()).map(e=>({pageId:e.pageId,browserId:e.browserId,url:e.url,createdAt:e.createdAt.toISOString()})),totalBrowsers:this.browsers.size,totalPages:this.pages.size}}clear(){this.browsers.clear(),this.pages.clear()}};J=M([(0,d.injectable)()],J);let kr=class{pageStates=new Map;pageInstances=new Map;startMonitoring(e,t){this.stopMonitoring(e);let n={networkRequests:new Map,consoleMessages:[],requestCounter:0,messageCounter:0,listeners:{}};n.listeners.request=e=>{let t=`req-${++n.requestCounter}`,r={id:t,url:e.url(),method:e.method(),resourceType:e.resourceType(),headers:e.headers(),postData:e.postData()??void 0,timestamp:new Date};n.networkRequests.set(t,r)},n.listeners.response=e=>{let t=e.request();for(let[,r]of n.networkRequests)if(r.url===t.url()&&!r.response){r.response={status:e.status(),statusText:e.statusText(),headers:e.headers(),timing:e.request().timing().responseEnd};break}},n.listeners.console=e=>{let t=`msg-${++n.messageCounter}`,r=e.location(),i={id:t,type:e.type(),text:e.text(),location:r.url?{url:r.url,lineNumber:r.lineNumber,columnNumber:r.columnNumber}:void 0,timestamp:new Date};n.consoleMessages.push(i)},t.on(`request`,n.listeners.request),t.on(`response`,n.listeners.response),t.on(`console`,n.listeners.console),this.pageStates.set(e,n),this.pageInstances.set(e,t),t.once(`close`,()=>{this.stopMonitoring(e)})}stopMonitoring(e){let t=this.pageStates.get(e),n=this.pageInstances.get(e);t&&n&&(t.listeners.request&&n.off(`request`,t.listeners.request),t.listeners.response&&n.off(`response`,t.listeners.response),t.listeners.console&&n.off(`console`,t.listeners.console)),this.pageStates.delete(e),this.pageInstances.delete(e)}getNetworkRequests(e){let t=this.pageStates.get(e);return t?Array.from(t.networkRequests.values()):[]}getNetworkRequest(e,t){let n=this.pageStates.get(e);if(n)return n.networkRequests.get(t)}getConsoleMessages(e,t){let n=this.pageStates.get(e);return n?t?n.consoleMessages.filter(e=>e.type===t):[...n.consoleMessages]:[]}clearData(e){let t=this.pageStates.get(e);t&&(t.networkRequests.clear(),t.consoleMessages=[],t.requestCounter=0,t.messageCounter=0)}};kr=M([(0,d.injectable)()],kr);let Ar=class{pages=new Map;pageIdCounter=0;constructor(e){this.webSocketHub=e}async register(e){let{page:t,browser:n,context:r,browserId:i,profileName:a,mode:o,onClose:s}=e,c=`page-${++this.pageIdCounter}`,l={id:c,mode:o??`playwright`,page:t,browser:n,context:r,browserId:i,url:t.url(),title:await t.title(),profileName:a,createdAt:new Date,lastAccessedAt:new Date,onClose:s};return this.pages.set(c,l),t.once(`close`,()=>{try{s?.(c)}catch{}this.remove(c)}),c}registerExtensionPage(e,t,n,r=!0){let i=`page-${++this.pageIdCounter}`,a={id:i,mode:`extension`,page:void 0,browser:void 0,context:void 0,browserId:e,url:n??`about:blank`,title:`Extension Tab`,extensionTabId:t,createdAt:new Date,lastAccessedAt:new Date};return this.pages.set(i,a),r&&this.webSocketHub?.broadcastPageCreated(e,i,n),i}get(e){return this.pages.get(e)}remove(e){let t=this.pages.get(e);t&&(this.pages.delete(e),t.mode===`extension`&&this.webSocketHub?.broadcastPageRemoved(t.browserId,e))}list(){return Array.from(this.pages.values())}findByBrowser(e){return this.list().filter(t=>t.browserId===e)}findByProfile(e){return this.list().filter(t=>t.profileName===e)}touchPage(e){let t=this.pages.get(e);t&&(t.lastAccessedAt=new Date)}async updateMetadata(e){let t=this.get(e);t&&t.page&&(t.url=t.page.url(),t.title=await t.page.title())}clear(){this.pages.clear(),this.pageIdCounter=0}};Ar=M([(0,d.injectable)(),F(0,(0,d.inject)(A.WebSocketHub)),F(0,(0,d.optional)()),j(`design:paramtypes`,[Object])],Ar);let jr=class{pauseStates=new Map;getOrCreateState(e){let t=this.pauseStates.get(e);return t||(t={isPaused:!1,stepName:null,reason:null,pausedAt:null,resolver:null},this.pauseStates.set(e,t)),t}pause(e,t,n){let r=this.getOrCreateState(e);if(r.isPaused)throw Error(`Session "${e}" is already paused at step "${r.stepName}"`);return r.isPaused=!0,r.stepName=t,r.reason=n??null,r.pausedAt=new Date,new Promise(e=>{r.resolver=e})}resume(e){let t=this.pauseStates.get(e);if(!t||!t.isPaused)return!1;let n=t.resolver;return t.isPaused=!1,t.stepName=null,t.reason=null,t.pausedAt=null,t.resolver=null,n&&n(),!0}waitForResume(e){let t=this.pauseStates.get(e);return!t||!t.isPaused||!t.resolver?Promise.resolve():new Promise(e=>{let n=t.resolver;t.resolver=()=>{n&&n(),e()}})}getStatus(e){let t=this.pauseStates.get(e);return{sessionId:e,isPaused:t?.isPaused??!1,stepName:t?.stepName??null,reason:t?.reason??null,pausedAt:t?.pausedAt??null}}isPaused(e){return this.pauseStates.get(e)?.isPaused??!1}clear(e){let t=this.pauseStates.get(e);t?.resolver&&t.resolver(),this.pauseStates.delete(e)}};jr=M([(0,d.injectable)()],jr);let Mr=class{profilesDir;constructor(){this.profilesDir=process.env.PLAYWRIGHT_PROFILES_DIR||(0,m.join)((0,C.homedir)(),`.browse-tool`,`profiles`)}getProfilesDir(){return this.profilesDir}getProfileDir(e){return(0,m.join)(this.getProfilesDir(),e)}getProfilePath(e){return(0,m.join)(this.getProfileDir(e),`profile.json`)}getStorageStatePath(e){return(0,m.join)(this.getProfileDir(e),`storage-state.json`)}async ensureProfilesDir(){let e=this.getProfilesDir();(0,p.existsSync)(e)||await(0,T.mkdir)(e,{recursive:!0})}async list(){await this.ensureProfilesDir();let e=await(0,T.readdir)(this.getProfilesDir(),{withFileTypes:!0}),t=[];for(let n of e)if(n.isDirectory()){let e=await this.get(n.name);e&&t.push(e)}return t}async get(e){let t=this.getProfilePath(e);if(!(0,p.existsSync)(t))return null;let n=await(0,T.readFile)(t,`utf-8`);return JSON.parse(n)}async create(e){if(await this.get(e.name))throw Error(`Profile "${e.name}" already exists`);await(0,T.mkdir)(this.getProfileDir(e.name),{recursive:!0});let t=new Date().toISOString(),n={...e,createdAt:t,updatedAt:t};return await(0,T.writeFile)(this.getProfilePath(e.name),JSON.stringify(n,null,2)),n}async update(e,t){let n=await this.get(e);if(!n)throw Error(`Profile "${e}" not found`);let r={...n,...t,name:n.name,createdAt:n.createdAt,updatedAt:new Date().toISOString()};return await(0,T.writeFile)(this.getProfilePath(e),JSON.stringify(r,null,2)),r}async delete(e){if(!await this.get(e))throw Error(`Profile "${e}" not found`);await(0,T.rm)(this.getProfileDir(e),{recursive:!0})}async saveStorageState(e,t){if(!await this.get(e))throw Error(`Profile "${e}" not found`);await(0,T.writeFile)(this.getStorageStatePath(e),JSON.stringify(t,null,2))}async loadStorageState(e){let t=this.getStorageStatePath(e);if(!(0,p.existsSync)(t))return null;let n=await(0,T.readFile)(t,`utf-8`);return JSON.parse(n)}};Mr=M([(0,d.injectable)(),j(`design:paramtypes`,[])],Mr);let Nr=class{constructor(e){this.httpClient=e}async execute(e,t={}){return this.httpClient.execute(e,t)}async isServerAvailable(){return this.httpClient.isHealthy()}setServerPort(e){this.httpClient.setBaseUrl(H(void 0,e))}async listTools(){let e=this.httpClient.getBaseUrl(),t=await fetch(`${e}/tools`);if(!t.ok)throw Error(`Failed to list tools: ${t.statusText}`);let n=await t.json();if(n.error)throw Error(n.error);return n.tools}};Nr=M([(0,d.injectable)(),F(0,(0,d.inject)(A.HttpBrowserClient)),j(`design:paramtypes`,[Object])],Nr);let Pr=class{constructor(e){this.bundler=e}async runSetup(e,t,n){let r=null;try{r=await this.bundler.bundle(e);let i=await import(`${r.outputPath}?t=${Date.now()}`),a=await this.getSetupFunction(i,t,e)(n);return{state:this.validateSetupResult(a,e),success:!0}}catch(t){return{state:{},success:!1,error:`Setup failed for "${e}": ${t instanceof Error?t.message:String(t)}`}}finally{r&&await r.cleanup()}}getSetupFunction(e,t,n){if(t in e&&typeof e[t]==`function`)return e[t];if(t===`default`&&`default`in e){let t=e.default;if(typeof t==`function`)return t;throw Error(`Default export in "${n}" is not a function`)}let r=Object.keys(e).filter(t=>typeof e[t]==`function`);throw r.length===0?Error(`No function exports found in "${n}"`):Error(`Export "${t}" not found in "${n}". Available functions: ${r.join(`, `)}`)}validateSetupResult(e,t){if(e==null)return{};if(typeof e!=`object`||Array.isArray(e))throw Error(`Setup function in "${t}" must return an object or undefined, got ${typeof e}`);return e}};Pr=M([(0,d.injectable)(),F(0,(0,d.inject)(A.SpecBundlerService)),j(`design:paramtypes`,[Object])],Pr);const Y=`[SpecBundler]`,Fr=`file://`,Ir=RegExp(`^@playwright\\/test$`),Lr=`stubs`,Rr=`playwright-test.mjs`,zr=`__PLAYWRIGHT_MCP_STUB_PATH__`,X={OUTDIR_NAME:`browse-tool-bundles`,PLUGIN_NAME:`playwright-test-alias`,EXTERNALS:[`playwright`,`playwright/test`,`playwright-core`]},Br={BUILD_FAILED:`SPEC_BUNDLER_BUILD_FAILED`,NO_OUTPUT:`SPEC_BUNDLER_NO_OUTPUT`,IO_FAILED:`SPEC_BUNDLER_IO_FAILED`},Z={UNEXPECTED_BUILD:`Unexpected build exception`,IO_MKDIR:`Failed to create output directory`,CLEANUP_FAILED:`Failed to clean up temporary file`};var Q=class extends Error{code=Br.BUILD_FAILED;recovery=`Check the spec file for syntax errors and ensure all imports are resolvable.`;constructor(e,t,n){super(`Failed to bundle spec "${(0,m.basename)(e)}": ${t}`,n),this.specPath=e,this.buildErrors=t,this.name=`SpecBundlerBuildError`}},Vr=class extends Error{code=Br.IO_FAILED;recovery=`Check filesystem permissions and available disk space.`;constructor(e,t,n){super(`${e} at "${t}"`,n),this.operation=e,this.targetPath=t,this.name=`SpecBundlerIoError`}};let Hr=class{stubPath;nodeModulesPath;constructor(){let e=(0,m.dirname)(require(`url`).pathToFileURL(__filename).href.replace(`file://`,``));this.stubPath=(0,m.join)(e,`stubs`,`playwright-test.mjs`),this.nodeModulesPath=this.findNodeModules(e)}findNodeModules(e){let t=e,n=(0,m.resolve)(`/`);for(;t!==n;){let e=(0,m.join)(t,`node_modules`);if((0,p.existsSync)((0,m.join)(e,`playwright`)))return e;t=(0,m.dirname)(t)}for(t=e;t!==n;){let e=(0,m.join)(t,`node_modules`);if((0,p.existsSync)(e))return e;t=(0,m.dirname)(t)}return(0,m.join)(e,`node_modules`)}async bundle(e){let t=(0,m.join)((0,C.tmpdir)(),X.OUTDIR_NAME);try{await(0,T.mkdir)(t,{recursive:!0})}catch(e){throw console.error(`${Y} ${Z.IO_MKDIR} "${t}":`,e),new Vr(Z.IO_MKDIR,t,{cause:e})}let n=(0,m.join)(t,`node_modules`);if(!(0,p.existsSync)(n))try{await(0,T.symlink)(this.nodeModulesPath,n,`junction`)}catch{}return this.bundleWithEsbuild(e,t)}async bundleWithEsbuild(e,t){let n=(0,m.basename)(e).replace(/\.[^.]+$/,``),r=this.stubPath;try{let i=await(0,re.build)({entryPoints:[e],outdir:t,bundle:!0,platform:`node`,format:`esm`,target:`node18`,banner:{js:`import { createRequire as __esbuildCreateRequire } from 'module'; const require = __esbuildCreateRequire(import.meta.url);`},external:[...X.EXTERNALS],define:{[zr]:JSON.stringify(r)},plugins:[{name:X.PLUGIN_NAME,setup(e){e.onResolve({filter:Ir},()=>({path:r}))}}],write:!0,logLevel:`silent`});if(i.errors.length>0){let t=i.errors.map(e=>e.text).join(`
10
- `);throw console.error(`${Y} Build failed for "${e}": ${t}`),new Q(e,t,{cause:Error(t)})}let a=(0,m.join)(t,`${n}.js`);return{outputPath:a,cleanup:()=>this.safeUnlink(a)}}catch(t){if(t instanceof Q)throw t;let n=t instanceof Error?t.message:Z.UNEXPECTED_BUILD;throw console.error(`${Y} Build failed for "${e}":`,t),new Q(e,n,{cause:t})}}async bundleWithHooks(e){let t=(0,m.join)((0,C.tmpdir)(),X.OUTDIR_NAME);try{await(0,T.mkdir)(t,{recursive:!0})}catch(e){throw console.error(`${Y} ${Z.IO_MKDIR} "${t}":`,e),new Vr(Z.IO_MKDIR,t,{cause:e})}let n=(0,m.join)(t,`node_modules`);if(!(0,p.existsSync)(n))try{await(0,T.symlink)(this.nodeModulesPath,n,`junction`)}catch{}return this.bundleSpecWithHooksEntry(e.specPath,e.hooksPath,t)}async bundleSpecWithHooksEntry(e,t,n){let r=(0,m.dirname)((0,m.resolve)(t)),i=this.stubPath,a=[`process.env.__HOOKS_SOURCE_DIR__ = ${JSON.stringify(r)};`,`import { setup as __hooksSetup } from ${JSON.stringify(t)};`,`await __hooksSetup();`,`delete process.env.__HOOKS_SOURCE_DIR__;`,`export * from ${JSON.stringify(e)};`].join(`
11
- `);try{let t=await(0,re.build)({stdin:{contents:a,resolveDir:(0,m.dirname)(e),loader:`ts`,sourcefile:`spec-with-hooks.ts`},outdir:n,bundle:!0,platform:`node`,format:`esm`,target:`node18`,banner:{js:`import { createRequire as __esbuildCreateRequire } from 'module'; const require = __esbuildCreateRequire(import.meta.url);`},external:[...X.EXTERNALS],define:{[zr]:JSON.stringify(i)},plugins:[{name:X.PLUGIN_NAME,setup(e){e.onResolve({filter:Ir},()=>({path:i}))}}],write:!0,logLevel:`silent`});if(t.errors.length>0){let n=t.errors.map(e=>e.text).join(`
12
- `);throw console.error(`${Y} Build failed for "${e}" (with hooks): ${n}`),new Q(e,n,{cause:Error(n)})}let r=(0,m.join)(n,`stdin.js`);return{outputPath:r,cleanup:()=>this.safeUnlink(r)}}catch(t){if(t instanceof Q)throw t;let n=t instanceof Error?t.message:Z.UNEXPECTED_BUILD;throw console.error(`${Y} Build failed for "${e}" (with hooks):`,t),new Q(e,n,{cause:t})}}async safeUnlink(e){try{await(0,T.unlink)(e)}catch(t){console.warn(`${Y} ${Z.CLEANUP_FAILED} "${e}":`,t)}}};Hr=M([(0,d.injectable)(),j(`design:paramtypes`,[])],Hr);let Ur=class{async discoverProjects(e){let t=e||process.cwd(),n=[],r=await this.findPlaywrightConfigs(t);for(let e of r){let t=(0,m.dirname)(e),r={name:(0,m.basename)(t),path:t,configPath:e,testDir:await this.getTestDirFromConfig(e),specs:[]};r.specs=await this.getProjectSpecs(t),n.push(r)}return n}async getProjectSpecs(e){let t=(0,m.join)(e,`playwright.config.ts`);if(!(0,p.existsSync)(t))throw Error(`No playwright.config.ts found in ${e}`);let n=(0,m.join)(e,await this.getTestDirFromConfig(t));if(!(0,p.existsSync)(n))return[];let r=[],i=await this.findSpecFiles(n);for(let t of i){let n=await this.getSpecInfo(t,e);r.push(n)}return r}async getSpecInfo(e,t){let n=(0,m.resolve)(e);if(!(0,p.existsSync)(n))throw Error(`Spec file not found: ${e}`);let r=(0,m.basename)(n);return{name:r,path:n,relativePath:t?(0,m.relative)(t,n):r,hasArgsSchema:await this.checkHasArgsSchema(n)}}async filterSpecs(e,t){let n=await this.discoverProjects(e),r=[];for(let e of n){if(t?.projectName&&e.name!==t.projectName)continue;let n=e.specs;if(t?.specPattern){let e=this.globToRegex(t.specPattern);n=n.filter(t=>e.test(t.name)||e.test(t.relativePath))}r=r.concat(n)}return r}async findPlaywrightConfigs(e){let t=[];return await this.walkDirectory(e,(e,n)=>{if(n){let t=(0,m.basename)(e);return!(t===`node_modules`||t.startsWith(`.`))}return(0,m.basename)(e)===`playwright.config.ts`&&t.push(e),!0}),t}async findSpecFiles(e){let t=[];return await this.walkDirectory(e,(e,n)=>n?(0,m.basename)(e)!==`node_modules`:(e.endsWith(`.spec.ts`)&&t.push(e),!0)),t}async walkDirectory(e,t){if(!(0,p.existsSync)(e))return;let n=await(0,T.readdir)(e,{withFileTypes:!0});for(let r of n){let n=(0,m.join)(e,r.name);r.isDirectory()?t(n,!0)&&await this.walkDirectory(n,t):t(n,!1)}}async getTestDirFromConfig(e){try{let t=(await(0,T.readFile)(e,`utf-8`)).match(/testDir:\s*['"`]([^'"`]+)['"`]/);if(t)return t[1].replace(/^\.\//,``)}catch{}return`tests`}async checkHasArgsSchema(e){try{let t=await(0,T.readFile)(e,`utf-8`);return/export\s+(const\s+)?argsSchema\b/.test(t)}catch{return!1}}globToRegex(e){let t=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`);return RegExp(`^${t}$`,`i`)}};Ur=M([(0,d.injectable)()],Ur);let Wr=class{constructor(e){this.bundler=e}async extractSpecMetadata(e){let t=await this.bundler.bundle(e);try{let e=await import(`${t.outputPath}?t=${Date.now()}`),n=e.argsSchema??null;return{argsSchema:n,envPrefix:e.envPrefix??null,hasDynamicArgs:n!==null}}catch{return{argsSchema:null,envPrefix:null,hasDynamicArgs:!1}}finally{await t.cleanup()}}async loadPlaywrightConfig(e){try{let t=await(0,T.readFile)(e,`utf-8`),n={},r=t.match(/baseURL:\s*['"`]([^'"`]+)['"`]/);r&&(n.baseURL=r[1]);let i=t.match(/export\s+const\s+mcpConfig\s*=\s*\{([^}]+)\}/s);if(i){let e=i[1],t=e.match(/setupFile:\s*['"`]([^'"`]+)['"`]/);t&&(n.setupFile=t[1]);let r=e.match(/setupExport:\s*['"`]([^'"`]+)['"`]/);r&&(n.setupExport=r[1])}let a=t.match(/webServer:\s*\{([^}]+(?:\{[^}]*\}[^}]*)*)\}/s);if(a){let e=a[1],t=e.match(/command:\s*['"`]([^'"`]+)['"`]/),r=e.match(/url:\s*['"`]([^'"`]+)['"`]/),i=e.match(/reuseExistingServer:\s*(true|false)/),o=e.match(/timeout:\s*(\d+)/),s=e.match(/cwd:\s*['"`]([^'"`]+)['"`]/);t&&r&&(n.webServer={command:t[1],url:r[1],reuseExistingServer:i?i[1]===`true`:void 0,timeout:o?Number.parseInt(o[1],10):void 0,cwd:s?s[1]:void 0})}return n}catch{return{}}}parseArgsFromEnv(e,t){let n={},r=t.toUpperCase();for(let[e,t]of Object.entries(process.env))if(e.startsWith(r)&&t!==void 0){let i=this.envKeyToFieldName(e.slice(r.length));n[i]=this.parseEnvValue(t)}try{return e.parse(n)}catch{return n}}envKeyToFieldName(e){return e.toLowerCase().split(`_`).map((e,t)=>t===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(``)}parseEnvValue(e){if(e.toLowerCase()===`true`)return!0;if(e.toLowerCase()===`false`)return!1;let t=Number(e);if(!Number.isNaN(t)&&e.trim()!==``)return t;if(e.startsWith(`{`)&&e.endsWith(`}`)||e.startsWith(`[`)&&e.endsWith(`]`))try{return JSON.parse(e)}catch{}return e}};Wr=M([(0,d.injectable)(),F(0,(0,d.inject)(A.SpecBundlerService)),j(`design:paramtypes`,[Object])],Wr);let Gr=class{constructor(e){this.bundler=e}async loadSpec(e,t){let n=t?await this.bundler.bundleWithHooks({specPath:e,hooksPath:t}):await this.bundler.bundle(e);try{c.c(e);let t=process,r=t.__pw_initiator__;return t.__pw_initiator__=void 0,await import(`${n.outputPath}?t=${Date.now()}`),t.__pw_initiator__=r,c.s()}catch(t){throw c.p(),Error(`Failed to load spec "${e}": ${t instanceof Error?t.message:String(t)}`,{cause:t})}finally{await n.cleanup()}}async executeSpec(e){let{specPath:t,page:n,context:r,browser:i,hooksPath:a}=e,o=Date.now(),s=[],l=0,u=0;try{let e=await this.loadSpec(t,a),d={page:n,context:r,browser:i,playwright:O.default};for(let t of e.allTests){let e=Date.now();try{await t.fn(d),s.push({title:t.title,fullTitle:t.fullTitle,passed:!0,error:null,duration:Date.now()-e}),l++}catch(n){if(n instanceof c.t)s.push({title:t.title,fullTitle:t.fullTitle,passed:!0,error:null,duration:Date.now()-e}),l++;else{let r=n instanceof Error?n.message:String(n);s.push({title:t.title,fullTitle:t.fullTitle,passed:!1,error:r,duration:Date.now()-e}),u++}}}return{specPath:t,totalTests:e.testCount,passed:l,failed:u,testResults:s,success:u===0,duration:Date.now()-o}}catch(e){return{specPath:t,totalTests:0,passed:0,failed:1,testResults:[{title:`Spec Loading`,fullTitle:`Failed to load: ${t}`,passed:!1,error:e instanceof Error?e.message:String(e),duration:Date.now()-o}],success:!1,duration:Date.now()-o}}}async executeSpecEnhanced(e){let{specPath:t,page:n,context:r,browser:i,testFilter:a,specArgs:o,hooksPath:s}=e,l=Date.now(),u=[],d=0,f=0;try{let e=await this.loadSpec(t,s),p=a?this.filterTests(e.allTests,a):e.allTests,m={page:n,context:r,browser:i,playwright:O.default,specArgs:o};for(let e of p){if(e.skip){u.push({title:e.title,fullTitle:e.fullTitle,passed:!0,error:null,duration:0}),d++;continue}let t=Date.now();try{await e.fn(m),u.push({title:e.title,fullTitle:e.fullTitle,passed:!0,error:null,duration:Date.now()-t}),d++}catch(n){if(n instanceof c.t)u.push({title:e.title,fullTitle:e.fullTitle,passed:!0,error:null,duration:Date.now()-t}),d++;else{let r=n instanceof Error?n.message:String(n);u.push({title:e.title,fullTitle:e.fullTitle,passed:!1,error:r,duration:Date.now()-t}),f++}}}return{specPath:t,totalTests:p.length,passed:d,failed:f,testResults:u,success:f===0,duration:Date.now()-l}}catch(e){return{specPath:t,totalTests:0,passed:0,failed:1,testResults:[{title:`Spec Loading`,fullTitle:`Failed to load: ${t}`,passed:!1,error:e instanceof Error?e.message:String(e),duration:Date.now()-l}],success:!1,duration:Date.now()-l}}}filterTests(e,t){let n=[...e];if(t.onlyMarked){let e=n.filter(e=>e.only);e.length>0&&(n=e)}if(t.testName&&(n=n.filter(e=>e.title===t.testName)),t.testPattern){let e=new RegExp(t.testPattern,`i`);n=n.filter(t=>e.test(t.fullTitle))}if(t.describeFilter){let e=new RegExp(t.describeFilter,`i`);n=n.filter(t=>e.test(t.fullTitle))}return n}};Gr=M([(0,d.injectable)(),F(0,(0,d.inject)(A.SpecBundlerService)),j(`design:paramtypes`,[Object])],Gr);let Kr=class{browsers=new Map;browserIdCounter=0;constructor(e,t,n){this.profileService=e,this.pageRegistry=t,this.lockManager=n}findChromePath(){let e=C.default.platform(),t={darwin:[`/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`,`/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary`,`${C.default.homedir()}/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`],win32:[`C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe`,`C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe`,`${process.env.LOCALAPPDATA}\\Google\\Chrome\\Application\\chrome.exe`],linux:[`/usr/bin/google-chrome`,`/usr/bin/google-chrome-stable`,`/usr/bin/chromium`,`/usr/bin/chromium-browser`,`/snap/bin/chromium`]},n=t[e]??t.linux;for(let e of n)if(p.default.existsSync(e))return e;return null}resolveExtensionPath(e){if(e&&p.default.existsSync(m.default.join(e,`manifest.json`)))return e;let t=m.default.dirname(new URL(require(`url`).pathToFileURL(__filename).href).pathname),n=[m.default.resolve(t,`../dist/extension`),m.default.resolve(t,`../../dist/extension`)];for(let e of n)if(p.default.existsSync(m.default.join(e,`manifest.json`)))return e;let r=m.default.resolve(process.cwd(),`dist/extension`);if(p.default.existsSync(m.default.join(r,`manifest.json`)))return r;throw Error(`Chrome extension not found. Build the extension first: pnpm build:extension`)}createUserDataDir(e){if(e){let t=m.default.join(this.profileService.getProfilesDir(),e,`stealth-user-data`);return p.default.mkdirSync(t,{recursive:!0}),t}let t=m.default.join(C.default.tmpdir(),`stealth-chrome-${Date.now()}`);return p.default.mkdirSync(t,{recursive:!0}),t}async launch(e={}){let t=this.findChromePath();if(!t)throw Error(`Chrome not found. Please install Google Chrome.
9
+ `)}async function Dn(e){let t=(0,ne.stripTypeScriptTypes)(await(0,w.readFile)(e,`utf8`),{mode:`strip`});return await import(`data:text/javascript;base64,${Buffer.from(t,`utf8`).toString(`base64`)}`)}var On=class{constructor(e=process.env.BROWSE_TOOL_SNIPPETS_DIR){this.snippetsDir=e}getDirectory(){return this.snippetsDir?m.default.resolve(this.snippetsDir):void 0}async listSnippets(){let e=this.requireDirectory();await(0,w.mkdir)(e,{recursive:!0});let t=await(0,w.readdir)(e,{withFileTypes:!0}),n=[];for(let r of t){if(!r.isFile()||!r.name.endsWith(`.ts`))continue;let t=r.name,i=await Dn(m.default.join(e,r.name)),a=typeof i.name==`string`&&i.name.trim().length>0?i.name:r.name.replace(/\.ts$/,``),o=typeof i.description==`string`?i.description:``;n.push({name:a,description:o,snippetPath:t})}return n.sort((e,t)=>e.name.localeCompare(t.name)),n}async loadSnippet(e){let t=await this.resolveSnippetPath(e),n=await Dn(t.filePath);if(typeof n.run!=`function`)throw Error(`Snippet "${t.snippetPath}" must export a "run" function`);return{name:typeof n.name==`string`&&n.name.trim().length>0?n.name:t.snippetPath.replace(/\.ts$/,``),description:typeof n.description==`string`?n.description:``,snippetPath:t.snippetPath,run:n.run}}async saveSnippet(e){let t=this.requireDirectory();await(0,w.mkdir)(t,{recursive:!0});let n=`${wn(e.name)}.ts`;return await(0,w.writeFile)(m.default.join(t,n),En(e),`utf8`),{name:e.name,description:e.description,snippetPath:n}}requireDirectory(){let e=this.getDirectory();if(!e)throw Error(`Snippet storage is not configured. Start browse-tool with --snippets-dir.`);return e}async resolveSnippetPath(e){let t=this.requireDirectory(),n=e.endsWith(`.ts`)?e:`${e}.ts`,r=m.default.resolve(t,n);if(!r.startsWith(`${t}${m.default.sep}`)&&r!==m.default.join(t,n))throw Error(`Snippet path must stay within the configured snippets directory`);if(!(await(0,w.stat)(r).catch(()=>null))?.isFile())throw Error(`Snippet "${e}" not found`);return{filePath:r,snippetPath:m.default.relative(t,r)}}};let kn=class{async locate(e,t){let n=await this.getFrameContext(e,t.frame),r=this.buildLocator(n,t);if(await r.count()===0)throw Error(`Element not found: ${this.describeSelector(t)}`);return r.first()}async locateAll(e,t){let n=await this.getFrameContext(e,t.frame);return this.buildLocator(n,t)}async waitForElement(e,t,n={}){let r=await this.getFrameContext(e,t.frame),i=this.buildLocator(r,t);return await i.waitFor({timeout:n.timeout??N,state:n.state??`visible`}),i.first()}async getFrameContext(e,t){return t?e.frameLocator(t):e}buildLocator(e,t){if(t.uid)return e.locator(`[data-uid="${t.uid}"]`);if(t.xpath)return e.locator(`xpath=${t.xpath}`);if(t.text)return e.locator(`text=${t.text}`);if(t.selector)return e.locator(t.selector);throw Error(`No selector provided. Specify one of: selector, xpath, text, or uid.`)}describeSelector(e){let t=[];return e.uid&&t.push(`uid="${e.uid}"`),e.selector&&t.push(`selector="${e.selector}"`),e.xpath&&t.push(`xpath="${e.xpath}"`),e.text&&t.push(`text="${e.text}"`),e.frame&&t.push(`frame="${e.frame}"`),t.length>0?t.join(`, `):`empty selector`}};kn=j([(0,d.injectable)()],kn);const An=process.env.BROWSE_TOOL_DEBUG_CUSTOM_TOOLS===`1`;function jn(e){return JSON.stringify(e,(e,t)=>typeof t==`string`&&t.length>240?`${t.slice(0,240)}...<trimmed>`:t)}function z(e,t){if(An){if(t){console.error(`[ExtensionPageProxy] ${e}`,t);return}console.error(`[ExtensionPageProxy] ${e}`)}}function Mn(e){return typeof e==`object`&&e&&`value`in e?e.value:e}let Nn=class{[c._]=!0;currentUrl=`about:blank`;defaultTimeoutMs=N;_pageId;_browserId;constructor(e){this.taskQueue=e}setTarget(e,t){this._pageId=e,this._browserId=t}get pageId(){return this._pageId}get browserId(){return this._browserId}async goto(e,t){let n=await this.executeTask(`browser_navigate`,{url:e,waitUntil:t?.waitUntil,timeout:t?.timeout});if(!n.success)throw Error(n.error??`Navigation failed`);this.currentUrl=e}async click(e,t){let n=await this.executeTask(`browser_click`,{selector:e,clickCount:t?.clickCount,delay:t?.delay,button:t?.button,modifiers:t?.modifiers});if(!n.success)throw Error(n.error??`Click failed on ${e}`)}async fill(e,t,n){let r=await this.executeTask(`browser_fill`,{selector:e,text:t,force:n?.force});if(!r.success)throw Error(r.error??`Fill failed on ${e}`)}async type(e,t,n){let r=await this.executeTask(`browser_type`,{selector:e,text:t,delay:n?.delay});if(!r.success)throw Error(r.error??`Type failed on ${e}`)}async press(e){let t=await this.executeTask(`browser_press_key`,{key:e});if(!t.success)throw Error(t.error??`Press key failed: ${e}`)}async hover(e){let t=await this.executeTask(`browser_hover`,{selector:e});if(!t.success)throw Error(t.error??`Hover failed on ${e}`)}async selectOption(e,t){let n=await this.executeTask(`browser_select`,{selector:e,values:Array.isArray(t)?t:[t]});if(!n.success)throw Error(n.error??`Select option failed on ${e}`)}async waitForSelector(e,t){let n=await this.executeTask(`browser_wait_for`,{selector:e,state:t?.state??`visible`,timeout:t?.timeout});if(!n.success)throw Error(n.error??`Wait for selector failed: ${e}`)}async waitForTimeout(e){let t=await this.executeTask(`browser_wait_for`,{timeout:e});if(!t.success)throw Error(t.error??`Wait for timeout failed`)}async screenshot(e){let t=await this.executeTask(`browser_screenshot`,{path:e?.path,fullPage:e?.fullPage,type:e?.type});if(!t.success)throw Error(t.error??`Screenshot failed`);return t.result?.path??``}async content(){let e=await this.executeTask(`browser_evaluate_script`,{script:`document.documentElement.outerHTML`});if(!e.success)throw Error(e.error??`Get content failed`);return Mn(e.result)??``}async title(){let e=await this.executeTask(`browser_evaluate_script`,{script:`document.title`});if(!e.success)throw Error(e.error??`Get title failed`);return Mn(e.result)??``}async textContent(e){return this.locator(e).textContent()}async innerText(e){return this.locator(e).innerText()}async inputValue(e){return this.locator(e).inputValue()}url(){return this.currentUrl}async evaluate(e,...t){let n=typeof e==`function`?`(${e.toString()})(${t.map(e=>JSON.stringify(e)).join(`,`)})`:e,r=await this.executeTask(`browser_evaluate_script`,{script:n});if(!r.success)throw Error(r.error??`Evaluate failed`);return Mn(r.result)}async getSnapshot(){let e=await this.executeTask(`browser_snapshot`,{});if(!e.success)throw Error(e.error??`Get snapshot failed`);let t=Mn(e.result);return typeof t==`string`?t:t==null?``:JSON.stringify(t,null,2)}getByRole(e,t){return new c.v(this,[{type:`role`,role:e,options:t}])}getByText(e,t){return new c.v(this,[{type:`text`,text:e,options:t}])}getByLabel(e,t){return new c.v(this,[{type:`label`,text:e,options:t}])}getByPlaceholder(e,t){return new c.v(this,[{type:`placeholder`,text:e,options:t}])}getByTestId(e){return new c.v(this,[{type:`testId`,testId:e}])}locator(e){return new c.v(this,[{type:`css`,selector:e}])}context(){return{clearCookies:async()=>{await this.clearStorageState()}}}async reload(e){let t=await this.executeTask(`browser_reload`,{waitUntil:e?.waitUntil,timeout:e?.timeout});if(!t.success)throw Error(t.error??`Reload failed`)}async currentUrlAsync(){let e=await this.evaluate(`window.location.href`);return e&&(this.currentUrl=e),this.currentUrl}async waitForResponse(e,t){let n=typeof e==`string`?{url:e}:e instanceof RegExp?{urlPattern:{source:e.source,flags:e.flags}}:null;if(!n)throw Error(`Extension mode only supports waitForResponse with a string or RegExp target`);let r=await this.executeTask(`browser_wait_for_response`,{...n,timeout:t?.timeout??this.defaultTimeoutMs});if(!r.success)throw Error(r.error??`Wait for response failed`)}async getStorageState(){let e=await this.executeTask(`browser_get_storage_state`,{});if(!e.success)throw Error(e.error??`Get storage state failed`);return e.result??{}}async clearStorageState(){let e=await this.executeTask(`browser_clear_storage_state`,{});if(!e.success)throw Error(e.error??`Clear storage state failed`)}async startRecording(){let e=await this.executeTask(`browser_start_recording`,{});if(!e.success)throw Error(e.error??`Start recording failed`)}async stopRecording(){let e=await this.executeTask(`browser_stop_recording`,{});if(!e.success)throw Error(e.error??`Stop recording failed`);return e.result?.videoBase64??``}async executeTask(e,t){if(!this._pageId||!this._browserId)return{success:!1,error:`Extension page proxy target is not initialized`};let n={...t,pageId:this._pageId};z(`Queueing extension task`,{tool:e,browserId:this._browserId,pageId:this._pageId,args:jn(n)});let r;try{r=await this.taskQueue.queueTask(e,n,this.defaultTimeoutMs,this._browserId)}catch(t){let n=t instanceof Error?t.message:String(t);return z(`Extension task threw before result`,{tool:e,browserId:this._browserId,pageId:this._pageId,error:n}),{success:!1,error:`Extension task "${e}" threw for page "${this._pageId}" in browser "${this._browserId}": ${n}`}}if(!r.success)return z(`Extension task returned unsuccessful result`,{tool:e,browserId:this._browserId,pageId:this._pageId,taskError:r.error??`Task failed`,taskResult:r}),{success:!1,error:r.error??`Extension task "${e}" failed for page "${this._pageId}" in browser "${this._browserId}"`};let i=r.result?.content?.[0];if(i?.type===`text`&&i.text)try{let t=JSON.parse(i.text);return z(`Extension task completed with JSON text result`,{tool:e,browserId:this._browserId,pageId:this._pageId}),{success:!0,result:t}}catch{return z(`Extension task completed with plain text result`,{tool:e,browserId:this._browserId,pageId:this._pageId,textPreview:i.text.slice(0,240)}),{success:!0,result:{value:i.text}}}return z(`Extension task completed with non-text result payload`,{tool:e,browserId:this._browserId,pageId:this._pageId,taskResult:r}),{success:!0,result:r.result}}};Nn=j([(0,d.injectable)(),P(0,(0,d.inject)(k.ExtensionTaskQueue)),A(`design:paramtypes`,[Object])],Nn);let Pn=class{sessions=new Map;browserIdToSessionId=new Map;sessionIdCounter=0;defaultStaleThresholdMs=6e4;register(e){let t=this.browserIdToSessionId.get(e.browserId);t&&(this.sessions.delete(t),this.browserIdToSessionId.delete(e.browserId));let n=`session-${++this.sessionIdCounter}-${Date.now()}`,r=new Date,i={id:n,browserId:e.browserId,tabId:e.tabId,currentUrl:e.url,createdAt:r,lastHeartbeatAt:r,controlMode:`manual`,handoffRequested:!1,metadata:e.metadata};return this.sessions.set(n,i),this.browserIdToSessionId.set(e.browserId,n),i}heartbeat(e){let t=this.sessions.get(e.sessionId);if(t)return t.lastHeartbeatAt=new Date,e.tabId!==void 0&&(t.tabId=e.tabId),e.url!==void 0&&(t.currentUrl=e.url),e.state&&(t.metadata={...t.metadata,...e.state}),t}requestHandoff(e){let t=this.sessions.get(e.sessionId);if(t)return t.handoffRequested=!0,e.pageState&&(t.currentUrl=e.pageState.url,t.metadata={...t.metadata,handoffReason:e.reason,handoffPageState:e.pageState}),t}acknowledgeHandoff(e){let t=this.sessions.get(e);if(!(!t||!t.handoffRequested))return t.handoffRequested=!1,t.controlMode=`ai`,t.activeSpecPath=void 0,t}getSession(e){return this.sessions.get(e)}getSessionByBrowserId(e){let t=this.browserIdToSessionId.get(e);if(t)return this.sessions.get(t)}listSessions(){return Array.from(this.sessions.values())}removeSession(e){let t=this.sessions.get(e);return t?(this.browserIdToSessionId.delete(t.browserId),this.sessions.delete(e),!0):!1}setControlMode(e,t){let n=this.sessions.get(e);if(n)return n.controlMode=t,n}setActiveSpec(e,t){let n=this.sessions.get(e);if(n)return n.activeSpecPath=t,t&&(n.controlMode=`spec`),n}cleanupStaleSessions(e=this.defaultStaleThresholdMs){let t=Date.now(),n=0;for(let[r,i]of this.sessions)t-i.lastHeartbeatAt.getTime()>e&&(this.browserIdToSessionId.delete(i.browserId),this.sessions.delete(r),n++);return n}};Pn=j([(0,d.injectable)()],Pn);let Fn=class{constructor(e,t,n){this.bundler=e,this.pageProxy=t,this.sessionRegistry=n}async loadSpec(e){let t=await this.bundler.bundle(e);try{c.c(e);let n=process,r=n.__pw_initiator__;return n.__pw_initiator__=void 0,await import(`${t.outputPath}?t=${Date.now()}`),n.__pw_initiator__=r,c.s()}catch(t){throw c.p(),Error(`Failed to load spec "${e}": ${t instanceof Error?t.message:String(t)}`,{cause:t})}finally{await t.cleanup()}}async executeSpec(e){let{specPath:t,sessionId:n,testFilter:r,specArgs:i,onHandoff:a}=e,o=Date.now(),s=[],c=0,l=0,u=!1;this.sessionRegistry.setActiveSpec(n,t);try{let e=await this.loadSpec(t),d=r?this.filterTests(e.allTests,r):e.allTests,f={page:this.pageProxy,requestHandoff:async e=>{if(!this.sessionRegistry.getSession(n))throw Error(`Session ${n} not found`);let t=await this.pageProxy.getSnapshot(),r=this.pageProxy.url();this.sessionRegistry.requestHandoff({sessionId:n,reason:e,pageState:{url:r,snapshot:t}}),u=!0,a&&await a(n)},specArgs:i};for(let e of d){if(e.skip){s.push({title:e.title,fullTitle:e.fullTitle,passed:!0,error:null,duration:0}),c++;continue}let t=this.sessionRegistry.getSession(n);if(t?.handoffRequested)break;let r=Date.now();try{await e.fn(f),s.push({title:e.title,fullTitle:e.fullTitle,passed:!0,error:null,duration:Date.now()-r,handoffTriggered:t?.handoffRequested}),c++}catch(t){let n=t instanceof Error?t.message:String(t);s.push({title:e.title,fullTitle:e.fullTitle,passed:!1,error:n,duration:Date.now()-r}),l++}}return{specPath:t,totalTests:d.length,passed:c,failed:l,testResults:s,success:l===0,duration:Date.now()-o,handoffOccurred:u,sessionId:n}}catch(e){return{specPath:t,totalTests:0,passed:0,failed:1,testResults:[{title:`Spec Loading`,fullTitle:`Failed to load: ${t}`,passed:!1,error:e instanceof Error?e.message:String(e),duration:Date.now()-o}],success:!1,duration:Date.now()-o,handoffOccurred:!1,sessionId:n}}finally{this.sessionRegistry.setActiveSpec(n,void 0)}}filterTests(e,t){let n=[...e];if(t.onlyMarked){let e=n.filter(e=>e.only);e.length>0&&(n=e)}if(t.testName&&(n=n.filter(e=>e.title===t.testName)),t.testPattern){let e=new RegExp(t.testPattern,`i`);n=n.filter(t=>e.test(t.fullTitle))}if(t.describeFilter){let e=new RegExp(t.describeFilter,`i`);n=n.filter(t=>e.test(t.fullTitle))}return n}};Fn=j([(0,d.injectable)(),P(0,(0,d.inject)(k.SpecBundlerService)),P(1,(0,d.inject)(k.ExtensionPageProxy)),P(2,(0,d.inject)(k.ExtensionSessionRegistry)),A(`design:paramtypes`,[Object,Object,Object])],Fn);const In=`localhost`,Ln=3200,Rn=`PLAYWRIGHT_HOST`,zn=`PLAYWRIGHT_PORT`;function B(){return process.env.PLAYWRIGHT_HOST?.trim()||`localhost`}function Bn(){let e=process.env[zn];if(!e)return Ln;let t=Number.parseInt(e,10);if(Number.isNaN(t)||t<=0||t>65535)throw Error(`Invalid ${zn} value: ${e}`);return t}function V(e=void 0,t){return`http://${typeof e==`string`?e:e?.host??B()}:${e&&typeof e!=`string`?e.port:t??Bn()}`}let Vn=class{baseUrl;defaultTimeout=N;constructor(){this.baseUrl=V()}setBaseUrl(e){this.baseUrl=e}getBaseUrl(){return this.baseUrl}async execute(e,t={}){let n=`${this.baseUrl}/execute`,r=new AbortController,i=setTimeout(()=>r.abort(),this.defaultTimeout);try{let a={tool:e,arguments:t},o=await fetch(n,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a),signal:r.signal});if(clearTimeout(i),!o.ok){let e=await o.text();return{content:[{type:`text`,text:`HTTP error ${o.status}: ${e}`}],isError:!0}}let s=await o.json();return s.success?s.result||{content:[{type:`text`,text:`No result returned`}]}:{content:[{type:`text`,text:s.error||s.result?.content?.[0]?.text||`Unknown error`}],isError:!0}}catch(e){return clearTimeout(i),e instanceof Error&&e.name===`AbortError`?{content:[{type:`text`,text:`Request timed out after ${this.defaultTimeout}ms`}],isError:!0}:{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}}async isHealthy(){try{let e=await fetch(`${this.baseUrl}/health`,{headers:{"Content-Type":`application/json`}});return e.ok?(await e.json()).status===`healthy`:!1}catch{return!1}}};Vn=j([(0,d.injectable)(),A(`design:paramtypes`,[])],Vn);let H=class{defaultTimeout=5e3;async check(e,t=this.defaultTimeout){try{let n=`${V(B(),e)}/health`,r=new AbortController,i=setTimeout(()=>r.abort(),t);try{let t=await fetch(n,{signal:r.signal,headers:{"Content-Type":`application/json`}});if(clearTimeout(i),!t.ok)return{healthy:!1,error:`HTTP error ${t.status}: ${t.statusText}`};let a=await t.json();return a.status===`healthy`?{healthy:!0,port:e,serviceName:a.service,browserCount:a.browsers?.count}:{healthy:!1,error:`Unexpected health status: ${a.status||`unknown`}`}}catch(e){return clearTimeout(i),e instanceof Error?e.name===`AbortError`?{healthy:!1,error:`Health check timed out after ${t}ms`}:`code`in e&&e.code===`ECONNREFUSED`?{healthy:!1,error:`Connection refused - server not running`}:{healthy:!1,error:`Network error: ${e.message}`}:{healthy:!1,error:`Unknown error: ${String(e)}`}}}catch(e){return{healthy:!1,error:e instanceof Error?e.message:String(e)}}}};H=j([(0,d.injectable)()],H);var Hn;const Un=(0,E.fileURLToPath)(require(`url`).pathToFileURL(__filename).href),Wn=m.dirname(Un),Gn=`PLAYWRIGHT_SKIP_DYNAMIC_TOOL_COMMANDS`,Kn=`1`,qn=[`pnpm-workspace.yaml`,`nx.json`,`.git`],U=`browse-tool-http`,Jn=`tool`,Yn=`service`,Xn=`http-serve`,Zn=3,Qn=1e4,$n=100,er=1e3,tr=`ESRCH`,nr=`SIGTERM`,rr=`SIGKILL`,ir=`--port`,ar=`--host`,or=`development`,sr=`node`,cr=`bun`,lr=`run`,ur=`cli.mjs`,dr=`cli.ts`,fr=`dist`,pr=`src`,mr=`HTTP_SERVER_STALE_ENTRY`,hr=`HTTP_SERVER_NOT_REGISTERED`,gr=`Server registered but not healthy`,_r=`No HTTP server registered`,vr=`Run ensureRunning() to start a fresh server or clean up stale entries.`,yr=`Call ensureRunning() to discover or spawn a server.`,br=`No matching registry entry`,xr=`No matching process entry`,W=`[HttpServerManager]`;var Sr=class extends Error{code=`HTTP_SERVER_PORT_ERROR`;recovery=`Check if other services are occupying ports in the configured range.`;constructor(e,t){super(e,t),this.name=`HttpServerPortError`}},G=class extends Error{code=`HTTP_SERVER_STARTUP_ERROR`;recovery=`Check server logs, ensure CLI binary exists, and verify port availability.`;constructor(e,t){super(e,t),this.name=`HttpServerStartupError`}},Cr=class extends Error{code=`HTTP_SERVER_STOP_ERROR`;recovery=`Manually kill the process and clean up the port registry.`;causes;constructor(e,t=[],n){super(e,n),this.name=`HttpServerStopError`,this.causes=t}};async function K(e){try{return await w.access(e),!0}catch(e){if(e instanceof Error&&`code`in e&&e.code===`ENOENT`)return!1;throw e}}async function wr(e=process.cwd()){let t=m.resolve(e);for(;;){for(let e of qn)if(await K(m.join(t,e)))return t;let e=m.dirname(t);if(e===t)return process.cwd();t=e}}let Tr=class{repositoryPath;environment;host;constructor(e,t,n=new C.ProcessRegistryService(process.env.PROCESS_REGISTRY_PATH)){this.healthCheck=e,this.portRegistry=t,this.processRegistry=n,this.environment=process.env.NODE_ENV||`development`,this.host=B()}async getRepositoryPath(){return this.repositoryPath||=await wr(process.cwd()),this.repositoryPath}buildErrorStatus(e){return{running:!1,error:e instanceof Error?e.message:String(e),errorCode:e instanceof Error&&`code`in e?e.code:void 0,errorRecovery:e instanceof Error&&`recovery`in e?e.recovery:void 0,errorCause:e instanceof Error&&e.cause instanceof Error?e.cause.message:void 0}}async listServiceEntries(){return this.portRegistry.listAllocations({serviceName:U,serviceType:Jn,environment:this.environment})}async releaseEntry(e){if(e.pid){let t=await this.processRegistry.releaseProcess({repositoryPath:e.repositoryPath,serviceName:U,serviceType:`service`,environment:e.environment,pid:e.pid,kill:!1,releasePort:!1});!t.success&&!t.error?.includes(`No matching process entry`)&&console.error(`${W} Failed to release process entry for port ${e.port}: ${t.error}`)}let t=await this.portRegistry.releasePort({repositoryPath:e.repositoryPath,serviceName:U,serviceType:Jn,environment:e.environment,pid:e.pid});!t.success&&!t.error?.includes(`No matching registry entry`)&&console.error(`${W} Failed to release entry for port ${e.port}: ${t.error}`)}async discoverHealthyService(){let e=await this.listServiceEntries();for(let t of e)try{let e=await this.healthCheck.check(t.port);if(e.healthy&&e.serviceName===U)return{entry:t,browserCount:e.browserCount}}catch(e){console.error(`${W} Health check threw for port ${t.port}: ${e instanceof Error?e.message:String(e)}`)}return null}async discoverHealthyServiceOnPort(e){let t=await this.findRegistrationByPort(e);if(!t)return null;try{let n=await this.healthCheck.check(e);if(n.healthy&&n.serviceName===U)return{entry:t,browserCount:n.browserCount}}catch(t){console.error(`${W} Health check threw for requested port ${e}: ${t instanceof Error?t.message:String(t)}`)}return null}async cleanupStaleEntries(){let e=await this.listServiceEntries(),t=[];for(let n of e)try{let e;try{e=await this.healthCheck.check(n.port)}catch(e){console.error(`${W} Health check threw for port ${n.port}, skipping cleanup: ${e instanceof Error?e.message:String(e)}`);continue}e.healthy&&e.serviceName===U||(n.pid&&await this.killProcess(n.pid),await this.releaseEntry(n))}catch(e){let r=`Failed to clean up entry on port ${n.port}: ${e instanceof Error?e.message:String(e)}`;console.error(`${W} ${r}`),t.push(r)}t.length>0&&console.error(`${W} ${t.length} entry cleanup failure(s) during stale entry removal`)}async findRegistrationByPort(e){return(await this.listServiceEntries()).find(t=>t.port===e)??null}async findAvailablePort(e){let t=await this.getRepositoryPath(),n=await this.portRegistry.findAvailablePort({repositoryPath:t,serviceName:U,serviceType:Jn,environment:this.environment,host:this.host,preferredPort:e});if(!n.success||!n.port)throw new Sr(`No available port found from ${e}: ${n.error}`);return n.port}async ensureExactPortAvailable(e){let t=await this.findAvailablePort(e);if(t!==e)throw new Sr(`Requested port ${e} is unavailable; next available port is ${t}`)}async resolveCliCommand(e){let t=m.resolve(Wn,ur),n=m.resolve(Wn,`..`,dr),r=[`--port`,e.toString(),`--host`,this.host];if(await K(t))return[sr,[t,Xn,...r]];if(await K(n))return[`bun`,[`run`,n,Xn,...r]];let i=m.resolve(Wn,`..`,`..`),a=m.join(i,`dist`,ur),o=m.join(i,`src`,dr);if(await K(a))return[sr,[a,Xn,...r]];if(await K(o))return[`bun`,[`run`,o,Xn,...r]];throw new G(`Cannot find CLI at ${t}, ${n}, ${a}, or ${o}`)}async startHttpServer(e){let[t,n]=await this.resolveCliCommand(e),r=(0,T.spawn)(t,n,{detached:!0,stdio:`ignore`,env:{...process.env,NODE_ENV:this.environment,PLAYWRIGHT_SKIP_DYNAMIC_TOOL_COMMANDS:`1`}}),i=await new Promise(e=>{let t=setTimeout(()=>{r.removeAllListeners(`error`),e(null)},100);r.once(`error`,n=>{clearTimeout(t),e(n)})});if(i)throw new G(`Failed to spawn HTTP server process: ${i.message}`,{cause:i});r.unref();let a=r.pid;if(!a)throw new G(`Failed to spawn HTTP server - no PID returned`);return a}async killProcess(e){try{process.kill(e,0),process.kill(e,`SIGTERM`)}catch(t){if((t instanceof Error&&`code`in t?t.code:void 0)===tr){console.error(`${W} Process ${e} does not exist — skipping kill`);return}throw t}await new Promise(e=>setTimeout(e,1e3));try{process.kill(e,0),process.kill(e,`SIGKILL`)}catch(t){if((t instanceof Error&&`code`in t?t.code:void 0)===tr){console.error(`${W} Process ${e} exited after SIGTERM`);return}throw t}}async cleanupFailedSpawn(e,t){await this.killProcess(e);let n=await this.findRegistrationByPort(t);n&&n.pid===e&&await this.releaseEntry(n)}async attemptSpawn(e){let t=await this.findAvailablePort(e),n=await this.startHttpServer(t);await new Promise(e=>setTimeout(e,1e4));let r;try{r=await this.healthCheck.check(t)}catch(e){let r=e instanceof Error?e.message:String(e);return console.error(`${W} Health check threw on port ${t}: ${r}`),await this.cleanupFailedSpawn(n,t),{success:!1,reason:`health_check_error`,port:t,error:r}}if(!r.healthy)return await this.cleanupFailedSpawn(n,t),{success:!1,reason:`health_check_failed`,port:t,error:r.error};if(r.serviceName!==U)return await this.cleanupFailedSpawn(n,t),{success:!1,reason:`service_name_mismatch`,port:t,error:`Expected ${U}, got ${r.serviceName}`};let i=await this.findRegistrationByPort(t);return!i||i.pid!==n?(console.error(`${W} Ownership mismatch on port ${t}: expected pid ${n}, found ${i?.pid}`),await this.cleanupFailedSpawn(n,t),{success:!1,reason:`ownership_mismatch`,port:t}):(console.error(`${W} Server self-registered on port ${t} (pid: ${i.pid})`),{success:!0,port:t,pid:n,browserCount:r.browserCount})}async ensureRunning(e=Bn(),t={}){try{if(t.exactPort){let t=await this.discoverHealthyServiceOnPort(e);if(t)return{running:!0,port:t.entry.port,pid:t.entry.pid,browserCount:t.browserCount,spawned:!1};await this.cleanupStaleEntries(),await this.ensureExactPortAvailable(e);let n=await this.attemptSpawn(e);if(n.success)return{running:!0,port:n.port,pid:n.pid,browserCount:n.browserCount,spawned:!0};let r=new G(`Failed to start browse-tool HTTP server on requested port ${e}: ${n.reason}`);return this.buildErrorStatus(r)}let n=await this.discoverHealthyService();if(n)return{running:!0,port:n.entry.port,pid:n.entry.pid,browserCount:n.browserCount,spawned:!1};await this.cleanupStaleEntries();let r=e;for(let e=0;e<3;e+=1){let t=await this.attemptSpawn(r);if(t.success)return{running:!0,port:t.port,pid:t.pid,browserCount:t.browserCount,spawned:!0};console.error(`${W} Spawn attempt ${e+1} failed: ${t.reason} on port ${t.port}`),r=t.port+1}let i=new G(`Failed to start browse-tool HTTP server after 3 attempts`);return this.buildErrorStatus(i)}catch(e){return this.buildErrorStatus(e)}}async stop(){let e=await this.listServiceEntries();if(e.length===0)return!1;let t=[];for(let n of e)try{n.pid&&await this.killProcess(n.pid),await this.releaseEntry(n)}catch(e){let r=e instanceof Error?e:Error(`Failed to stop entry on port ${n.port}: ${String(e)}`);console.error(`${W} ${r.message}`),t.push(r)}if(t.length>0){let n=t.map(e=>e.message);throw new Cr(`Failed to stop ${t.length} of ${e.length} server(s): ${n.join(`; `)}`,t,{cause:t[0]})}return!0}async getStatus(){try{let e=await this.discoverHealthyService();if(e)return{running:!0,port:e.entry.port,pid:e.entry.pid,browserCount:e.browserCount};let t=await this.listServiceEntries();if(t.length>0){let e=t[0];return{running:!1,port:e.port,pid:e.pid,error:`Server registered but not healthy`,errorCode:`HTTP_SERVER_STALE_ENTRY`,errorRecovery:`Run ensureRunning() to start a fresh server or clean up stale entries.`}}return{running:!1,error:`No HTTP server registered`,errorCode:`HTTP_SERVER_NOT_REGISTERED`,errorRecovery:`Call ensureRunning() to discover or spawn a server.`}}catch(e){return this.buildErrorStatus(e)}}};Tr=j([(0,d.injectable)(),P(0,(0,d.inject)(k.HttpServerHealthCheck)),P(1,(0,d.inject)(k.PortRegistryService)),P(2,(0,d.inject)(k.ProcessRegistryService)),A(`design:paramtypes`,[Object,Object,typeof(Hn=C.ProcessRegistryService!==void 0&&C.ProcessRegistryService)==`function`?Hn:Object])],Tr);const Er=900*1e3,Dr=1800*1e3,Or=60*1e3,kr=`PLAYWRIGHT_BROWSER_IDLE_TIMEOUT_MINUTES`;function Ar(){let e=process.env[kr];if(!e)return Dr;let t=Number.parseFloat(e);return!Number.isFinite(t)||t<=0?Dr:Math.round(t*60*1e3)}let jr=class{intervalId=null;browserIdleTimeoutMs=Ar();constructor(e,t){this.browserService=e,this.pageRegistry=t}start(){this.intervalId||(this.intervalId=setInterval(()=>{this.cleanup().catch(e=>{console.warn(`[IdleCleanup] Error during cleanup:`,e)})},6e4),this.intervalId&&typeof this.intervalId==`object`&&`unref`in this.intervalId&&this.intervalId.unref(),console.warn(`[IdleCleanup] Started (page timeout: ${Er/6e4}min, browser timeout: ${this.browserIdleTimeoutMs/6e4}min)`))}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null,console.warn(`[IdleCleanup] Stopped`))}async cleanup(){let e=Date.now();await this.cleanupIdlePages(e),await this.cleanupIdleBrowsers(e)}async cleanupIdlePages(e){let t=this.pageRegistry.list();for(let n of t){let t=e-n.lastAccessedAt.getTime();if(!(t<Er)){console.warn(`[IdleCleanup] Closing idle page "${n.id}" (idle ${Math.round(t/6e4)}min)`);try{if(n.page)await n.page.close();else{let e=this.browserService.getBrowser(n.browserId);if(e&&(e.pageIds.delete(n.id),e.currentPageId===n.id)){let t=Array.from(e.pageIds);e.currentPageId=t.length>0?t[0]:null}this.pageRegistry.remove(n.id)}}catch(e){console.warn(`[IdleCleanup] Failed to close page "${n.id}":`,e)}}}}async cleanupIdleBrowsers(e){let t=this.browserService.listBrowsers();for(let n of t){let t=n.specOrigin?Er:this.browserIdleTimeoutMs,r=e-n.lastAccessedAt.getTime();if(!(r<t)){console.warn(`[IdleCleanup] Closing idle browser "${n.id}" (idle ${Math.round(r/6e4)}min)`);try{await this.browserService.closeBrowser(n.id)}catch(e){console.warn(`[IdleCleanup] Failed to close browser "${n.id}":`,e)}}}}};jr=j([(0,d.injectable)(),P(0,(0,d.inject)(k.BrowserService)),P(1,(0,d.inject)(k.PageRegistry)),A(`design:paramtypes`,[Object,Object])],jr);let q=class{browsers=new Map;pages=new Map;trackBrowser(e,t){this.browsers.has(e)||this.browsers.set(e,{browserId:e,mode:t,createdAt:new Date,pageIds:new Set})}trackPage(e,t,n){if(this.pages.has(e))return;this.pages.set(e,{pageId:e,browserId:t,url:n,createdAt:new Date});let r=this.browsers.get(t);r&&r.pageIds.add(e)}untrackBrowser(e){let t=this.browsers.get(e);if(t){for(let e of t.pageIds)this.pages.delete(e);this.browsers.delete(e)}}untrackPage(e){let t=this.pages.get(e);if(t){let n=this.browsers.get(t.browserId);n&&n.pageIds.delete(e),this.pages.delete(e)}}getBrowserIds(){return Array.from(this.browsers.keys())}getPageIds(){return Array.from(this.pages.keys())}getPageIdsForBrowser(e){let t=this.browsers.get(e);return t?Array.from(t.pageIds):[]}getSessionState(){return{browsers:Array.from(this.browsers.values()).map(e=>({browserId:e.browserId,mode:e.mode,createdAt:e.createdAt.toISOString(),pageIds:Array.from(e.pageIds)})),pages:Array.from(this.pages.values()).map(e=>({pageId:e.pageId,browserId:e.browserId,url:e.url,createdAt:e.createdAt.toISOString()})),totalBrowsers:this.browsers.size,totalPages:this.pages.size}}clear(){this.browsers.clear(),this.pages.clear()}};q=j([(0,d.injectable)()],q);let Mr=class{pageStates=new Map;pageInstances=new Map;startMonitoring(e,t){this.stopMonitoring(e);let n={networkRequests:new Map,consoleMessages:[],requestCounter:0,messageCounter:0,listeners:{}};n.listeners.request=e=>{let t=`req-${++n.requestCounter}`,r={id:t,url:e.url(),method:e.method(),resourceType:e.resourceType(),headers:e.headers(),postData:e.postData()??void 0,timestamp:new Date};n.networkRequests.set(t,r)},n.listeners.response=e=>{let t=e.request();for(let[,r]of n.networkRequests)if(r.url===t.url()&&!r.response){r.response={status:e.status(),statusText:e.statusText(),headers:e.headers(),timing:e.request().timing().responseEnd};break}},n.listeners.console=e=>{let t=`msg-${++n.messageCounter}`,r=e.location(),i={id:t,type:e.type(),text:e.text(),location:r.url?{url:r.url,lineNumber:r.lineNumber,columnNumber:r.columnNumber}:void 0,timestamp:new Date};n.consoleMessages.push(i)},t.on(`request`,n.listeners.request),t.on(`response`,n.listeners.response),t.on(`console`,n.listeners.console),this.pageStates.set(e,n),this.pageInstances.set(e,t),t.once(`close`,()=>{this.stopMonitoring(e)})}stopMonitoring(e){let t=this.pageStates.get(e),n=this.pageInstances.get(e);t&&n&&(t.listeners.request&&n.off(`request`,t.listeners.request),t.listeners.response&&n.off(`response`,t.listeners.response),t.listeners.console&&n.off(`console`,t.listeners.console)),this.pageStates.delete(e),this.pageInstances.delete(e)}getNetworkRequests(e){let t=this.pageStates.get(e);return t?Array.from(t.networkRequests.values()):[]}getNetworkRequest(e,t){let n=this.pageStates.get(e);if(n)return n.networkRequests.get(t)}getConsoleMessages(e,t){let n=this.pageStates.get(e);return n?t?n.consoleMessages.filter(e=>e.type===t):[...n.consoleMessages]:[]}clearData(e){let t=this.pageStates.get(e);t&&(t.networkRequests.clear(),t.consoleMessages=[],t.requestCounter=0,t.messageCounter=0)}};Mr=j([(0,d.injectable)()],Mr);let Nr=class{pages=new Map;pageIdCounter=0;constructor(e){this.webSocketHub=e}async register(e){let{page:t,browser:n,context:r,browserId:i,profileName:a,mode:o,onClose:s}=e,c=`page-${++this.pageIdCounter}`,l={id:c,mode:o??`playwright`,page:t,browser:n,context:r,browserId:i,url:t.url(),title:await t.title(),profileName:a,createdAt:new Date,lastAccessedAt:new Date,onClose:s};return this.pages.set(c,l),t.once(`close`,()=>{try{s?.(c)}catch{}this.remove(c)}),c}registerExtensionPage(e,t,n,r=!0){let i=`page-${++this.pageIdCounter}`,a={id:i,mode:`extension`,page:void 0,browser:void 0,context:void 0,browserId:e,url:n??`about:blank`,title:`Extension Tab`,extensionTabId:t,createdAt:new Date,lastAccessedAt:new Date};return this.pages.set(i,a),r&&this.webSocketHub?.broadcastPageCreated(e,i,n),i}get(e){return this.pages.get(e)}remove(e){let t=this.pages.get(e);t&&(this.pages.delete(e),t.mode===`extension`&&this.webSocketHub?.broadcastPageRemoved(t.browserId,e))}list(){return Array.from(this.pages.values())}findByBrowser(e){return this.list().filter(t=>t.browserId===e)}findByProfile(e){return this.list().filter(t=>t.profileName===e)}touchPage(e){let t=this.pages.get(e);t&&(t.lastAccessedAt=new Date)}async updateMetadata(e){let t=this.get(e);t&&t.page&&(t.url=t.page.url(),t.title=await t.page.title())}clear(){this.pages.clear(),this.pageIdCounter=0}};Nr=j([(0,d.injectable)(),P(0,(0,d.inject)(k.WebSocketHub)),P(0,(0,d.optional)()),A(`design:paramtypes`,[Object])],Nr);let Pr=class{pauseStates=new Map;getOrCreateState(e){let t=this.pauseStates.get(e);return t||(t={isPaused:!1,stepName:null,reason:null,pausedAt:null,resolver:null},this.pauseStates.set(e,t)),t}pause(e,t,n){let r=this.getOrCreateState(e);if(r.isPaused)throw Error(`Session "${e}" is already paused at step "${r.stepName}"`);return r.isPaused=!0,r.stepName=t,r.reason=n??null,r.pausedAt=new Date,new Promise(e=>{r.resolver=e})}resume(e){let t=this.pauseStates.get(e);if(!t||!t.isPaused)return!1;let n=t.resolver;return t.isPaused=!1,t.stepName=null,t.reason=null,t.pausedAt=null,t.resolver=null,n&&n(),!0}waitForResume(e){let t=this.pauseStates.get(e);return!t||!t.isPaused||!t.resolver?Promise.resolve():new Promise(e=>{let n=t.resolver;t.resolver=()=>{n&&n(),e()}})}getStatus(e){let t=this.pauseStates.get(e);return{sessionId:e,isPaused:t?.isPaused??!1,stepName:t?.stepName??null,reason:t?.reason??null,pausedAt:t?.pausedAt??null}}isPaused(e){return this.pauseStates.get(e)?.isPaused??!1}clear(e){let t=this.pauseStates.get(e);t?.resolver&&t.resolver(),this.pauseStates.delete(e)}};Pr=j([(0,d.injectable)()],Pr);let Fr=class{profilesDir;constructor(){this.profilesDir=process.env.PLAYWRIGHT_PROFILES_DIR||(0,m.join)((0,x.homedir)(),`.browse-tool`,`profiles`)}getProfilesDir(){return this.profilesDir}getProfileDir(e){return(0,m.join)(this.getProfilesDir(),e)}getProfilePath(e){return(0,m.join)(this.getProfileDir(e),`profile.json`)}getStorageStatePath(e){return(0,m.join)(this.getProfileDir(e),`storage-state.json`)}async ensureProfilesDir(){let e=this.getProfilesDir();(0,p.existsSync)(e)||await(0,w.mkdir)(e,{recursive:!0})}async list(){await this.ensureProfilesDir();let e=await(0,w.readdir)(this.getProfilesDir(),{withFileTypes:!0}),t=[];for(let n of e)if(n.isDirectory()){let e=await this.get(n.name);e&&t.push(e)}return t}async get(e){let t=this.getProfilePath(e);if(!(0,p.existsSync)(t))return null;let n=await(0,w.readFile)(t,`utf-8`);return JSON.parse(n)}async create(e){if(await this.get(e.name))throw Error(`Profile "${e.name}" already exists`);await(0,w.mkdir)(this.getProfileDir(e.name),{recursive:!0});let t=new Date().toISOString(),n={...e,createdAt:t,updatedAt:t};return await(0,w.writeFile)(this.getProfilePath(e.name),JSON.stringify(n,null,2)),n}async update(e,t){let n=await this.get(e);if(!n)throw Error(`Profile "${e}" not found`);let r={...n,...t,name:n.name,createdAt:n.createdAt,updatedAt:new Date().toISOString()};return await(0,w.writeFile)(this.getProfilePath(e),JSON.stringify(r,null,2)),r}async delete(e){if(!await this.get(e))throw Error(`Profile "${e}" not found`);await(0,w.rm)(this.getProfileDir(e),{recursive:!0})}async saveStorageState(e,t){if(!await this.get(e))throw Error(`Profile "${e}" not found`);await(0,w.writeFile)(this.getStorageStatePath(e),JSON.stringify(t,null,2))}async loadStorageState(e){let t=this.getStorageStatePath(e);if(!(0,p.existsSync)(t))return null;let n=await(0,w.readFile)(t,`utf-8`);return JSON.parse(n)}};Fr=j([(0,d.injectable)(),A(`design:paramtypes`,[])],Fr);let Ir=class{constructor(e){this.httpClient=e}async execute(e,t={}){return this.httpClient.execute(e,t)}async isServerAvailable(){return this.httpClient.isHealthy()}setServerPort(e){this.httpClient.setBaseUrl(V(void 0,e))}async listTools(){let e=this.httpClient.getBaseUrl(),t=await fetch(`${e}/tools`);if(!t.ok)throw Error(`Failed to list tools: ${t.statusText}`);let n=await t.json();if(n.error)throw Error(n.error);return n.tools}};Ir=j([(0,d.injectable)(),P(0,(0,d.inject)(k.HttpBrowserClient)),A(`design:paramtypes`,[Object])],Ir);let Lr=class{constructor(e){this.bundler=e}async runSetup(e,t,n){let r=null;try{r=await this.bundler.bundle(e);let i=await import(`${r.outputPath}?t=${Date.now()}`),a=await this.getSetupFunction(i,t,e)(n);return{state:this.validateSetupResult(a,e),success:!0}}catch(t){return{state:{},success:!1,error:`Setup failed for "${e}": ${t instanceof Error?t.message:String(t)}`}}finally{r&&await r.cleanup()}}getSetupFunction(e,t,n){if(t in e&&typeof e[t]==`function`)return e[t];if(t===`default`&&`default`in e){let t=e.default;if(typeof t==`function`)return t;throw Error(`Default export in "${n}" is not a function`)}let r=Object.keys(e).filter(t=>typeof e[t]==`function`);throw r.length===0?Error(`No function exports found in "${n}"`):Error(`Export "${t}" not found in "${n}". Available functions: ${r.join(`, `)}`)}validateSetupResult(e,t){if(e==null)return{};if(typeof e!=`object`||Array.isArray(e))throw Error(`Setup function in "${t}" must return an object or undefined, got ${typeof e}`);return e}};Lr=j([(0,d.injectable)(),P(0,(0,d.inject)(k.SpecBundlerService)),A(`design:paramtypes`,[Object])],Lr);const J=`[SpecBundler]`,Rr=`file://`,zr=RegExp(`^@playwright\\/test$`),Br=`stubs`,Vr=`playwright-test.mjs`,Hr=`__PLAYWRIGHT_MCP_STUB_PATH__`,Y={OUTDIR_NAME:`browse-tool-bundles`,PLUGIN_NAME:`playwright-test-alias`,EXTERNALS:[`playwright`,`playwright/test`,`playwright-core`]},Ur={BUILD_FAILED:`SPEC_BUNDLER_BUILD_FAILED`,NO_OUTPUT:`SPEC_BUNDLER_NO_OUTPUT`,IO_FAILED:`SPEC_BUNDLER_IO_FAILED`},X={UNEXPECTED_BUILD:`Unexpected build exception`,IO_MKDIR:`Failed to create output directory`,CLEANUP_FAILED:`Failed to clean up temporary file`};var Z=class extends Error{code=Ur.BUILD_FAILED;recovery=`Check the spec file for syntax errors and ensure all imports are resolvable.`;constructor(e,t,n){super(`Failed to bundle spec "${(0,m.basename)(e)}": ${t}`,n),this.specPath=e,this.buildErrors=t,this.name=`SpecBundlerBuildError`}},Wr=class extends Error{code=Ur.IO_FAILED;recovery=`Check filesystem permissions and available disk space.`;constructor(e,t,n){super(`${e} at "${t}"`,n),this.operation=e,this.targetPath=t,this.name=`SpecBundlerIoError`}};let Gr=class{stubPath;nodeModulesPath;constructor(){let e=(0,m.dirname)(require(`url`).pathToFileURL(__filename).href.replace(`file://`,``));this.stubPath=(0,m.join)(e,`stubs`,`playwright-test.mjs`),this.nodeModulesPath=this.findNodeModules(e)}findNodeModules(e){let t=e,n=(0,m.resolve)(`/`);for(;t!==n;){let e=(0,m.join)(t,`node_modules`);if((0,p.existsSync)((0,m.join)(e,`playwright`)))return e;t=(0,m.dirname)(t)}for(t=e;t!==n;){let e=(0,m.join)(t,`node_modules`);if((0,p.existsSync)(e))return e;t=(0,m.dirname)(t)}return(0,m.join)(e,`node_modules`)}async bundle(e){let t=(0,m.join)((0,x.tmpdir)(),Y.OUTDIR_NAME);try{await(0,w.mkdir)(t,{recursive:!0})}catch(e){throw console.error(`${J} ${X.IO_MKDIR} "${t}":`,e),new Wr(X.IO_MKDIR,t,{cause:e})}let n=(0,m.join)(t,`node_modules`);if(!(0,p.existsSync)(n))try{await(0,w.symlink)(this.nodeModulesPath,n,`junction`)}catch{}return this.bundleWithEsbuild(e,t)}async bundleWithEsbuild(e,t){let n=(0,m.basename)(e).replace(/\.[^.]+$/,``),r=this.stubPath;try{let i=await(0,re.build)({entryPoints:[e],outdir:t,bundle:!0,platform:`node`,format:`esm`,target:`node18`,banner:{js:`import { createRequire as __esbuildCreateRequire } from 'module'; const require = __esbuildCreateRequire(import.meta.url);`},external:[...Y.EXTERNALS],define:{[Hr]:JSON.stringify(r)},plugins:[{name:Y.PLUGIN_NAME,setup(e){e.onResolve({filter:zr},()=>({path:r}))}}],write:!0,logLevel:`silent`});if(i.errors.length>0){let t=i.errors.map(e=>e.text).join(`
10
+ `);throw console.error(`${J} Build failed for "${e}": ${t}`),new Z(e,t,{cause:Error(t)})}let a=(0,m.join)(t,`${n}.js`);return{outputPath:a,cleanup:()=>this.safeUnlink(a)}}catch(t){if(t instanceof Z)throw t;let n=t instanceof Error?t.message:X.UNEXPECTED_BUILD;throw console.error(`${J} Build failed for "${e}":`,t),new Z(e,n,{cause:t})}}async bundleWithHooks(e){let t=(0,m.join)((0,x.tmpdir)(),Y.OUTDIR_NAME);try{await(0,w.mkdir)(t,{recursive:!0})}catch(e){throw console.error(`${J} ${X.IO_MKDIR} "${t}":`,e),new Wr(X.IO_MKDIR,t,{cause:e})}let n=(0,m.join)(t,`node_modules`);if(!(0,p.existsSync)(n))try{await(0,w.symlink)(this.nodeModulesPath,n,`junction`)}catch{}return this.bundleSpecWithHooksEntry(e.specPath,e.hooksPath,t)}async bundleSpecWithHooksEntry(e,t,n){let r=(0,m.dirname)((0,m.resolve)(t)),i=this.stubPath,a=[`process.env.__HOOKS_SOURCE_DIR__ = ${JSON.stringify(r)};`,`import { setup as __hooksSetup } from ${JSON.stringify(t)};`,`await __hooksSetup();`,`delete process.env.__HOOKS_SOURCE_DIR__;`,`export * from ${JSON.stringify(e)};`].join(`
11
+ `);try{let t=await(0,re.build)({stdin:{contents:a,resolveDir:(0,m.dirname)(e),loader:`ts`,sourcefile:`spec-with-hooks.ts`},outdir:n,bundle:!0,platform:`node`,format:`esm`,target:`node18`,banner:{js:`import { createRequire as __esbuildCreateRequire } from 'module'; const require = __esbuildCreateRequire(import.meta.url);`},external:[...Y.EXTERNALS],define:{[Hr]:JSON.stringify(i)},plugins:[{name:Y.PLUGIN_NAME,setup(e){e.onResolve({filter:zr},()=>({path:i}))}}],write:!0,logLevel:`silent`});if(t.errors.length>0){let n=t.errors.map(e=>e.text).join(`
12
+ `);throw console.error(`${J} Build failed for "${e}" (with hooks): ${n}`),new Z(e,n,{cause:Error(n)})}let r=(0,m.join)(n,`stdin.js`);return{outputPath:r,cleanup:()=>this.safeUnlink(r)}}catch(t){if(t instanceof Z)throw t;let n=t instanceof Error?t.message:X.UNEXPECTED_BUILD;throw console.error(`${J} Build failed for "${e}" (with hooks):`,t),new Z(e,n,{cause:t})}}async safeUnlink(e){try{await(0,w.unlink)(e)}catch(t){console.warn(`${J} ${X.CLEANUP_FAILED} "${e}":`,t)}}};Gr=j([(0,d.injectable)(),A(`design:paramtypes`,[])],Gr);let Kr=class{async discoverProjects(e){let t=e||process.cwd(),n=[],r=await this.findPlaywrightConfigs(t);for(let e of r){let t=(0,m.dirname)(e),r={name:(0,m.basename)(t),path:t,configPath:e,testDir:await this.getTestDirFromConfig(e),specs:[]};r.specs=await this.getProjectSpecs(t),n.push(r)}return n}async getProjectSpecs(e){let t=(0,m.join)(e,`playwright.config.ts`);if(!(0,p.existsSync)(t))throw Error(`No playwright.config.ts found in ${e}`);let n=(0,m.join)(e,await this.getTestDirFromConfig(t));if(!(0,p.existsSync)(n))return[];let r=[],i=await this.findSpecFiles(n);for(let t of i){let n=await this.getSpecInfo(t,e);r.push(n)}return r}async getSpecInfo(e,t){let n=(0,m.resolve)(e);if(!(0,p.existsSync)(n))throw Error(`Spec file not found: ${e}`);let r=(0,m.basename)(n);return{name:r,path:n,relativePath:t?(0,m.relative)(t,n):r,hasArgsSchema:await this.checkHasArgsSchema(n)}}async filterSpecs(e,t){let n=await this.discoverProjects(e),r=[];for(let e of n){if(t?.projectName&&e.name!==t.projectName)continue;let n=e.specs;if(t?.specPattern){let e=this.globToRegex(t.specPattern);n=n.filter(t=>e.test(t.name)||e.test(t.relativePath))}r=r.concat(n)}return r}async findPlaywrightConfigs(e){let t=[];return await this.walkDirectory(e,(e,n)=>{if(n){let t=(0,m.basename)(e);return!(t===`node_modules`||t.startsWith(`.`))}return(0,m.basename)(e)===`playwright.config.ts`&&t.push(e),!0}),t}async findSpecFiles(e){let t=[];return await this.walkDirectory(e,(e,n)=>n?(0,m.basename)(e)!==`node_modules`:(e.endsWith(`.spec.ts`)&&t.push(e),!0)),t}async walkDirectory(e,t){if(!(0,p.existsSync)(e))return;let n=await(0,w.readdir)(e,{withFileTypes:!0});for(let r of n){let n=(0,m.join)(e,r.name);r.isDirectory()?t(n,!0)&&await this.walkDirectory(n,t):t(n,!1)}}async getTestDirFromConfig(e){try{let t=(await(0,w.readFile)(e,`utf-8`)).match(/testDir:\s*['"`]([^'"`]+)['"`]/);if(t)return t[1].replace(/^\.\//,``)}catch{}return`tests`}async checkHasArgsSchema(e){try{let t=await(0,w.readFile)(e,`utf-8`);return/export\s+(const\s+)?argsSchema\b/.test(t)}catch{return!1}}globToRegex(e){let t=e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`.*`).replace(/\?/g,`.`);return RegExp(`^${t}$`,`i`)}};Kr=j([(0,d.injectable)()],Kr);let qr=class{constructor(e){this.bundler=e}async extractSpecMetadata(e){let t=await this.bundler.bundle(e);try{let e=await import(`${t.outputPath}?t=${Date.now()}`),n=e.argsSchema??null;return{argsSchema:n,envPrefix:e.envPrefix??null,hasDynamicArgs:n!==null}}catch{return{argsSchema:null,envPrefix:null,hasDynamicArgs:!1}}finally{await t.cleanup()}}async loadPlaywrightConfig(e){try{let t=await(0,w.readFile)(e,`utf-8`),n={},r=t.match(/baseURL:\s*['"`]([^'"`]+)['"`]/);r&&(n.baseURL=r[1]);let i=t.match(/export\s+const\s+mcpConfig\s*=\s*\{([^}]+)\}/s);if(i){let e=i[1],t=e.match(/setupFile:\s*['"`]([^'"`]+)['"`]/);t&&(n.setupFile=t[1]);let r=e.match(/setupExport:\s*['"`]([^'"`]+)['"`]/);r&&(n.setupExport=r[1])}let a=t.match(/webServer:\s*\{([^}]+(?:\{[^}]*\}[^}]*)*)\}/s);if(a){let e=a[1],t=e.match(/command:\s*['"`]([^'"`]+)['"`]/),r=e.match(/url:\s*['"`]([^'"`]+)['"`]/),i=e.match(/reuseExistingServer:\s*(true|false)/),o=e.match(/timeout:\s*(\d+)/),s=e.match(/cwd:\s*['"`]([^'"`]+)['"`]/);t&&r&&(n.webServer={command:t[1],url:r[1],reuseExistingServer:i?i[1]===`true`:void 0,timeout:o?Number.parseInt(o[1],10):void 0,cwd:s?s[1]:void 0})}return n}catch{return{}}}parseArgsFromEnv(e,t){let n={},r=t.toUpperCase();for(let[e,t]of Object.entries(process.env))if(e.startsWith(r)&&t!==void 0){let i=this.envKeyToFieldName(e.slice(r.length));n[i]=this.parseEnvValue(t)}try{return e.parse(n)}catch{return n}}envKeyToFieldName(e){return e.toLowerCase().split(`_`).map((e,t)=>t===0?e:e.charAt(0).toUpperCase()+e.slice(1)).join(``)}parseEnvValue(e){if(e.toLowerCase()===`true`)return!0;if(e.toLowerCase()===`false`)return!1;let t=Number(e);if(!Number.isNaN(t)&&e.trim()!==``)return t;if(e.startsWith(`{`)&&e.endsWith(`}`)||e.startsWith(`[`)&&e.endsWith(`]`))try{return JSON.parse(e)}catch{}return e}};qr=j([(0,d.injectable)(),P(0,(0,d.inject)(k.SpecBundlerService)),A(`design:paramtypes`,[Object])],qr);let Jr=class{constructor(e){this.bundler=e}async loadSpec(e,t){let n=t?await this.bundler.bundleWithHooks({specPath:e,hooksPath:t}):await this.bundler.bundle(e);try{c.c(e);let t=process,r=t.__pw_initiator__;return t.__pw_initiator__=void 0,await import(`${n.outputPath}?t=${Date.now()}`),t.__pw_initiator__=r,c.s()}catch(t){throw c.p(),Error(`Failed to load spec "${e}": ${t instanceof Error?t.message:String(t)}`,{cause:t})}finally{await n.cleanup()}}async executeSpec(e){let{specPath:t,browser:n,hooksPath:r,baseURL:i}=e,a=Date.now(),o=[],s=0,l=0;try{let e=await this.loadSpec(t,r);for(let t of e.allTests){let e=await n.newContext(i?{baseURL:i}:{}),r={page:await e.newPage(),context:e,browser:n,playwright:D.default},a=Date.now();try{await t.fn(r),o.push({title:t.title,fullTitle:t.fullTitle,passed:!0,error:null,duration:Date.now()-a}),s++}catch(e){if(e instanceof c.t||e instanceof Error&&`isSkip`in e)o.push({title:t.title,fullTitle:t.fullTitle,passed:!0,error:null,duration:Date.now()-a}),s++;else{let n=e instanceof Error?e.message:String(e);o.push({title:t.title,fullTitle:t.fullTitle,passed:!1,error:n,duration:Date.now()-a}),l++}}finally{await e.close().catch(()=>{})}}return{specPath:t,totalTests:e.testCount,passed:s,failed:l,testResults:o,success:l===0,duration:Date.now()-a}}catch(e){return{specPath:t,totalTests:0,passed:0,failed:1,testResults:[{title:`Spec Loading`,fullTitle:`Failed to load: ${t}`,passed:!1,error:e instanceof Error?e.message:String(e),duration:Date.now()-a}],success:!1,duration:Date.now()-a}}}async executeSpecEnhanced(e){let{specPath:t,browser:n,testFilter:r,specArgs:i,hooksPath:a,baseURL:o}=e,s=Date.now(),l=[],u=0,d=0;try{let e=await this.loadSpec(t,a),f=r?this.filterTests(e.allTests,r):e.allTests;for(let e of f){let t=await n.newContext(o?{baseURL:o}:{}),r={page:await t.newPage(),context:t,browser:n,playwright:D.default,specArgs:i};if(e.skip){l.push({title:e.title,fullTitle:e.fullTitle,passed:!0,error:null,duration:0}),u++,await t.close().catch(()=>{});continue}let a=Date.now();try{await e.fn(r),l.push({title:e.title,fullTitle:e.fullTitle,passed:!0,error:null,duration:Date.now()-a}),u++}catch(t){if(t instanceof c.t||t instanceof Error&&`isSkip`in t)l.push({title:e.title,fullTitle:e.fullTitle,passed:!0,error:null,duration:Date.now()-a}),u++;else{let n=t instanceof Error?t.message:String(t);l.push({title:e.title,fullTitle:e.fullTitle,passed:!1,error:n,duration:Date.now()-a}),d++}}finally{await t.close().catch(()=>{})}}return{specPath:t,totalTests:f.length,passed:u,failed:d,testResults:l,success:d===0,duration:Date.now()-s}}catch(e){return{specPath:t,totalTests:0,passed:0,failed:1,testResults:[{title:`Spec Loading`,fullTitle:`Failed to load: ${t}`,passed:!1,error:e instanceof Error?e.message:String(e),duration:Date.now()-s}],success:!1,duration:Date.now()-s}}}filterTests(e,t){let n=[...e];if(t.onlyMarked){let e=n.filter(e=>e.only);e.length>0&&(n=e)}if(t.testName&&(n=n.filter(e=>e.title===t.testName)),t.testPattern){let e=new RegExp(t.testPattern,`i`);n=n.filter(t=>e.test(t.fullTitle))}if(t.describeFilter){let e=new RegExp(t.describeFilter,`i`);n=n.filter(t=>e.test(t.fullTitle))}return n}};Jr=j([(0,d.injectable)(),P(0,(0,d.inject)(k.SpecBundlerService)),A(`design:paramtypes`,[Object])],Jr);let Yr=class{browsers=new Map;browserIdCounter=0;constructor(e,t,n){this.profileService=e,this.pageRegistry=t,this.lockManager=n}findChromePath(){let e=x.default.platform(),t={darwin:[`/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`,`/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary`,`${x.default.homedir()}/Applications/Google Chrome.app/Contents/MacOS/Google Chrome`],win32:[`C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe`,`C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe`,`${process.env.LOCALAPPDATA}\\Google\\Chrome\\Application\\chrome.exe`],linux:[`/usr/bin/google-chrome`,`/usr/bin/google-chrome-stable`,`/usr/bin/chromium`,`/usr/bin/chromium-browser`,`/snap/bin/chromium`]},n=t[e]??t.linux;for(let e of n)if(p.default.existsSync(e))return e;return null}resolveExtensionPath(e){if(e&&p.default.existsSync(m.default.join(e,`manifest.json`)))return e;let t=m.default.dirname(new URL(require(`url`).pathToFileURL(__filename).href).pathname),n=[m.default.resolve(t,`../dist/extension`),m.default.resolve(t,`../../dist/extension`)];for(let e of n)if(p.default.existsSync(m.default.join(e,`manifest.json`)))return e;let r=m.default.resolve(process.cwd(),`dist/extension`);if(p.default.existsSync(m.default.join(r,`manifest.json`)))return r;throw Error(`Chrome extension not found. Build the extension first: pnpm build:extension`)}createUserDataDir(e){if(e){let t=m.default.join(this.profileService.getProfilesDir(),e,`stealth-user-data`);return p.default.mkdirSync(t,{recursive:!0}),t}let t=m.default.join(x.default.tmpdir(),`stealth-chrome-${Date.now()}`);return p.default.mkdirSync(t,{recursive:!0}),t}async launch(e={}){let t=this.findChromePath();if(!t)throw Error(`Chrome not found. Please install Google Chrome.
13
13
  macOS: brew install --cask google-chrome
14
- Linux: sudo apt install google-chrome-stable`);let n=this.resolveExtensionPath(e.extensionPath),r=this.createUserDataDir(e.profileName);await this.lockManager.ensureAvailable(r);let i=`stealth-browser-${++this.browserIdCounter}`,a=[n];e.proxy?.username&&e.proxy?.password&&a.push(Xt(e.proxy.username,e.proxy.password));let o=a.join(`,`),s=(0,E.spawn)(t,[`--user-data-dir=${r}`,`--load-extension=${o}`,`--disable-extensions-except=${o}`,`--disable-blink-features=AutomationControlled`,`--disable-infobars`,`--no-first-run`,`--no-default-browser-check`,`--disable-background-timer-throttling`,`--disable-backgrounding-occluded-windows`,`--disable-renderer-backgrounding`,`--disable-component-update`,`--disable-features=TranslateUI`,`--disable-ipc-flooding-protection`,`--password-store=basic`,`--use-mock-keychain`,`--disable-dev-shm-usage`,`--disable-gpu-sandbox`,...e.windowSize?[`--window-size=${e.windowSize.width},${e.windowSize.height}`]:[`--window-size=1280,720`],...e.proxy?Zt(e.proxy):[],e.url??`about:blank`,...e.extraArgs??[]],{detached:!1,stdio:[`ignore`,`ignore`,`ignore`],env:{...process.env,DISPLAY:process.env.DISPLAY}});if(!s.pid)throw Error(`Failed to start Chrome process`);let c={id:i,process:s,pid:s.pid,userDataDir:r,extensionPath:n,profileName:e.profileName,createdAt:new Date,isRunning:!0};return s.on(`exit`,()=>{c.isRunning=!1}),s.on(`error`,e=>{console.error(`Chrome process ${i} error:`,e),c.isRunning=!1}),this.browsers.set(i,c),this.pageRegistry.registerExtensionPage(i),c}async close(e){let t=this.browsers.get(e);if(t&&(t.isRunning&&t.pid&&await Yt(t.pid),t.isRunning=!1,this.browsers.delete(e),!t.profileName&&t.userDataDir.includes(`stealth-chrome-`)))try{p.default.rmSync(t.userDataDir,{recursive:!0,force:!0})}catch{}}async closeAll(){let e=Array.from(this.browsers.keys()).map(e=>this.close(e));await Promise.all(e)}getBrowser(e){return this.browsers.get(e)}listBrowsers(){return Array.from(this.browsers.values()).filter(e=>e.isRunning)}};Kr=M([(0,d.injectable)(),F(0,(0,d.inject)(A.ProfileService)),F(1,(0,d.inject)(A.PageRegistry)),F(2,(0,d.inject)(A.BrowserLockManager)),j(`design:paramtypes`,[Object,Object,Object])],Kr);function qr(e){if(!e.isError)return;let t=e.content[0];return t?.type===`text`&&typeof t.text==`string`?t.text:`Unknown tool execution error`}let Jr=class{constructor(e,t,n,r=new N){this.pageRegistry=e,this.browserService=t,this.delegator=n,this.telemetry=r}async execute(e,t,n,r){return this.telemetry.runInSpan(`browse_tool.tool_executor.page`,{attributes:{"browse_tool.tool.name":e,"browse_tool.page.id":t}},async i=>{let a=this.pageRegistry.get(t);if(!a)return i?.setStatus({code:h.SpanStatusCode.ERROR,message:`Page "${t}" not found`}),{content:[{type:`text`,text:`Page "${t}" not found`}],isError:!0};i?.setAttributes({"browse_tool.browser.id":a.browserId,"browse_tool.execution.mode":a.mode});let o=a.mode===`extension`?await this.delegator.executeTool(e,{pageId:t,browserId:a.browserId,...n}):await r(),s=qr(o);if(s)i?.setStatus({code:h.SpanStatusCode.ERROR,message:s});else if(a.mode===`extension`)try{await this.browserService.ensureExtensionRecordingActive(a.browserId,t)}catch(e){console.warn(`[ToolExecutor] Failed to start extension recording for browser "${a.browserId}" on page "${t}":`,e)}return o})}isExtensionMode(e){return this.pageRegistry.get(e)?.mode===`extension`}async executeForBrowser(e,t,n,r){return this.telemetry.runInSpan(`browse_tool.tool_executor.browser`,{attributes:{"browse_tool.tool.name":e,"browse_tool.browser.id":t}},async i=>{let a=this.browserService.getBrowser(t);if(!a)return i?.setStatus({code:h.SpanStatusCode.ERROR,message:`Browser "${t}" not found`}),{content:[{type:`text`,text:`Browser "${t}" not found`}],isError:!0};i?.setAttributes({"browse_tool.execution.mode":a.mode});let o=a.mode===`extension`||a.mode===`vm`?await this.delegator.executeTool(e,{browserId:t,...n}):await r(),s=qr(o);return s&&i?.setStatus({code:h.SpanStatusCode.ERROR,message:s}),o})}isBrowserExtensionMode(e){let t=this.browserService.getBrowser(e);return t?.mode===`extension`||t?.mode===`vm`}};Jr=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ExtensionToolDelegator)),F(3,(0,d.inject)(A.TelemetryService)),j(`design:paramtypes`,[Object,Object,Object,Object])],Jr);let Yr=class{serverProcess=null;currentUrl=null;cleanupRegistered=!1;constructor(){this.registerCleanup()}registerCleanup(){if(this.cleanupRegistered)return;this.cleanupRegistered=!0;let e=()=>this.cleanupSync();process.on(`exit`,e),process.on(`SIGINT`,e),process.on(`SIGTERM`,e)}async startServer(e,t){let{command:n,url:r,reuseExistingServer:i=!1,timeout:a=3e4,cwd:o}=e;if(i&&await this.isServerRunning(r))return this.currentUrl=r,{started:!1,url:r,reused:!0};await this.stopServer();let s=o?(0,m.resolve)(t,o):t,[c,...l]=this.parseCommand(n);if(this.serverProcess=(0,E.spawn)(c,l,{cwd:s,shell:!0,stdio:[`ignore`,`pipe`,`pipe`],detached:!1}),this.currentUrl=r,this.serverProcess.on(`error`,e=>{console.error(`Server process error: ${e.message}`)}),!await this.waitForServer(r,a))throw await this.stopServer(),Error(`Server failed to start within ${a}ms. URL: ${r}, Command: ${n}`);return{started:!0,url:r,reused:!1}}async waitForServer(e,t){let n=Date.now(),r=100;for(;Date.now()-n<t;){if(await this.isServerRunning(e))return!0;await this.sleep(r),r=Math.min(r*1.5,2e3)}return!1}async stopServer(){if(this.serverProcess)return new Promise(e=>{if(!this.serverProcess){e();return}let t=this.serverProcess;this.serverProcess=null,this.currentUrl=null;let n=setTimeout(()=>{try{t.kill(`SIGKILL`)}catch{}e()},5e3);t.on(`exit`,()=>{clearTimeout(n),e()});try{t.kill(`SIGTERM`)}catch{clearTimeout(n),e()}})}async isServerRunning(e){try{let t=new AbortController,n=setTimeout(()=>t.abort(),3e3),r=await fetch(e,{method:`HEAD`,signal:t.signal});return clearTimeout(n),r.status>=200&&r.status<400}catch{return!1}}parseCommand(e){let t=[],n=``,r=!1,i=``;for(let a of e)(a===`"`||a===`'`)&&!r?(r=!0,i=a):a===i&&r?(r=!1,i=``):a===` `&&!r?n&&=(t.push(n),``):n+=a;return n&&t.push(n),t}sleep(e){return new Promise(t=>setTimeout(t,e))}getCurrentUrl(){return this.currentUrl}cleanupSync(){if(this.serverProcess){try{this.serverProcess.kill(`SIGKILL`)}catch{}this.serverProcess=null,this.currentUrl=null}}};Yr=M([(0,d.injectable)(),j(`design:paramtypes`,[])],Yr);const Xr=w.z.object({type:w.z.string(),text:w.z.string().optional(),data:w.z.string().optional(),mimeType:w.z.string().optional()}),Zr=w.z.object({traceId:w.z.string().regex(/^[0-9a-f]{32}$/i).optional(),parentSpanId:w.z.string().regex(/^[0-9a-f]{16}$/i).optional()}),Qr=w.z.object({content:w.z.array(Xr),isError:w.z.boolean().optional()}),$r=w.z.object({type:w.z.literal(`task:push`),id:w.z.string(),payload:w.z.object({taskId:w.z.string(),tool:w.z.string(),arguments:w.z.record(w.z.string(),w.z.unknown()),pageId:w.z.string().optional(),telemetry:Zr.optional()})}),ei=w.z.object({type:w.z.literal(`page:created`),payload:w.z.object({pageId:w.z.string(),browserId:w.z.string(),url:w.z.string().optional()})}),ti=w.z.object({type:w.z.literal(`page:removed`),payload:w.z.object({pageId:w.z.string()})}),ni=w.z.object({type:w.z.literal(`session:ack`),id:w.z.string(),payload:w.z.object({sessionId:w.z.string(),controlMode:w.z.string()})}),ri=w.z.object({type:w.z.literal(`pong`)}),ii=w.z.object({type:w.z.literal(`error`),payload:w.z.object({message:w.z.string(),code:w.z.string().optional()})}),ai=w.z.discriminatedUnion(`type`,[$r,ei,ti,ni,ri,ii]),oi=w.z.object({type:w.z.literal(`session:register`),id:w.z.string(),payload:w.z.object({browserId:w.z.string(),tabId:w.z.number().optional(),url:w.z.string().optional()})}),si=w.z.object({type:w.z.literal(`task:result`),payload:w.z.object({taskId:w.z.string(),success:w.z.boolean(),result:Qr.optional(),error:w.z.string().optional()})}),ci=w.z.object({type:w.z.literal(`tab:mapped`),payload:w.z.object({pageId:w.z.string(),tabId:w.z.number()})}),li=w.z.object({type:w.z.literal(`ping`)}),ui=w.z.object({type:w.z.literal(`heartbeat`),payload:w.z.object({sessionId:w.z.string(),tabId:w.z.number().optional(),url:w.z.string().optional()})}),di=w.z.discriminatedUnion(`type`,[oi,si,ci,li,ui]);function fi(e){let t=di.safeParse(e);return t.success?t.data:null}let pi=class{connections=new Map;browserConnections=new Map;eventHandlers={};maxConnections=100;setEventHandlers(e){this.eventHandlers=e}addConnection(e,t){if(this.connections.size>=this.maxConnections)throw Error(`Maximum connections (${this.maxConnections}) reached`);let n=crypto.randomUUID(),r={id:n,ws:e,browserId:t,connectedAt:new Date,lastMessageAt:new Date};return this.connections.set(n,r),this.browserConnections.has(t)||this.browserConnections.set(t,new Set),this.browserConnections.get(t).add(n),console.log(`[WebSocketHub] Connection added: ${n} for browser ${t}`),n}removeConnection(e){let t=this.connections.get(e);if(!t)return;this.eventHandlers.onDisconnect?.(t);let n=this.browserConnections.get(t.browserId);n&&(n.delete(e),n.size===0&&this.browserConnections.delete(t.browserId)),this.connections.delete(e),console.log(`[WebSocketHub] Connection removed: ${e}`)}getConnection(e){return this.connections.get(e)}getConnectionsByBrowser(e){let t=this.browserConnections.get(e);return t?Array.from(t).map(e=>this.connections.get(e)).filter(e=>e!==void 0):[]}hasConnection(e){return this.browserConnections.has(e)&&(this.browserConnections.get(e)?.size??0)>0}reassignConnection(e,t){let n=this.connections.get(e);if(!n)return!1;let r=n.browserId;if(r===t)return!0;let i=this.browserConnections.get(r);return i&&(i.delete(e),i.size===0&&this.browserConnections.delete(r)),this.browserConnections.has(t)||this.browserConnections.set(t,new Set),this.browserConnections.get(t).add(e),n.browserId=t,!0}handleMessage(e,t){let n=this.connections.get(e);if(!n){console.warn(`[WebSocketHub] Message from unknown connection: ${e}`);return}n.lastMessageAt=new Date;try{let r=typeof t==`string`?t:new TextDecoder().decode(t),i=JSON.parse(r),a=fi(i);if(!a){console.warn(`[WebSocketHub] Invalid message format from ${e}:`,i),this.sendError(n,`Invalid message format`);return}this.routeMessage(n,a)}catch(t){console.error(`[WebSocketHub] Error parsing message from ${e}:`,t),this.sendError(n,`Failed to parse message`)}}routeMessage(e,t){switch(t.type){case`session:register`:this.eventHandlers.onSessionRegister?.(e,t);break;case`task:result`:this.eventHandlers.onTaskResult?.(e,t);break;case`tab:mapped`:this.eventHandlers.onTabMapped?.(e,t);break;case`heartbeat`:this.eventHandlers.onHeartbeat?.(e,t);break;case`ping`:this.sendToConnection(e,{type:`pong`});break}}sendToConnection(e,t){try{return e.ws.send(JSON.stringify(t)),!0}catch(t){return console.error(`[WebSocketHub] Failed to send to ${e.id}:`,t),!1}}sendError(e,t,n){this.sendToConnection(e,{type:`error`,payload:{message:t,code:n}})}pushTask(e,t){let n=this.getConnectionsByBrowser(e);if(n.length===0)return console.warn(`[WebSocketHub] No connections for browser ${e}`),!1;let r=n[0];return this.sendToConnection(r,t)}broadcastPageCreated(e,t,n){let r={type:`page:created`,payload:{pageId:t,browserId:e,url:n}},i=this.getConnectionsByBrowser(e);for(let e of i)this.sendToConnection(e,r)}broadcastPageRemoved(e,t){let n={type:`page:removed`,payload:{pageId:t}},r=this.getConnectionsByBrowser(e);for(let e of r)this.sendToConnection(e,n)}sendSessionAck(e,t,n,r){e.sessionId=n;let i={type:`session:ack`,id:t,payload:{sessionId:n,controlMode:r}};this.sendToConnection(e,i)}getStats(){return{totalConnections:this.connections.size,browserCount:this.browserConnections.size,connections:Array.from(this.connections.values()).map(e=>({id:e.id,browserId:e.browserId,connectedAt:e.connectedAt}))}}closeAll(){for(let[e,t]of this.connections){try{t.ws.close()}catch{}this.removeConnection(e)}}};pi=M([(0,d.injectable)()],pi);let $=class{constructor(e,t,n){this.pageRegistry=e,this.browserService=t,this.toolExecutor=n}getPage(e){return this.pageRegistry.get(e)}resolvePage(e){let t=this.pageRegistry.get(e);if(!t)throw Error(`Page "${e}" not found`);if(!t.page)throw Error(`Page "${e}" is in extension mode and has no Playwright page`);return t.page}resolvePageEntry(e){let t=this.pageRegistry.get(e);if(!t)throw Error(`Page "${e}" not found`);return t}success(e){return{content:[{type:`text`,text:e}]}}successJson(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}successImage(e,t=`image/png`){return{content:[{type:`image`,data:e,mimeType:t}]}}error(e){return{content:[{type:`text`,text:e}],isError:!0}}async safeExecute(e){try{return await e()}catch(e){let t=e instanceof Error?e.message:String(e);return this.error(t)}}async executeWithMode(e,t,n,r){return this.toolExecutor.execute(e,t,n,r)}};$=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],$);var mi;let hi=class extends ${static{mi=this}static TOOL_NAME=`browser_click`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:mi.TOOL_NAME,description:`Clicks on an element on the page. Supports CSS selector, XPath, text content, or accessibility snapshot UID for element identification.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},selector:{type:`string`,description:`CSS selector (e.g., "button.submit", "#login-btn")`},xpath:{type:`string`,description:`XPath expression (e.g., "//button[@type='submit']")`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID reference`},frame:{type:`string`,description:`Frame selector for iframe content`},clickCount:{type:`number`,description:`Number of clicks (default: 1, use 2 for double-click)`,default:1},button:{type:`string`,enum:[`left`,`middle`,`right`],description:`Mouse button to use`,default:`left`},modifiers:{type:`array`,items:{type:`string`,enum:[`Alt`,`Control`,`Meta`,`Shift`]},description:`Modifier keys to hold during click`},delay:{type:`number`,description:`Time to wait between mousedown and mouseup in ms`},position:{type:`object`,properties:{x:{type:`number`},y:{type:`number`}},description:`Position offset within the element`},timeout:{type:`number`,description:`Timeout in milliseconds (default: ${P})`,default:P}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(mi.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);return await(await this.elementLocator.locate(t,{selector:e.selector,xpath:e.xpath,text:e.text,uid:e.uid,frame:e.frame})).click({clickCount:e.clickCount,button:e.button,modifiers:e.modifiers,delay:e.delay,position:e.position,timeout:e.timeout}),this.success(`Clicked element successfully`)})}};hi=mi=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.ElementLocatorService)),j(`design:paramtypes`,[Object,Object,Object,Object])],hi);var gi;let _i=class extends ${static{gi=this}static TOOL_NAME=`browser_close`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:gi.TOOL_NAME,description:`Closes a browser instance by its ID. Terminates the browser process, cleans up all associated pages, and releases resources. Works for all modes: playwright, extension, vm (Docker), and stealth.`,inputSchema:{type:`object`,properties:{browserId:{type:`string`,description:`The browser ID to close (returned by browser_launch)`}},required:[`browserId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.browserService.getBrowser(e.browserId);if(!t)return this.error(`Browser "${e.browserId}" not found`);let n=t.pageIds.size,r=t.mode??`playwright`;return await this.browserService.closeBrowser(e.browserId),this.successJson({closedBrowserId:e.browserId,mode:r,pagesRemoved:n,message:`Browser "${e.browserId}" closed successfully`})})}};_i=gi=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],_i);var vi;let yi=class extends ${static{vi=this}static TOOL_NAME=`browser_close_page`;constructor(e,t,n,r){super(e,t,n),this.profileService=r}getDefinition(){return{name:vi.TOOL_NAME,description:`Closes a page (tab) by its ID. Removes the page from the session and registry. If closed page was current, another page becomes current.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to close`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.pageRegistry.get(e.pageId);if(!t)return this.error(`Page "${e.pageId}" not found`);let{browserId:n,profileName:r,mode:i}=t,a=this.browserService.getBrowser(n);if(!a)return this.error(`Browser "${n}" not found`);let o=a.currentPageId===e.pageId,s=a.pageIds.size===1;if(i===`extension`||i===`vm`){let t=await this.executeWithMode(vi.TOOL_NAME,e.pageId,e,async()=>this.error(`Page "${e.pageId}" is not in extension mode`));if(t.isError)return t;if(await this.browserService.finalizeExtensionRecording(n,e.pageId),this.pageRegistry.remove(e.pageId),a.pageIds.delete(e.pageId),a.currentPageId===e.pageId&&(a.currentPageId=Array.from(a.pageIds)[0]??null),s)try{await this.browserService.closeBrowser(n)}catch(e){console.error(`Failed to close extension browser "${n}" after last tab shutdown:`,e)}return this.successJson({closedPageId:e.pageId,browserId:n,wasCurrentPage:o,newCurrentPageId:a.currentPageId,browserKeptOpen:!s,message:s?`Page "${e.pageId}" closed. Browser "${n}" was also closed because no tabs remained.`:`Page "${e.pageId}" closed successfully`})}if(!t.page)return this.error(`Page "${e.pageId}" is in extension mode and cannot be closed via Playwright`);await t.page.close();let c=this.browserService.getBrowser(n)?.currentPageId??null;if(s){if(r&&a.context)try{let e=await a.context.storageState();await this.profileService.saveStorageState(r,e)}catch(e){console.error(`Failed to auto-save profile "${r}":`,e)}if(!r)try{await this.browserService.closeBrowser(n)}catch(e){console.error(`Failed to auto-close browser "${n}":`,e)}}return this.successJson({closedPageId:e.pageId,browserId:n,wasCurrentPage:o,newCurrentPageId:c,browserKeptOpen:s&&!!r,message:s&&r?`Page "${e.pageId}" closed. Browser kept open for profile "${r}" reuse.`:`Page "${e.pageId}" closed successfully`})})}};yi=vi=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.ProfileService)),j(`design:paramtypes`,[Object,Object,Object,Object])],yi);var bi;let xi=class{static{bi=this}static TOOL_NAME=`browser_create_profile`;constructor(e){this.profileService=e}getDefinition(){return{name:bi.TOOL_NAME,description:`Creates a browser profile for persistent browser settings and session reuse.`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Unique profile name`},browserType:{type:`string`,enum:[`chromium`,`firefox`,`webkit`],description:`Preferred browser type for the profile`,default:`chromium`},viewport:{type:`object`,properties:{width:{type:`number`},height:{type:`number`}},required:[`width`,`height`],additionalProperties:!1},userAgent:{type:`string`},locale:{type:`string`},timezone:{type:`string`},colorScheme:{type:`string`,enum:[`light`,`dark`,`no-preference`]}},required:[`name`],additionalProperties:!1}}}async execute(e){try{let t=await this.profileService.create({name:e.name,browserType:e.browserType??`chromium`,viewport:e.viewport,userAgent:e.userAgent,locale:e.locale,timezone:e.timezone,colorScheme:e.colorScheme});return{content:[{type:`text`,text:JSON.stringify(t,null,2)}]}}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}}};xi=bi=M([(0,d.injectable)(),F(0,(0,d.inject)(A.ProfileService)),j(`design:paramtypes`,[Object])],xi);var Si;let Ci=class{static{Si=this}static TOOL_NAME=`browser_delete_profile`;constructor(e){this.profileService=e}getDefinition(){return{name:Si.TOOL_NAME,description:`Deletes a browser profile and all its associated storage state data.`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Name of the profile to delete`}},required:[`name`],additionalProperties:!1}}}async execute(e){try{return await this.profileService.delete(e.name),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Profile "${e.name}" deleted successfully`},null,2)}]}}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}};Ci=Si=M([(0,d.injectable)(),F(0,(0,d.inject)(A.ProfileService)),j(`design:paramtypes`,[Object])],Ci);var wi;let Ti=class{static{wi=this}static TOOL_NAME=`discover_specs`;constructor(e){this.specDiscoveryService=e}getDefinition(){return{name:wi.TOOL_NAME,description:`Discovers e2e projects (directories with playwright.config.ts) and their spec files. Use to find available specs before running them.`,inputSchema:{type:`object`,properties:{basePath:{type:`string`,description:`Absolute path to search for e2e projects (required)`},projectName:{type:`string`,description:`Filter by project name (e.g., 'boomlink-e2e')`},specPattern:{type:`string`,description:`Filter specs by name pattern (supports * and ? wildcards, e.g., "auth*", "*.spec.ts")`},includeMetadata:{type:`boolean`,description:`Include metadata like hasArgsSchema detection (default: true)`,default:!0}},required:[`basePath`],additionalProperties:!1}}}async execute(e){if(!e.basePath||!(0,m.isAbsolute)(e.basePath))return{content:[{type:`text`,text:`Error: basePath must be an absolute path (e.g., /Users/me/project)`}],isError:!0};try{let t=e.basePath,n=e.includeMetadata!==!1;if(e.projectName||e.specPattern){let r=await this.specDiscoveryService.filterSpecs(t,{projectName:e.projectName,specPattern:e.specPattern}),i={filter:{basePath:t,projectName:e.projectName,specPattern:e.specPattern},totalSpecs:r.length,specs:r.map(e=>({name:e.name,path:e.path,relativePath:e.relativePath,...n&&{hasArgsSchema:e.hasArgsSchema}}))};return{content:[{type:`text`,text:JSON.stringify(i,null,2)}]}}let r=await this.specDiscoveryService.discoverProjects(t),i={basePath:t,totalProjects:r.length,totalSpecs:r.reduce((e,t)=>e+t.specs.length,0),projects:r.map(e=>({name:e.name,path:e.path,configPath:e.configPath,testDir:e.testDir,specCount:e.specs.length,specs:e.specs.map(e=>({name:e.name,path:e.path,relativePath:e.relativePath,...n&&{hasArgsSchema:e.hasArgsSchema}}))}))};return{content:[{type:`text`,text:JSON.stringify(i,null,2)}]}}catch(e){return{content:[{type:`text`,text:`Error discovering specs: ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}};Ti=wi=M([(0,d.injectable)(),F(0,(0,d.inject)(A.SpecDiscoveryService)),j(`design:paramtypes`,[Object])],Ti);var Ei;let Di=class extends ${static{Ei=this}static TOOL_NAME=`browser_drag`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:Ei.TOOL_NAME,description:`Drags an element to a target location or element.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},source:{type:`object`,description:`Source element selector`,properties:{selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`}}},target:{type:`object`,description:`Target element selector or coordinates`,properties:{selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`},x:{type:`number`,description:`X coordinate`},y:{type:`number`,description:`Y coordinate`}}},force:{type:`boolean`,description:`Bypass actionability checks`,default:!1},timeout:{type:`number`,description:`Timeout in milliseconds`,default:P}},required:[`pageId`,`source`,`target`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ei.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId),n=await this.elementLocator.locate(t,e.source);if(`x`in e.target&&`y`in e.target)await n.dragTo(t.locator(`body`),{targetPosition:{x:e.target.x,y:e.target.y},force:e.force,timeout:e.timeout});else{let r=await this.elementLocator.locate(t,e.target);await n.dragTo(r,{force:e.force,timeout:e.timeout})}return this.success(`Dragged element successfully`)})}};Di=Ei=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.ElementLocatorService)),j(`design:paramtypes`,[Object,Object,Object,Object])],Di);var Oi;let ki=class extends ${static{Oi=this}static TOOL_NAME=`browser_emulate`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Oi.TOOL_NAME,description:`Emulates device characteristics like geolocation, timezone, locale, color scheme, and network conditions.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},geolocation:{type:`object`,description:`Geolocation coordinates to emulate`,properties:{latitude:{type:`number`,minimum:-90,maximum:90},longitude:{type:`number`,minimum:-180,maximum:180},accuracy:{type:`number`,minimum:0}},required:[`latitude`,`longitude`]},locale:{type:`string`,description:`Locale to emulate (e.g., "en-US", "de-DE")`},timezone:{type:`string`,description:`Timezone to emulate (e.g., "America/New_York", "Europe/London")`},userAgent:{type:`string`,description:`User agent string to use`},offline:{type:`boolean`,description:`Whether to emulate offline mode`},colorScheme:{type:`string`,enum:[`light`,`dark`,`no-preference`],description:`Color scheme preference`},reducedMotion:{type:`string`,enum:[`reduce`,`no-preference`],description:`Reduced motion preference`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Oi.TOOL_NAME,e.pageId,e,async()=>this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId),n=t.context,r=t.page;if(!n||!r)return this.error(`Page "${e.pageId}" is in extension mode and cannot be emulated via Playwright`);let i={};return e.geolocation&&(await n.setGeolocation(e.geolocation),i.geolocation=e.geolocation),e.offline!==void 0&&(await n.setOffline(e.offline),i.offline=e.offline),e.colorScheme&&(await r.emulateMedia({colorScheme:e.colorScheme}),i.colorScheme=e.colorScheme),e.reducedMotion&&(await r.emulateMedia({reducedMotion:e.reducedMotion}),i.reducedMotion=e.reducedMotion),e.locale&&(i.locale=e.locale,i.localeNote=`Locale changes may require a new browser context to take full effect`),e.timezone&&(i.timezone=e.timezone,i.timezoneNote=`Timezone changes may require a new browser context to take full effect`),e.userAgent&&(i.userAgent=e.userAgent,i.userAgentNote=`User agent changes may require a new browser context to take full effect`),this.successJson({success:!0,pageId:t.id,appliedSettings:i})}))}};ki=Oi=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],ki);var Ai;let ji=class extends ${static{Ai=this}static TOOL_NAME=`browser_evaluate_script`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ai.TOOL_NAME,description:`Executes JavaScript code in the page context and returns the result. The script can be a function body or an expression.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},script:{type:`string`,description:`JavaScript code to execute. Can be a function body or expression (e.g., "document.title" or "() => window.location.href")`},arg:{description:`Optional argument to pass to the script if it is a function`}},required:[`pageId`,`script`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ai.TOOL_NAME,e.pageId,{script:e.script,arg:e.arg},async()=>{let t=await this.resolvePage(e.pageId).evaluate(e.script,e.arg),n;try{n=JSON.stringify(t,null,2)}catch{n=String(t)}let r=`evaluate-${(0,k.randomUUID)()}.json`,i=(0,m.join)((0,C.tmpdir)(),r);return await(0,T.writeFile)(i,n,`utf-8`),this.success(`Result saved to: ${i}`)})}};ji=Ai=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],ji);var Mi;let Ni=class extends ${static{Mi=this}static TOOL_NAME=`browser_expect`;constructor(e,t,n,r){super(e,t,n),this.extensionPageProxy=r}getDefinition(){return{name:Mi.TOOL_NAME,description:`Performs Playwright expect() assertions on page elements. Supports various assertion types like toBeVisible, toHaveText, toHaveValue, toBeEnabled, etc.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},selector:{type:`string`,description:`CSS selector for the element to assert on (not required for page-level assertions like toHaveTitle, toHaveURL)`},assertion:{type:`string`,enum:[`toBeVisible`,`toBeHidden`,`toBeEnabled`,`toBeDisabled`,`toBeChecked`,`toBeEditable`,`toBeFocused`,`toBeEmpty`,`toHaveText`,`toContainText`,`toHaveValue`,`toHaveAttribute`,`toHaveClass`,`toHaveCount`,`toHaveCSS`,`toHaveId`,`toHaveTitle`,`toHaveURL`],description:`Type of assertion to perform`},expected:{oneOf:[{type:`string`},{type:`number`}],description:`Expected value for assertions that require one (e.g., toHaveText, toHaveValue)`},attributeName:{type:`string`,description:`Attribute name for toHaveAttribute or toHaveCSS assertion`},not:{type:`boolean`,description:`Whether to negate the assertion (not.toBeVisible, etc.)`},timeout:{type:`number`,description:`Timeout in milliseconds for the assertion (default: 5000)`}},required:[`pageId`,`assertion`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId),n=t.mode===`extension`?(()=>(this.extensionPageProxy.setTarget(t.id,t.browserId),this.extensionPageProxy))():this.resolvePage(e.pageId),{selector:r,assertion:i,expected:a,attributeName:o,not:s,timeout:l=5e3}=e,u=[`toHaveTitle`,`toHaveURL`];if(!u.includes(i)&&!r)return this.error(`Selector is required for assertion type: ${i}`);try{if(u.includes(i)){let e=s?c.a(n).not:c.a(n);i===`toHaveTitle`?await e.toHaveTitle(a,{timeout:l}):i===`toHaveURL`&&await e.toHaveURL(a,{timeout:l})}else{let e=n.locator(r),t=s?c.a(e).not:c.a(e);switch(i){case`toBeVisible`:await t.toBeVisible({timeout:l});break;case`toBeHidden`:await t.toBeHidden({timeout:l});break;case`toBeEnabled`:await t.toBeEnabled({timeout:l});break;case`toBeDisabled`:await t.toBeDisabled({timeout:l});break;case`toBeChecked`:await t.toBeChecked({timeout:l});break;case`toBeEditable`:await t.toBeEditable({timeout:l});break;case`toBeFocused`:await t.toBeFocused({timeout:l});break;case`toBeEmpty`:await t.toBeEmpty({timeout:l});break;case`toHaveText`:await t.toHaveText(a,{timeout:l});break;case`toContainText`:await t.toContainText(a,{timeout:l});break;case`toHaveValue`:await t.toHaveValue(a,{timeout:l});break;case`toHaveAttribute`:if(!o)return this.error(`attributeName is required for toHaveAttribute assertion`);await t.toHaveAttribute(o,a,{timeout:l});break;case`toHaveClass`:await t.toHaveClass(a,{timeout:l});break;case`toHaveCount`:await t.toHaveCount(a,{timeout:l});break;case`toHaveCSS`:if(!o)return this.error(`attributeName (CSS property name) is required for toHaveCSS assertion`);await t.toHaveCSS(o,a,{timeout:l});break;case`toHaveId`:await t.toHaveId(a,{timeout:l});break;default:return this.error(`Unsupported assertion type: ${i}`)}}return this.successJson({success:!0,assertion:s?`not.${i}`:i,selector:r??null,passed:!0})}catch(e){let t=e instanceof Error?e.message:`Assertion failed`;return this.successJson({success:!0,assertion:s?`not.${i}`:i,selector:r??null,passed:!1,failureMessage:t})}})}};Ni=Mi=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.ExtensionPageProxy)),j(`design:paramtypes`,[Object,Object,Object,Object])],Ni);var Pi;let Fi=class extends ${static{Pi=this}static TOOL_NAME=`browser_fill`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:Pi.TOOL_NAME,description:`Fills an input field with text, clearing any existing content first. Use for form inputs, textareas, and contenteditable elements.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`},value:{type:`string`,description:`The text value to fill into the input`},force:{type:`boolean`,description:`Bypass actionability checks`,default:!1},timeout:{type:`number`,description:`Timeout in milliseconds`,default:P}},required:[`pageId`,`value`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Pi.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);return await(await this.elementLocator.locate(t,e)).fill(e.value,{force:e.force,timeout:e.timeout}),this.success(`Filled element with: "${e.value}"`)})}};Fi=Pi=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.ElementLocatorService)),j(`design:paramtypes`,[Object,Object,Object,Object])],Fi);var Ii;let Li=class extends ${static{Ii=this}static TOOL_NAME=`browser_get_network_request`;constructor(e,t,n,r){super(e,t,n),this.pageMonitor=r}getDefinition(){return{name:Ii.TOOL_NAME,description:`Retrieves detailed information about a specific network request by ID, including headers, body, and response data.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},requestId:{type:`string`,description:`The ID of the network request to retrieve (e.g., "req-1")`}},required:[`pageId`,`requestId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId);return this.executeWithMode(Ii.TOOL_NAME,t.id,e,async()=>{let n=this.pageMonitor.getNetworkRequest(t.id,e.requestId);return n?this.successJson({id:n.id,url:n.url,method:n.method,resourceType:n.resourceType,headers:n.headers,postData:n.postData,timestamp:n.timestamp.toISOString(),response:n.response?{status:n.response.status,statusText:n.response.statusText,headers:n.response.headers,timing:n.response.timing}:null}):this.error(`Network request "${e.requestId}" not found for page "${t.id}"`)})})}};Li=Ii=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.PageMonitorService)),j(`design:paramtypes`,[Object,Object,Object,Object])],Li);var Ri;let zi=class extends ${static{Ri=this}static TOOL_NAME=`browser_go_back`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ri.TOOL_NAME,description:`Navigates the browser back in history.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},waitUntil:{type:`string`,enum:[`load`,`domcontentloaded`,`networkidle`,`commit`],description:`Wait until condition`,default:`load`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:P}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ri.TOOL_NAME,e.pageId,e,async()=>{let t=await this.resolvePage(e.pageId).goBack({waitUntil:e.waitUntil,timeout:e.timeout});if(t===null)return this.success(`No previous page in history`);let n=t.status();return this.success(`Navigated back (status: ${n})`)})}};zi=Ri=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],zi);var Bi;let Vi=class extends ${static{Bi=this}static TOOL_NAME=`browser_go_forward`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Bi.TOOL_NAME,description:`Navigates the browser forward in history.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},waitUntil:{type:`string`,enum:[`load`,`domcontentloaded`,`networkidle`,`commit`],description:`Wait until condition`,default:`load`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:P}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Bi.TOOL_NAME,e.pageId,e,async()=>{let t=await this.resolvePage(e.pageId).goForward({waitUntil:e.waitUntil,timeout:e.timeout});if(t===null)return this.success(`No next page in history`);let n=t.status();return this.success(`Navigated forward (status: ${n})`)})}};Vi=Bi=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],Vi);var Hi;let Ui=class extends ${static{Hi=this}static TOOL_NAME=`browser_handle_dialog`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Hi.TOOL_NAME,description:`Handles JavaScript dialogs (alert, confirm, prompt) by accepting or dismissing them. Set up a listener before triggering the action that opens the dialog.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},accept:{type:`boolean`,description:`Whether to accept (true) or dismiss (false) the dialog`},promptText:{type:`string`,description:`Text to enter for prompt dialogs (only used when accept is true)`},timeout:{type:`number`,description:`Timeout in milliseconds to wait for dialog (default: ${P})`,default:P}},required:[`pageId`,`accept`],additionalProperties:!1}}}async execute(e){return this.safeExecute(()=>this.executeWithMode(Hi.TOOL_NAME,e.pageId,{accept:e.accept,promptText:e.promptText,timeout:e.timeout},async()=>{let t=this.resolvePage(e.pageId),n=e.timeout??P,r=setTimeout(()=>{t.off(`dialog`,i)},n),i=async n=>{clearTimeout(r);try{e.accept?await n.accept(e.promptText):await n.dismiss()}finally{t.off(`dialog`,i)}};return t.once(`dialog`,i),this.successJson({armed:!0,action:e.accept?`accept`:`dismiss`,timeout:n,promptText:e.promptText??null})}))}};Ui=Hi=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],Ui);var Wi;let Gi=class extends ${static{Wi=this}static TOOL_NAME=`browser_hover`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:Wi.TOOL_NAME,description:`Hovers over an element to trigger hover states, tooltips, or dropdown menus.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`},position:{type:`object`,properties:{x:{type:`number`},y:{type:`number`}},description:`Position offset within element`},modifiers:{type:`array`,items:{type:`string`,enum:[`Alt`,`Control`,`Meta`,`Shift`]},description:`Modifier keys to hold`},force:{type:`boolean`,description:`Bypass actionability checks`,default:!1},timeout:{type:`number`,description:`Timeout in milliseconds`,default:P}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Wi.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);return await(await this.elementLocator.locate(t,e)).hover({position:e.position,modifiers:e.modifiers,force:e.force,timeout:e.timeout}),this.success(`Hovered over element successfully`)})}};Gi=Wi=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.ElementLocatorService)),j(`design:paramtypes`,[Object,Object,Object,Object])],Gi);var Ki;const qi=[`pnpm-workspace.yaml`,`nx.json`,`.git`],Ji=`about:blank`,Yi=`browser-extension-`,Xi=process.env.BROWSE_TOOL_DEBUG_EXTENSION_RECORDING===`1`,Zi=`browse-tool-http`,Qi=`tool`,$i=`development`,ea=`host.docker.internal`,ta=`[LaunchBrowserTool]`,na=new Set([`docker`,`docker-vm`,`docker-chromium`,`docker-chrome-testing`]);function ra(e=process.cwd()){let t=m.default.resolve(e);for(;;){for(let e of qi)if((0,p.existsSync)(m.default.join(t,e)))return t;let e=m.default.dirname(t);if(e===t)return process.cwd();t=e}}let ia=class{static{Ki=this}static TOOL_NAME=`browser_launch`;constructor(e,t){this.browserService=e,this.stealthLauncher=t}getDefinition(){return{name:Ki.TOOL_NAME,description:`Launches a new browser instance. Returns browserId and pageId for subsequent browser operations. Use mode "extension" for bot-detection-free automation via Chrome extension, or mode "vm" for isolated runtime launch.`,inputSchema:{type:`object`,properties:{mode:{type:`string`,enum:[`playwright`,`extension`,`vm`,`stealth`],description:`Execution mode. "playwright" uses Playwright APIs. "extension" uses Playwright with Chrome extension. "vm" launches in an isolated runtime (for example via Docker). "stealth" spawns Chrome directly without automation flags.`,default:`playwright`},browserType:{type:`string`,enum:[`chromium`,`firefox`,`webkit`],description:`Browser type to use (only applies to playwright mode)`,default:`chromium`},headless:{type:`boolean`,description:`Run browser in headless mode (only applies to playwright mode)`,default:!0},url:{type:`string`,description:`Optional URL to navigate to after launch`},profileName:{type:`string`,description:`Optional profile name to use for browser settings and persistent storage`},vmCommand:{type:`string`,description:`Executable/alias for vm mode launch (e.g., "docker" for isolated container runtime)`},vmCommandArgs:{type:`array`,description:`Browser arguments for vm command runtime`,items:{type:`string`}},vmUseChromeForTesting:{type:`boolean`,description:`When true, vm mode prefers Chrome for Testing. If command is omitted, "chrome-testing" alias, or generic "chrome", this resolves to Chrome for Testing.`,default:!0},vmBrowserId:{type:`string`,description:`Optional browserId override for vm mode`},startupDelayMs:{type:`number`,description:`Optional startup delay in milliseconds before returning in vm mode`},vmServerUrl:{type:`string`,description:`Explicit MCP server URL reachable from inside VM (e.g., "http://host.docker.internal:3200"). Overrides registry discovery.`},vmExtensionPath:{type:`string`,description:`Explicit extension path that exists inside VM filesystem. Useful when VM does not share host workspace paths.`},vmEnableVnc:{type:`boolean`,description:`Expose VNC/noVNC ports when using Docker VM runtime`,default:!1},vmVncPort:{type:`number`,description:`Host port for VNC (container port 5900) when vmEnableVnc is true`,minimum:1,maximum:65535},vmNoVncPort:{type:`number`,description:`Host port for noVNC web UI (container port 7900) when vmEnableVnc is true`,minimum:1,maximum:65535},vmVncPassword:{type:`string`,description:`Optional VNC password for Docker VM runtime`},baseURL:{type:`string`,description:`Base URL for relative navigation (e.g., page.goto("/") will use this as the base)`},videoDir:{type:`string`,description:`Directory to save video recordings. If provided, video will be recorded for all pages. Videos are saved when the page or context is closed.`},proxy:{type:`object`,description:`Proxy configuration for routing browser traffic through a proxy server. Supports authenticated residential proxies.`,properties:{server:{type:`string`,description:`Proxy server URL (e.g., "http://proxy.example.com:8080")`},username:{type:`string`,description:`Proxy username for authentication`},password:{type:`string`,description:`Proxy password for authentication`},bypass:{type:`string`,description:`Comma-separated list of hosts to bypass the proxy (e.g., "localhost,127.0.0.1")`}},required:[`server`],additionalProperties:!1}},required:[],additionalProperties:!1}}}async execute(e){let t=e.mode??`playwright`;try{return t===`stealth`?await this.launchStealthMode(e):t===`vm`?await this.launchVmMode(e):t===`extension`?await this.launchExtensionMode(e):await this.launchPlaywrightMode(e)}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}}async launchPlaywrightMode(e){let t=await this.browserService.launch({browserType:e.browserType,headless:e.headless,profileName:e.profileName,baseURL:e.baseURL,recordVideo:e.videoDir?{dir:e.videoDir}:void 0,proxy:e.proxy});return e.url&&await t.page.goto(e.url),{content:[{type:`text`,text:JSON.stringify({browserId:t.browserInstance.id,pageId:t.pageId,mode:`playwright`,url:e.url??t.page.url()},null,2)}]}}async launchStealthMode(e){let t=await this.stealthLauncher.launch({url:e.url,profileName:e.profileName,proxy:e.proxy});return{content:[{type:`text`,text:JSON.stringify({browserId:t.id,pageId:`page-${t.id}`,mode:`stealth`,url:e.url??`about:blank`,pid:t.pid},null,2)}]}}async launchExtensionMode(e){Xi&&console.log(`[ExtensionRecordingDebug] launch tool mode=extension videoDir=${e.videoDir??``} url=${e.url??``}`);let t=e.profileName?`browser-${e.profileName}`:`browser-extension-${(0,k.randomUUID)()}`,n=e.url??Ji,r=await this.resolveExtensionBootstrapServerUrl(),i=this.buildVmBootstrapUrl(r,t,n),a=await this.browserService.launchWithExtension({url:i,baseURL:e.baseURL,profileName:e.profileName,recordVideo:e.videoDir?{dir:e.videoDir}:void 0,proxy:e.proxy,mode:`extension`,browserId:t});return{content:[{type:`text`,text:JSON.stringify({browserId:a.browserInstance.id,pageId:a.pageId,mode:`extension`,url:n,pid:a.process.pid},null,2)}]}}async launchVmMode(e){let t=e.vmBrowserId??`browser-vm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,n=e.url??Ji,r=e.vmCommand??`docker`,i=await this.resolveVmBootstrapServerUrl(e.vmServerUrl,r),a=this.buildVmBootstrapUrl(i,t,n),o=this.buildVmDockerRuntimeOptions(e),s=await this.browserService.launchWithExtension({url:a,baseURL:e.baseURL,profileName:e.profileName,recordVideo:e.videoDir?{dir:e.videoDir}:void 0,proxy:e.proxy,extensionPath:e.vmExtensionPath??process.env.PLAYWRIGHT_VM_EXTENSION_PATH,mode:`vm`,useChromeForTesting:e.vmUseChromeForTesting??!0,command:r,commandArgs:e.vmCommandArgs,dockerRunArgs:o.runArgs,dockerEnv:o.env,dockerEnableVnc:o.enableVnc,browserId:t,startupDelayMs:e.startupDelayMs}),c=o.vnc?{vncUrl:o.vnc.vncUrl,noVncUrl:o.vnc.noVncUrl}:void 0;return{content:[{type:`text`,text:JSON.stringify({browserId:s.browserInstance.id,pageId:s.pageId,mode:`vm`,url:n,pid:s.process.pid,...c?{vm:c}:{}},null,2)}]}}buildVmBootstrapUrl(e,t,n){let r=new URL(e);return r.searchParams.set(`playwright_mcp_connect`,`1`),r.searchParams.set(`playwright_mcp_server`,e),r.searchParams.set(`playwright_mcp_browser_id`,t),r.searchParams.set(`playwright_mcp_navigate`,n),r.toString()}async resolveVmBootstrapServerUrl(e,t){let n=e??process.env.PLAYWRIGHT_VM_SERVER_URL;if(n)return this.normalizeVmServerUrl(n);let r=V(),i=await this.getRegisteredPort(r);return this.isDockerVmCommand(t??`docker`)?H(`host.docker.internal`,i.port):H(i.host,i.port)}async resolveExtensionBootstrapServerUrl(){let e=V(),t=await this.getRegisteredPort(e);return H(t.host,t.port)}normalizeVmServerUrl(e){let t;try{t=new URL(e)}catch{throw Error(`Invalid vmServerUrl: "${e}"`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`vmServerUrl must use http or https: "${e}"`);return t.origin}isDockerVmCommand(e){return na.has(e.trim().toLowerCase())}buildVmDockerRuntimeOptions(e){let t=e.vmEnableVnc||e.vmVncPort!==void 0||e.vmNoVncPort!==void 0,n=[],r={},i;if(t){let t=e.vmVncPort??5901,r=e.vmNoVncPort??7901;n.push(`-p`,`${t}:5900`,`-p`,`${r}:7900`),i={vncUrl:`vnc://localhost:${t}`,noVncUrl:`http://localhost:${r}/`}}return e.vmVncPassword&&e.vmVncPassword.trim().length>0&&(r.SE_VNC_PASSWORD=e.vmVncPassword.trim()),{runArgs:n.length>0?n:void 0,env:Object.keys(r).length>0?r:void 0,enableVnc:t,vnc:i}}getFallbackPort(){try{return Bn()}catch{return 3200}}isValidPort(e){return typeof e==`number`&&Number.isInteger(e)&&e>0&&e<=65535}getLatestRegistryEntry(e){return e.length===0?null:[...e].sort((e,t)=>{let n=Number.isNaN(Date.parse(e.updatedAt))?0:Date.parse(e.updatedAt);return(Number.isNaN(Date.parse(t.updatedAt))?0:Date.parse(t.updatedAt))-n})[0]??null}async getRegisteredPort(e){let t={host:e,port:this.getFallbackPort()},n=ra(process.cwd()),r=process.env.NODE_ENV||`development`,i=new S.PortRegistryService(process.env.PORT_REGISTRY_PATH);try{let t=await i.getPort({repositoryPath:n,serviceName:Zi,serviceType:Qi,environment:r});if(t.success&&t.record&&this.isValidPort(t.record.port))return{host:t.record.host||e,port:t.record.port}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`${ta} Scoped registry lookup failed for ${Zi} in ${r}: ${t}`)}try{let n=await i.listAllocations({serviceName:Zi,serviceType:Qi,environment:r}),a=this.getLatestRegistryEntry(n);return!a||!this.isValidPort(a.port)?t:{host:a.host||e,port:a.port}}catch(e){let n=e instanceof Error?e.message:String(e);return console.warn(`${ta} Global registry lookup failed for ${Zi} in ${r}: ${n}`),t}}};ia=Ki=M([(0,d.injectable)(),F(0,(0,d.inject)(A.BrowserService)),F(1,(0,d.inject)(A.StealthLauncher)),j(`design:paramtypes`,[Object,Object])],ia);var aa;let oa=class extends ${static{aa=this}static TOOL_NAME=`browser_list_console_messages`;constructor(e,t,n,r){super(e,t,n),this.pageMonitor=r}getDefinition(){return{name:aa.TOOL_NAME,description:`Lists all console messages captured during page automation. Requires monitoring to be started first.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},type:{type:`string`,description:`Filter by message type (log, info, warning, error, debug, trace, etc.)`,enum:[`log`,`info`,`warning`,`error`,`debug`,`trace`,`dir`,`dirxml`,`table`,`count`,`assert`]},limit:{type:`number`,description:`Maximum number of messages to return`,minimum:1}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId);return this.executeWithMode(aa.TOOL_NAME,t.id,e,async()=>{let n=this.pageMonitor.getConsoleMessages(t.id,e.type);return e.limit&&(n=n.slice(0,e.limit)),this.successJson({pageId:t.id,messageCount:n.length,messages:n.map(e=>({id:e.id,type:e.type,text:e.text,location:e.location,timestamp:e.timestamp.toISOString()}))})})})}};oa=aa=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.PageMonitorService)),j(`design:paramtypes`,[Object,Object,Object,Object])],oa);var sa;let ca=class extends ${static{sa=this}static TOOL_NAME=`browser_list_network_requests`;constructor(e,t,n,r){super(e,t,n),this.pageMonitor=r}getDefinition(){return{name:sa.TOOL_NAME,description:`Lists all network requests captured during page automation. Requires monitoring to be started first.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},resourceType:{type:`string`,description:`Filter by resource type (document, xhr, fetch, script, stylesheet, image, etc.)`},urlPattern:{type:`string`,description:`Filter by URL pattern (substring match)`},method:{type:`string`,description:`Filter by HTTP method (GET, POST, etc.)`},limit:{type:`number`,description:`Maximum number of requests to return`,minimum:1}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId);return this.executeWithMode(sa.TOOL_NAME,t.id,e,async()=>{let n=this.pageMonitor.getNetworkRequests(t.id);if(e.resourceType&&(n=n.filter(t=>t.resourceType===e.resourceType)),e.urlPattern){let t=e.urlPattern;n=n.filter(e=>e.url.includes(t))}return e.method&&(n=n.filter(t=>t.method===e.method)),e.limit&&(n=n.slice(0,e.limit)),this.successJson({pageId:t.id,requestCount:n.length,requests:n.map(e=>({id:e.id,url:e.url,method:e.method,resourceType:e.resourceType,status:e.response?.status,statusText:e.response?.statusText,timing:e.response?.timing,timestamp:e.timestamp.toISOString()}))})})})}};ca=sa=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.PageMonitorService)),j(`design:paramtypes`,[Object,Object,Object,Object])],ca);var la;let ua=class extends ${static{la=this}static TOOL_NAME=`browser_list_pages`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:la.TOOL_NAME,description:`Lists all pages (tabs) in a browser. Returns page IDs, URLs, titles, and indicates which page is currently active.`,inputSchema:{type:`object`,properties:{browserId:{type:`string`,description:`Browser ID to list pages for`}},required:[`browserId`],additionalProperties:!1}}}async execute(e){return this.toolExecutor.executeForBrowser(la.TOOL_NAME,e.browserId,e,async()=>{let t=this.browserService.getBrowser(e.browserId);if(!t)return this.error(`Browser "${e.browserId}" not found`);let n=this.pageRegistry.findByBrowser(e.browserId),r=await Promise.all(n.map(async e=>{await this.pageRegistry.updateMetadata(e.id);let n=this.pageRegistry.get(e.id);return{pageId:e.id,url:n?.url??e.url,title:n?.title??e.title,isActive:e.id===t.currentPageId,browserId:e.browserId,profileName:e.profileName,createdAt:e.createdAt.toISOString()}}));return this.successJson({browserId:e.browserId,currentPageId:t.currentPageId,pageCount:r.length,pages:r})})}};ua=la=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],ua);var da;let fa=class{static{da=this}static TOOL_NAME=`browser_list_profiles`;constructor(e){this.profileService=e}getDefinition(){return{name:da.TOOL_NAME,description:`Lists all available browser profiles with their settings, browser type, viewport, and timestamps.`,inputSchema:{type:`object`,properties:{},required:[],additionalProperties:!1}}}async execute(){try{let e=await this.profileService.list();return{content:[{type:`text`,text:JSON.stringify({profileCount:e.length,profiles:e.map(e=>({name:e.name,browserType:e.browserType,viewport:e.viewport??null,userAgent:e.userAgent??null,locale:e.locale??null,timezone:e.timezone??null,colorScheme:e.colorScheme??null,createdAt:e.createdAt,updatedAt:e.updatedAt}))},null,2)}]}}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}};fa=da=M([(0,d.injectable)(),F(0,(0,d.inject)(A.ProfileService)),j(`design:paramtypes`,[Object])],fa);var pa;let ma=class{static{pa=this}static TOOL_NAME=`browser_list_snippets`;constructor(e){this.snippetService=e}getDefinition(){return{name:pa.TOOL_NAME,description:`Lists saved code snippets by name, description, and snippetPath for reuse with browser_run_code.`,inputSchema:{type:`object`,properties:{},required:[],additionalProperties:!1}}}async execute(){try{let e=await this.snippetService.listSnippets();return{content:[{type:`text`,text:JSON.stringify({snippetCount:e.length,snippets:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}};ma=pa=M([(0,d.injectable)(),F(0,(0,d.inject)(A.CodeSnippetService)),j(`design:paramtypes`,[Object])],ma);var ha;let ga=class extends ${static{ha=this}static TOOL_NAME=`browser_navigate`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:ha.TOOL_NAME,description:`Navigates the browser to a specified URL.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},url:{type:`string`,description:`URL to navigate to`},waitUntil:{type:`string`,enum:[`load`,`domcontentloaded`,`networkidle`,`commit`],description:`Wait until condition`,default:`load`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:P},referer:{type:`string`,description:`Referer header value`}},required:[`pageId`,`url`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(ha.TOOL_NAME,e.pageId,e,async()=>{let t=(await this.resolvePage(e.pageId).goto(e.url,{waitUntil:e.waitUntil,timeout:e.timeout,referer:e.referer}))?.status()??`unknown`;return this.success(`Navigated to ${e.url} (status: ${t})`)})}};ga=ha=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],ga);var _a;let va=class extends ${static{_a=this}static TOOL_NAME=`browser_new_page`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:_a.TOOL_NAME,description:`Creates a new page (tab) in a browser instance. Uses the default browser if browserId is not specified, launching one if needed.`,inputSchema:{type:`object`,properties:{browserId:{type:`string`,description:`Browser ID to create the page in (optional - uses default browser if not specified)`},url:{type:`string`,description:`Optional URL to navigate to after creation`},setAsCurrent:{type:`boolean`,description:`Whether to set as current page for the browser (default: true)`,default:!0}},required:[],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=e.browserId?this.browserService.getBrowser(e.browserId):await this.browserService.getOrCreateDefaultBrowser();if(!t)return this.error(`Browser "${e.browserId}" not found`);let n=t.id,r=e.setAsCurrent!==!1;if(t.mode===`extension`||t.mode===`vm`){let i=this.pageRegistry.registerExtensionPage(n,void 0,e.url,!1),a=await this.toolExecutor.executeForBrowser(_a.TOOL_NAME,n,{...e,pageId:i},async()=>this.error(`Browser "${n}" is not in extension mode`));if(a.isError)return this.pageRegistry.remove(i),a;t.pageIds.add(i),(r||!t.currentPageId)&&(t.currentPageId=i);let o=a.content[0]?.type===`text`?a.content[0].text:void 0,s={};if(typeof o==`string`)try{s=JSON.parse(o)}catch{s={}}let c=this.pageRegistry.get(i);return c&&(c.url=s.url??c.url,c.title=s.title??c.title,c.extensionTabId=s.tabId??c.extensionTabId),this.browserService.recordBrowserActivity(n,i),this.successJson({pageId:i,url:c?.url??e.url??`about:blank`,title:c?.title??``,browserId:n,isActive:t.currentPageId===i})}let{pageId:i,page:a}=await this.browserService.newPage(n);if(e.url)try{await a.goto(e.url),await this.pageRegistry.updateMetadata(i)}catch(e){throw await a.close(),e}r&&this.browserService.setCurrentPage(n,i);let o=this.pageRegistry.get(i);return this.successJson({pageId:i,url:o?.url??a.url(),title:o?.title??``,browserId:n,isActive:r})})}};va=_a=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],va);var ya;let ba=class extends ${static{ya=this}static TOOL_NAME=`browser_pdf`;constructor(e,t,n,r){super(e,t,n),this.extensionTaskQueue=r}getDefinition(){return{name:ya.TOOL_NAME,description:`Generates a PDF of the page with configurable format options. Saves to temp directory and returns the file path.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},format:{type:`string`,enum:[`Letter`,`Legal`,`Tabloid`,`Ledger`,`A0`,`A1`,`A2`,`A3`,`A4`,`A5`,`A6`],description:`Paper format`,default:`Letter`},printBackground:{type:`boolean`,description:`Print background graphics`,default:!1},landscape:{type:`boolean`,description:`Landscape orientation`,default:!1},scale:{type:`number`,description:`Page scale (0.1 to 2)`,minimum:.1,maximum:2,default:1},marginTop:{type:`string`,description:`Top margin (e.g., "1cm", "0.5in")`},marginBottom:{type:`string`,description:`Bottom margin`},marginLeft:{type:`string`,description:`Left margin`},marginRight:{type:`string`,description:`Right margin`},filename:{type:`string`,description:`Custom filename without extension`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){let t=this.getPage(e.pageId);return t?t.mode===`extension`?this.safeExecute(async()=>{let n=e.filename??`page-${(0,k.randomUUID)()}`,r=(0,m.join)((0,C.tmpdir)(),`${n}.pdf`),i=await this.extensionTaskQueue.queueTask(ya.TOOL_NAME,{pageId:e.pageId,format:e.format,printBackground:e.printBackground,landscape:e.landscape,scale:e.scale,marginTop:e.marginTop,marginBottom:e.marginBottom,marginLeft:e.marginLeft,marginRight:e.marginRight,filename:n},void 0,t.browserId),a=JSON.parse(i.result?.content?.[0]?.text??`{}`);if(!a.pdfBase64)throw Error(`Extension mode PDF generation returned no data`);return await(0,T.writeFile)(r,Buffer.from(a.pdfBase64,`base64`)),this.success(`PDF saved to: ${r}`)}):this.executeWithMode(ya.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId),n=e.filename??`page-${(0,k.randomUUID)()}`,r=(0,m.join)((0,C.tmpdir)(),`${n}.pdf`);return await t.pdf({path:r,format:e.format??`Letter`,printBackground:e.printBackground??!1,landscape:e.landscape??!1,scale:e.scale??1,margin:{top:e.marginTop,bottom:e.marginBottom,left:e.marginLeft,right:e.marginRight}}),this.success(`PDF saved to: ${r}`)}):this.error(`Page "${e.pageId}" not found`)}};ba=ya=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.ExtensionTaskQueue)),j(`design:paramtypes`,[Object,Object,Object,Object])],ba);var xa;let Sa=class extends ${static{xa=this}static TOOL_NAME=`browser_press_key`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:xa.TOOL_NAME,description:`Presses a keyboard key or key combination. Supports modifier keys like Control, Shift, Alt, Meta.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},key:{type:`string`,description:`Key or key combination (e.g., "Enter", "Tab", "Control+a", "Meta+Shift+t", "ArrowDown")`},element:{type:`object`,description:`Optional element to focus before pressing key`,properties:{selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`}}},delay:{type:`number`,description:`Delay between keydown and keyup in ms`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:P}},required:[`pageId`,`key`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(xa.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);return e.element?await(await this.elementLocator.locate(t,e.element)).press(e.key,{delay:e.delay,timeout:e.timeout}):await t.keyboard.press(e.key,{delay:e.delay}),this.success(`Pressed key: "${e.key}"`)})}};Sa=xa=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.ElementLocatorService)),j(`design:paramtypes`,[Object,Object,Object,Object])],Sa);var Ca;let wa=class extends ${static{Ca=this}static TOOL_NAME=`browser_reload`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ca.TOOL_NAME,description:`Reloads the current page.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},waitUntil:{type:`string`,enum:[`load`,`domcontentloaded`,`networkidle`,`commit`],description:`Wait until condition`,default:`load`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:P}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ca.TOOL_NAME,e.pageId,e,async()=>{let t=(await this.resolvePage(e.pageId).reload({waitUntil:e.waitUntil,timeout:e.timeout}))?.status()??`unknown`;return this.success(`Page reloaded (status: ${t})`)})}};wa=Ca=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],wa);var Ta;let Ea=class extends ${static{Ta=this}static TOOL_NAME=`browser_resize_page`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ta.TOOL_NAME,description:`Resizes the viewport of a page to specified width and height dimensions.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},width:{type:`number`,description:`Viewport width in pixels`,minimum:1},height:{type:`number`,description:`Viewport height in pixels`,minimum:1},deviceScaleFactor:{type:`number`,description:`Device scale factor (default: 1)`,minimum:1,maximum:3},isMobile:{type:`boolean`,description:`Whether the meta viewport tag is taken into account`},hasTouch:{type:`boolean`,description:`Whether the viewport supports touch events`}},required:[`pageId`,`width`,`height`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ta.TOOL_NAME,e.pageId,{width:e.width,height:e.height},async()=>{let t=this.resolvePage(e.pageId);await t.setViewportSize({width:e.width,height:e.height});let n=t.viewportSize();return this.successJson({success:!0,viewport:{width:n?.width??e.width,height:n?.height??e.height}})})}};Ea=Ta=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],Ea);var Da;let Oa=class extends ${static{Da=this}static TOOL_NAME=`browser_run_code`;constructor(e,t,n,r,i){super(e,t,n),this.extensionPageProxy=r,this.snippetService=i}getDefinition(){return{name:Da.TOOL_NAME,description:`Runs a Playwright code snippet. The code should be an async function body that receives { page, context, browser } and can perform any Playwright operation. Return a value to include it in the response.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},code:{type:`string`,description:`JavaScript code to execute. Receives { page, context, browser } as arguments. Example: "await page.goto('https://example.com'); return await page.title();"`},snippetPath:{type:`string`,description:`Relative snippet path inside the configured snippets directory. When provided, executes the saved snippet instead of inline code.`},saveAs:{type:`object`,description:`Optional snippet metadata used to save the inline code into the configured snippets directory.`,properties:{name:{type:`string`,description:`Human-readable snippet name. The filename is generated from a sanitized version of this value.`},description:{type:`string`,description:`Short description shown by browser_list_snippets.`}},required:[`name`,`description`],additionalProperties:!1}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{if(!e.code&&!e.snippetPath)return this.error(`Either "code" or "snippetPath" is required`);if(e.saveAs&&!e.code)return this.error(`"saveAs" requires inline "code"`);let t=this.resolvePageEntry(e.pageId),{page:n,context:r,browser:i}=t,a=t.mode===`extension`?(()=>(this.extensionPageProxy.setTarget(t.id,t.browserId),this.extensionPageProxy))():n,o=t.mode===`extension`?this.extensionPageProxy.context():r,s=t.mode===`extension`?{id:t.browserId,mode:this.browserService.getBrowser(t.browserId)?.mode??`extension`,pageId:t.id}:i,c;e.saveAs&&(c=await this.snippetService.saveSnippet({name:e.saveAs.name,description:e.saveAs.description,code:e.code}));let l=e.snippetPath?await this.snippetService.loadSnippet(e.snippetPath).then(e=>e.run({page:a,context:o,browser:s})):await Function(`page`,`context`,`browser`,`return (async () => { ${e.code} })();`)(a,o,s);return l===void 0?c?this.successJson({savedSnippet:c}):this.success(`Code executed successfully`):this.successJson(c?{result:l,savedSnippet:c}:{result:l})})}};Oa=Da=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.ExtensionPageProxy)),F(4,(0,d.inject)(A.CodeSnippetService)),j(`design:paramtypes`,[Object,Object,Object,Object,Object])],Oa);var ka;const Aa=`run-spec-hooks.ts`,ja=4,Ma={width:1920,height:1080};let Na=class{static{ka=this}static TOOL_NAME=`run_spec`;constructor(e,t,n,r,i){this.automationRunner=e,this.specMetadataService=t,this.extensionSpecRunner=n,this.extensionPageProxy=r,this.specBundlerService=i}getDefinition(){return{name:ka.TOOL_NAME,description:`Runs a Playwright spec file with optional test filtering and dynamic arguments. Supports filtering by test name, pattern, or test.only markers.`,inputSchema:{type:`object`,properties:{specPath:{type:`string`,description:`Absolute path to the Playwright spec file to execute`},automationId:{type:`string`,description:`Optional automation session ID (auto-generated if not provided)`},mode:{type:`string`,enum:[`playwright`,`extension`],description:`Execution mode: playwright (standard) or extension (Chrome extension)`,default:`playwright`},browserId:{type:`string`,description:`Browser ID to use (required for extension mode)`},pageId:{type:`string`,description:`Page ID to use (required for extension mode)`},browserType:{type:`string`,enum:[`chromium`,`firefox`,`webkit`],description:`Browser type to use (only applies to playwright mode)`,default:`chromium`},headless:{type:`boolean`,description:`Run browser in headless mode (only applies to playwright mode)`,default:!0},baseURL:{type:`string`,description:`Base URL for relative navigation (e.g., page.goto("/") will use this as the base)`},keepBrowserOpen:{type:`boolean`,description:`Keep browser open after spec execution completes for further interaction`,default:!1},hooksPath:{type:`string`,description:`Explicit absolute path to run-spec-hooks.ts file. Skips auto-discovery when provided. The source directory is injected as process.env.__HOOKS_SOURCE_DIR__ so hooks can resolve paths relative to their original location.`},env:{type:`object`,description:`Environment variables to set before running the spec. Applied before hooks execution. Useful for passing config like API endpoints without relying on hooks file path resolution.`,additionalProperties:{type:`string`}},testName:{type:`string`,description:`Filter by exact test name`},testPattern:{type:`string`,description:`Filter by regex pattern on full test title (e.g., "login.*success")`},onlyMarked:{type:`boolean`,description:`Run only tests marked with test.only()`,default:!1},describeFilter:{type:`string`,description:`Filter by describe block name pattern`},specArgs:{type:`object`,description:`Arguments to pass to the spec (available as fixtures.specArgs)`,additionalProperties:!0},loadArgsFromEnv:{type:`boolean`,description:`Load specArgs from environment variables using spec's envPrefix export`,default:!1},videoDir:{type:`string`,description:`Absolute directory path to save video recordings. Supported in both playwright and extension modes.`}},required:[`specPath`],additionalProperties:!1}}}async execute(e){if(!(0,m.isAbsolute)(e.specPath))return{content:[{type:`text`,text:`Error: specPath must be an absolute path (e.g., /Users/me/project/tests/my-spec.ts)`}],isError:!0};if(e.hooksPath&&!(0,m.isAbsolute)(e.hooksPath))return{content:[{type:`text`,text:`Error: hooksPath must be an absolute path`}],isError:!0};if(e.videoDir&&!(0,m.isAbsolute)(e.videoDir))return{content:[{type:`text`,text:`Error: videoDir must be an absolute path`}],isError:!0};try{if(e.env)for(let[t,n]of Object.entries(e.env))process.env[t]=n;let t=this.resolveHooksPath(e.specPath,e.hooksPath),n=t?await this.runHooks(t):null;return n?.baseURL&&!e.baseURL&&(e.baseURL=n.baseURL),(e.mode??`playwright`)===`extension`?await this.executeExtensionMode(e):e.testName||e.testPattern||e.onlyMarked||e.describeFilter||e.loadArgsFromEnv?await this.executeEnhanced(e,t):await this.executeBasic(e,t)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}findHooksFile(e){let t=(0,m.dirname)(e);for(let e=0;e<4;e++){let e=(0,m.join)(t,`run-spec-hooks.ts`);if((0,p.existsSync)(e))return e;let n=(0,m.dirname)(t);if(n===t)break;t=n}return null}async runHooks(e){let t=(0,m.dirname)((0,m.resolve)(e)),n=await this.specBundlerService.bundle(e);try{process.env.__HOOKS_SOURCE_DIR__=t;let e=await import(`${n.outputPath}?t=${Date.now()}`);return typeof e.setup==`function`?await e.setup():void 0}finally{process.env.__HOOKS_SOURCE_DIR__=void 0,await n.cleanup()}}resolveHooksPath(e,t){return t?(0,m.resolve)(t):this.findHooksFile(e)}async executeExtensionMode(e){if(!e.pageId||!e.browserId)return{content:[{type:`text`,text:`Error: pageId and browserId are required for extension mode`}],isError:!0};this.extensionPageProxy.setTarget(e.pageId,e.browserId);let t=e.specArgs??{};if(e.loadArgsFromEnv){let n=await this.specMetadataService.extractSpecMetadata(e.specPath);n.argsSchema&&n.envPrefix&&(t={...this.specMetadataService.parseArgsFromEnv(n.argsSchema,n.envPrefix),...t})}let n={};e.testName&&(n.testName=e.testName),e.testPattern&&(n.testPattern=e.testPattern),e.onlyMarked&&(n.onlyMarked=e.onlyMarked),e.describeFilter&&(n.describeFilter=e.describeFilter);let r=e.automationId??`ext-spec-${Date.now()}`,i=!!e.videoDir;i&&await this.extensionPageProxy.startRecording();let a;try{a=await this.extensionSpecRunner.executeSpec({specPath:e.specPath,sessionId:r,testFilter:Object.keys(n).length>0?n:void 0,specArgs:Object.keys(t).length>0?t:void 0})}finally{if(i&&e.videoDir)try{let t=await this.extensionPageProxy.stopRecording();if(t){(0,p.mkdirSync)(e.videoDir,{recursive:!0});let n=(0,m.join)(e.videoDir,`recording-${r}.webm`);(0,p.writeFileSync)(n,Buffer.from(t,`base64`)),a.videoPath=n}}catch{}}return this.formatExtensionResult(a)}async executeBasic(e,t){let n=await this.automationRunner.runSpec({specPath:e.specPath,automationId:e.automationId,browserId:e.browserId,pageId:e.pageId,keepBrowserOpen:e.keepBrowserOpen??!1,recordVideo:e.videoDir?{dir:e.videoDir,size:Ma}:void 0,browserOptions:{browserType:e.browserType,headless:e.headless,baseURL:e.baseURL},hooksPath:t??void 0});return this.formatResult(n,e.keepBrowserOpen??!1)}async executeEnhanced(e,t){let n=e.specArgs??{};if(e.loadArgsFromEnv){let t=await this.specMetadataService.extractSpecMetadata(e.specPath);t.argsSchema&&t.envPrefix&&(n={...this.specMetadataService.parseArgsFromEnv(t.argsSchema,t.envPrefix),...n})}let r={};e.testName&&(r.testName=e.testName),e.testPattern&&(r.testPattern=e.testPattern),e.onlyMarked&&(r.onlyMarked=e.onlyMarked),e.describeFilter&&(r.describeFilter=e.describeFilter);let i=await this.automationRunner.runSpecEnhanced({specPath:e.specPath,automationId:e.automationId,browserId:e.browserId,pageId:e.pageId,keepBrowserOpen:e.keepBrowserOpen??!1,recordVideo:e.videoDir?{dir:e.videoDir,size:Ma}:void 0,browserOptions:{browserType:e.browserType,headless:e.headless,baseURL:e.baseURL},testFilter:Object.keys(r).length>0?r:void 0,specArgs:Object.keys(n).length>0?n:void 0,hooksPath:t??void 0});return this.formatResult(i,e.keepBrowserOpen??!1)}formatResult(e,t){let n=t?`Spec completed. Browser kept open for further interaction.`:`Spec completed.`;return{content:[{type:`text`,text:JSON.stringify({automationId:e.automationId,status:e.status,pageIds:e.pageIds,browserId:e.browserId,specResult:e.specResult,message:n},null,2)}]}}formatExtensionResult(e){let t=e.success?`Spec completed: ${e.passed}/${e.totalTests} tests passed`:`Spec failed: ${e.failed}/${e.totalTests} tests failed`;return{content:[{type:`text`,text:JSON.stringify({sessionId:e.sessionId,status:e.success?`completed`:`failed`,totalTests:e.totalTests,passed:e.passed,failed:e.failed,duration:e.duration,handoffOccurred:e.handoffOccurred,testResults:e.testResults,videoPath:e.videoPath,message:t},null,2)}],isError:!e.success}}};Na=ka=M([(0,d.injectable)(),F(0,(0,d.inject)(A.AutomationRunner)),F(1,(0,d.inject)(A.SpecMetadataService)),F(2,(0,d.inject)(A.ExtensionSpecRunner)),F(3,(0,d.inject)(A.ExtensionPageProxy)),F(4,(0,d.inject)(A.SpecBundlerService)),j(`design:paramtypes`,[Object,Object,Object,Object,Object])],Na);var Pa;let Fa=class{static{Pa=this}static TOOL_NAME=`browser_save_profile_state`;constructor(e,t,n){this.profileService=e,this.browserService=t,this.extensionPageProxy=n}getDefinition(){return{name:Pa.TOOL_NAME,description:`Saves the current browser state to the named profile for reuse across future launches.`,inputSchema:{type:`object`,properties:{profileName:{type:`string`,description:`Profile to save state into`},browserId:{type:`string`,description:`Browser to read state from`}},required:[`profileName`],additionalProperties:!1}}}async execute(e){try{let t=e.browserId?this.browserService.getBrowser(e.browserId):this.browserService.getBrowserByProfile(e.profileName);if(!t)throw Error(`Browser for profile "${e.profileName}" not found`);if(t.context){let n=await t.context.storageState();await this.profileService.saveStorageState(e.profileName,n)}else{let n=t.currentPageId??[...t.pageIds][0];if(!n)throw Error(`Browser "${t.id}" has no active page`);this.extensionPageProxy.setTarget(n,t.id);let r=await this.extensionPageProxy.getStorageState();await this.profileService.saveStorageState(e.profileName,r)}return{content:[{type:`text`,text:JSON.stringify({profileName:e.profileName,browserId:t.id,saved:!0},null,2)}]}}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}}};Fa=Pa=M([(0,d.injectable)(),F(0,(0,d.inject)(A.ProfileService)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ExtensionPageProxy)),j(`design:paramtypes`,[Object,Object,Object])],Fa);var Ia;let La=class extends ${static{Ia=this}static TOOL_NAME=`browser_screenshot`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ia.TOOL_NAME,description:`Captures a screenshot of the page or specific element. Saves to temp directory and returns the file path.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},fullPage:{type:`boolean`,description:`Capture full page scrollable area`,default:!1},selector:{type:`string`,description:`CSS selector for element to screenshot`},clip:{type:`object`,description:`Clip region to capture by coordinates (cannot be used with selector)`,properties:{x:{type:`number`,description:`X coordinate of top-left corner`,minimum:0},y:{type:`number`,description:`Y coordinate of top-left corner`,minimum:0},width:{type:`number`,description:`Width of clipping region`,minimum:1},height:{type:`number`,description:`Height of clipping region`,minimum:1}},required:[`x`,`y`,`width`,`height`],additionalProperties:!1},type:{type:`string`,enum:[`png`,`jpeg`],description:`Image format`,default:`png`},quality:{type:`number`,description:`Quality for jpeg format (0-100)`,minimum:0,maximum:100},omitBackground:{type:`boolean`,description:`Omit background for transparent PNG`,default:!1},filename:{type:`string`,description:`Custom filename without extension`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ia.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);if(e.clip&&e.selector)throw Error(`Cannot use both clip and selector options together`);let n=e.type??`png`,r=e.filename??`screenshot-${(0,k.randomUUID)()}`,i=(0,m.join)((0,C.tmpdir)(),`${r}.${n}`);if(e.selector){let r=await t.$(e.selector);if(!r)throw Error(`Element not found: ${e.selector}`);await r.screenshot({path:i,type:n,omitBackground:e.omitBackground??!1,quality:n===`jpeg`?e.quality:void 0})}else await t.screenshot({path:i,type:n,fullPage:e.fullPage??!1,omitBackground:e.omitBackground??!1,quality:n===`jpeg`?e.quality:void 0,clip:e.clip});return this.success(`Screenshot saved to: ${i}`)})}};La=Ia=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],La);var Ra;let za=class extends ${static{Ra=this}static TOOL_NAME=`browser_select_page`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ra.TOOL_NAME,description:`Switches the active page for a browser. Updates the current page ID so subsequent operations use this page by default.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to set as current`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.pageRegistry.get(e.pageId);if(!t)return this.error(`Page "${e.pageId}" not found`);let{browserId:n}=t;if(t.mode===`extension`||t.mode===`vm`){let t=await this.executeWithMode(Ra.TOOL_NAME,e.pageId,e,async()=>this.error(`Page "${e.pageId}" is not in extension mode`));if(t.isError)return t}this.browserService.setCurrentPage(n,e.pageId),this.browserService.recordBrowserActivity(n,e.pageId),await this.pageRegistry.updateMetadata(e.pageId);let r=this.pageRegistry.get(e.pageId);return this.successJson({browserId:n,pageId:e.pageId,url:r?.url??t.url,title:r?.title??t.title,message:`Page "${e.pageId}" is now the active page for browser "${n}"`})})}};za=Ra=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],za);var Ba;let Va=class extends ${static{Ba=this}static TOOL_NAME=`browser_select`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:Ba.TOOL_NAME,description:`Selects option(s) from a dropdown/select element. Can select by value, label, or index.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`},values:{type:`array`,items:{type:`string`},description:`Option value(s) to select`},labels:{type:`array`,items:{type:`string`},description:`Option label(s) to select`},indexes:{type:`array`,items:{type:`number`},description:`Option index(es) to select`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:P}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ba.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId),n=await this.elementLocator.locate(t,e),r=[];e.values?r=e.values.map(e=>({value:e})):e.labels?r=e.labels.map(e=>({label:e})):e.indexes&&(r=e.indexes.map(e=>({index:e})));let i=await n.selectOption(r,{timeout:e.timeout});return this.success(`Selected ${i.length} option(s): ${i.join(`, `)}`)})}};Va=Ba=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.ElementLocatorService)),j(`design:paramtypes`,[Object,Object,Object,Object])],Va);var Ha;const Ua=1e4;let Wa=class extends ${static{Ha=this}static TOOL_NAME=`browser_snapshot`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ha.TOOL_NAME,description:`Returns the accessibility tree snapshot of the page. Preferred for LLM processing as it provides structured, semantic information about page content.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},root:{type:`string`,description:`CSS selector for root element to snapshot (defaults to body)`},sizeThreshold:{type:`number`,description:`Size threshold in bytes; snapshots larger than this are saved to file (default: 10000)`,default:1e4}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ha.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId),n=e.root??`body`,r=t.locator(n);if(await r.count()===0)throw Error(`Root element not found: ${n}`);let i=await r.ariaSnapshot();if(!i)return this.success(`No accessibility tree available for this page`);let a=e.sizeThreshold??1e4;if(Buffer.byteLength(i,`utf-8`)<=a)return this.success(i);let o=`snapshot-${(0,k.randomUUID)()}.yaml`,s=(0,m.join)((0,C.tmpdir)(),o);return await(0,T.writeFile)(s,i,`utf-8`),this.success(`Snapshot saved to: ${s}`)})}};Wa=Ha=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],Wa);var Ga;let Ka=class extends ${static{Ga=this}static TOOL_NAME=`browser_start_trace`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ga.TOOL_NAME,description:`Starts Playwright performance tracing with configurable options for screenshots, snapshots, and sources. Use browser_stop_trace to stop and save the trace.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},name:{type:`string`,description:`Name for the trace (used in trace filename)`},screenshots:{type:`boolean`,description:`Whether to capture screenshots during tracing (default: true)`},snapshots:{type:`boolean`,description:`Whether to capture snapshots during tracing (default: true)`},sources:{type:`boolean`,description:`Whether to include source files in the trace (default: false)`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId),n=t.context;if(!n)return this.error(`Page "${e.pageId}" is in extension mode and cannot start tracing`);let{name:r,screenshots:i=!0,snapshots:a=!0,sources:o=!1}=e;return await n.tracing.start({name:r,screenshots:i,snapshots:a,sources:o}),this.successJson({success:!0,message:`Tracing started`,pageId:t.id,options:{name:r??null,screenshots:i,snapshots:a,sources:o}})})}};Ka=Ga=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],Ka);var qa;let Ja=class extends ${static{qa=this}static TOOL_NAME=`browser_start_recording`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:qa.TOOL_NAME,description:`Starts recording an existing extension/vm browser page and saves the artifact to the provided path or a temporary .webm file.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`The page ID to record.`},path:{type:`string`,description:`Optional absolute output path for the .webm file. If omitted, browse-tool creates a temporary recording path.`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId);if(t.mode!==`extension`&&t.mode!==`vm`)return this.error(`Page "${e.pageId}" is in "${t.mode}" mode and cannot use extension recording`);if(e.path){if(!m.default.isAbsolute(e.path))return this.error(`Recording path must be an absolute path (e.g., /Users/me/project/recording.webm)`);if(m.default.extname(e.path).toLowerCase()!==`.webm`)return this.error(`Recording path must end with .webm`)}let n=await this.browserService.startPageRecording(t.browserId,t.id,e.path);return this.successJson({started:!0,browserId:t.browserId,pageId:t.id,outputPath:n.outputPath})})}};Ja=qa=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],Ja);var Ya;let Xa=class extends ${static{Ya=this}static TOOL_NAME=`browser_stop_trace`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ya.TOOL_NAME,description:`Stops Playwright performance tracing and saves the trace file to a specified path. The trace can be viewed using Playwright Trace Viewer.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},path:{type:`string`,description:`Absolute path where the trace file should be saved (e.g., "/Users/me/project/traces/trace.zip"). Must end with .zip extension.`}},required:[`pageId`,`path`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId),n=t.context;if(!n)return this.error(`Page "${e.pageId}" is in extension mode and cannot stop tracing`);let r=e.path;return m.default.isAbsolute(r)?r.endsWith(`.zip`)?(await n.tracing.stop({path:r}),this.successJson({success:!0,message:`Tracing stopped and saved`,pageId:t.id,tracePath:r,viewCommand:`npx playwright show-trace ${r}`})):this.error(`Trace path must end with .zip extension`):this.error(`Trace path must be an absolute path (e.g., /Users/me/project/traces/trace.zip)`)})}};Xa=Ya=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],Xa);var Za;let Qa=class extends ${static{Za=this}static TOOL_NAME=`browser_stop_recording`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Za.TOOL_NAME,description:`Stops an active extension/vm browser recording and returns the saved .webm path with optional base64 payload.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`The page ID whose recording should be stopped.`},includeBase64:{type:`boolean`,description:`Whether to include the base64-encoded WebM payload in the response.`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId);if(t.mode!==`extension`&&t.mode!==`vm`)return this.error(`Page "${e.pageId}" is in "${t.mode}" mode and cannot use extension recording`);let n=await this.browserService.stopPageRecording(t.browserId,t.id,{includeBase64:e.includeBase64});return this.successJson({stopped:!0,browserId:t.browserId,pageId:t.id,outputPath:n.outputPath,fileSizeBytes:n.fileSizeBytes,...n.videoBase64?{videoBase64:n.videoBase64}:{}})})}};Qa=Za=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],Qa);var $a;let eo=class extends ${static{$a=this}static TOOL_NAME=`browser_type`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:$a.TOOL_NAME,description:`Types text into an element character by character, simulating real keyboard input. Does not clear existing content. Use browser_fill for replacing content.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`},text:{type:`string`,description:`The text to type character by character`},delay:{type:`number`,description:`Delay between key presses in ms`,default:0},timeout:{type:`number`,description:`Timeout in milliseconds`,default:P}},required:[`pageId`,`text`],additionalProperties:!1}}}async execute(e){return this.executeWithMode($a.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);return await(await this.elementLocator.locate(t,{selector:e.selector,xpath:e.xpath,uid:e.uid,frame:e.frame})).pressSequentially(e.text,{delay:e.delay,timeout:e.timeout}),this.success(`Typed: "${e.text}"`)})}};eo=$a=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.ElementLocatorService)),j(`design:paramtypes`,[Object,Object,Object,Object])],eo);var to;let no=class extends ${static{to=this}static TOOL_NAME=`browser_upload_file`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:to.TOOL_NAME,description:`Uploads file(s) to a file input element.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`},files:{oneOf:[{type:`string`,description:`Single file path to upload`},{type:`array`,items:{type:`string`},description:`Multiple file paths to upload`}],description:`File path(s) to upload`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:P}},required:[`pageId`,`files`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(to.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);await(await this.elementLocator.locate(t,e)).setInputFiles(e.files,{timeout:e.timeout});let n=Array.isArray(e.files)?e.files.length:1;return this.success(`Uploaded ${n} file(s) successfully`)})}};no=to=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),F(3,(0,d.inject)(A.ElementLocatorService)),j(`design:paramtypes`,[Object,Object,Object,Object])],no);var ro;let io=class extends ${static{ro=this}static TOOL_NAME=`browser_wait_for`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:ro.TOOL_NAME,description:`Waits for a condition to be met: element visibility, text appearance, timeout duration, or page load state.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},type:{type:`string`,enum:[`element`,`text`,`timeout`,`loadState`],description:`Type of wait condition`},selector:{type:`string`,description:`CSS selector for element wait`},text:{type:`string`,description:`Text to wait for (supports regex patterns)`},duration:{type:`number`,description:`Duration in milliseconds for timeout wait`},state:{type:`string`,enum:[`load`,`domcontentloaded`,`networkidle`],description:`Load state to wait for`},elementState:{type:`string`,enum:[`attached`,`detached`,`visible`,`hidden`],description:`Element state to wait for`,default:`visible`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:P}},required:[`pageId`],additionalProperties:!1}}}async execute(e){let t=e.type??(e.text?`text`:e.selector||e.elementState?`element`:e.duration===void 0?e.state?`loadState`:void 0:`timeout`);if(!t)return this.error(`Unable to infer wait type. Provide "type" or one of selector, text, duration, or state.`);if(t===`timeout`){let t=e.duration??1e3;return await new Promise(e=>setTimeout(e,t)),this.success(`Waited for ${t}ms`)}return this.executeWithMode(ro.TOOL_NAME,e.pageId,{...e,type:t},async()=>{let n=this.resolvePage(e.pageId);switch(t){case`element`:if(!e.selector)throw Error(`selector is required for element wait`);return await n.locator(e.selector).waitFor({state:e.elementState??`visible`,timeout:e.timeout}),this.success(`Element "${e.selector}" is ${e.elementState??`visible`}`);case`text`:if(!e.text)throw Error(`text is required for text wait`);return await n.getByText(e.text).waitFor({state:`visible`,timeout:e.timeout}),this.success(`Text "${e.text}" appeared on page`);case`loadState`:{let t=e.state??`load`;return await n.waitForLoadState(t,{timeout:e.timeout}),this.success(`Page reached "${t}" state`)}default:throw Error(`Unknown wait type: ${t}`)}})}};io=ro=M([(0,d.injectable)(),F(0,(0,d.inject)(A.PageRegistry)),F(1,(0,d.inject)(A.BrowserService)),F(2,(0,d.inject)(A.ToolExecutor)),j(`design:paramtypes`,[Object,Object,Object])],io);const ao=new d.ContainerModule(e=>{e.bind(A.PortRegistryService).toDynamicValue(()=>new S.PortRegistryService(process.env.PORT_REGISTRY_PATH)).inSingletonScope(),e.bind(A.HttpServerHealthCheck).to(U).inSingletonScope(),e.bind(A.HttpServerManager).to(Sr).inSingletonScope(),e.bind(A.McpSessionTracker).to(J).inSingletonScope()}),oo=new d.ContainerModule(e=>{e.bind(A.ProfileService).to(Mr).inSingletonScope(),e.bind(A.PageRegistry).to(Ar).inSingletonScope(),e.bind(A.BrowserService).to(Cn).inSingletonScope(),e.bind(A.BrowserLockManager).to(ft).inSingletonScope(),e.bind(A.ChromeForTestingService).to(Tt).inSingletonScope(),e.bind(A.ElementLocatorService).to(kn).inSingletonScope(),e.bind(A.PageMonitorService).to(kr).inSingletonScope(),e.bind(A.PauseController).to(jr).inSingletonScope(),e.bind(A.SpecBundlerService).to(Hr).inSingletonScope(),e.bind(A.SpecDiscoveryService).to(Ur).inSingletonScope(),e.bind(A.SpecMetadataService).to(Wr).inSingletonScope(),e.bind(A.SetupRunner).to(Pr).inSingletonScope(),e.bind(A.WebServerManager).to(Yr).inSingletonScope(),e.bind(A.SpecRunner).to(Gr).inSingletonScope(),e.bind(A.AutomationRunner).to(ut).inSingletonScope(),e.bind(A.TelemetryService).to(N).inSingletonScope(),e.bind(A.CodeSnippetService).toDynamicValue(()=>new On(process.env.BROWSE_TOOL_SNIPPETS_DIR)).inSingletonScope(),e.bind(A.ExtensionTaskQueue).to(I).inSingletonScope(),e.bind(A.ExtensionToolDelegator).to(L).inSingletonScope(),e.bind(A.ToolExecutor).to(Jr).inSingletonScope(),e.bind(A.ExtensionSessionRegistry).to(Pn).inSingletonScope(),e.bind(A.ExtensionPageProxy).to(Nn).inSingletonScope(),e.bind(A.ExtensionSpecRunner).to(Fn).inSingletonScope(),e.bind(A.StealthLauncher).to(Kr).inSingletonScope(),e.bind(A.HttpServerHealthCheck).to(U).inSingletonScope(),e.bind(A.HttpBrowserClient).to(Vn).inSingletonScope(),e.bind(A.RemoteToolExecutor).to(Nr).inSingletonScope(),e.bind(A.WebSocketHub).to(pi).inSingletonScope(),e.bind(A.IdleCleanupService).to(Or).inSingletonScope()}),so=new d.ContainerModule(e=>{e.bind(A.Tool).to(hi).inSingletonScope(),e.bind(A.Tool).to(Fi).inSingletonScope(),e.bind(A.Tool).to(eo).inSingletonScope(),e.bind(A.Tool).to(Va).inSingletonScope(),e.bind(A.Tool).to(Gi).inSingletonScope(),e.bind(A.Tool).to(Di).inSingletonScope(),e.bind(A.Tool).to(Sa).inSingletonScope(),e.bind(A.Tool).to(no).inSingletonScope(),e.bind(A.Tool).to(ga).inSingletonScope(),e.bind(A.Tool).to(zi).inSingletonScope(),e.bind(A.Tool).to(Vi).inSingletonScope(),e.bind(A.Tool).to(wa).inSingletonScope(),e.bind(A.Tool).to(io).inSingletonScope(),e.bind(A.Tool).to(Wa).inSingletonScope(),e.bind(A.Tool).to(La).inSingletonScope(),e.bind(A.Tool).to(ba).inSingletonScope(),e.bind(A.Tool).to(ua).inSingletonScope(),e.bind(A.Tool).to(va).inSingletonScope(),e.bind(A.Tool).to(za).inSingletonScope(),e.bind(A.Tool).to(yi).inSingletonScope(),e.bind(A.Tool).to(Ui).inSingletonScope(),e.bind(A.Tool).to(ca).inSingletonScope(),e.bind(A.Tool).to(Li).inSingletonScope(),e.bind(A.Tool).to(oa).inSingletonScope(),e.bind(A.Tool).to(ji).inSingletonScope(),e.bind(A.Tool).to(ki).inSingletonScope(),e.bind(A.Tool).to(Ea).inSingletonScope(),e.bind(A.Tool).to(Ni).inSingletonScope(),e.bind(A.Tool).to(Ja).inSingletonScope(),e.bind(A.Tool).to(Qa).inSingletonScope(),e.bind(A.Tool).to(Ka).inSingletonScope(),e.bind(A.Tool).to(Xa).inSingletonScope(),e.bind(A.Tool).to(fa).inSingletonScope(),e.bind(A.Tool).to(ma).inSingletonScope(),e.bind(A.Tool).to(xi).inSingletonScope(),e.bind(A.Tool).to(Ci).inSingletonScope(),e.bind(A.Tool).to(Fa).inSingletonScope(),e.bind(A.Tool).to(Na).inSingletonScope(),e.bind(A.Tool).to(Ti).inSingletonScope(),e.bind(A.Tool).to(ia).inSingletonScope(),e.bind(A.Tool).to(_i).inSingletonScope(),e.bind(A.Tool).to(Oa).inSingletonScope()});function co(){let e=new d.Container({defaultScope:`Singleton`});return e.load(ao),e}function lo(){let e=new d.Container({defaultScope:`Singleton`});return e.load(oo,so),e}const uo=new d.ContainerModule(e=>{e.bind(A.PortRegistryService).toDynamicValue(()=>new S.PortRegistryService(process.env.PORT_REGISTRY_PATH)).inSingletonScope(),e.bind(A.ProfileService).to(Mr).inSingletonScope(),e.bind(A.PageRegistry).to(Ar).inSingletonScope(),e.bind(A.BrowserService).to(Cn).inSingletonScope(),e.bind(A.ElementLocatorService).to(kn).inSingletonScope(),e.bind(A.PageMonitorService).to(kr).inSingletonScope(),e.bind(A.PauseController).to(jr).inSingletonScope(),e.bind(A.SpecBundlerService).to(Hr).inSingletonScope(),e.bind(A.SpecDiscoveryService).to(Ur).inSingletonScope(),e.bind(A.SpecMetadataService).to(Wr).inSingletonScope(),e.bind(A.SetupRunner).to(Pr).inSingletonScope(),e.bind(A.WebServerManager).to(Yr).inSingletonScope(),e.bind(A.SpecRunner).to(Gr).inSingletonScope(),e.bind(A.AutomationRunner).to(ut).inSingletonScope(),e.bind(A.HttpServerHealthCheck).to(U).inSingletonScope(),e.bind(A.HttpServerManager).to(Sr).inSingletonScope(),e.bind(A.HttpBrowserClient).to(Vn).inSingletonScope(),e.bind(A.RemoteToolExecutor).to(Nr).inSingletonScope(),e.bind(A.ExtensionTaskQueue).to(I).inSingletonScope(),e.bind(A.ExtensionToolDelegator).to(L).inSingletonScope(),e.bind(A.ToolExecutor).to(Jr).inSingletonScope(),e.bind(A.StealthLauncher).to(Kr).inSingletonScope(),e.bind(A.BrowserLockManager).to(ft).inSingletonScope(),e.bind(A.ExtensionSessionRegistry).to(Pn).inSingletonScope(),e.bind(A.ExtensionPageProxy).to(Nn).inSingletonScope(),e.bind(A.ExtensionSpecRunner).to(Fn).inSingletonScope(),e.bind(A.McpSessionTracker).to(J).inSingletonScope(),e.bind(A.ChromeForTestingService).to(Tt).inSingletonScope(),e.bind(A.IdleCleanupService).to(Or).inSingletonScope()}),fo=new d.Container({defaultScope:`Singleton`});fo.load(uo,so);function po(){let e=new d.Container({defaultScope:`Singleton`});return e.load(uo,so),e}var mo=class extends Error{code=`TRANSPORT_CONNECTION_ERROR`;recovery=`Check that stdio streams are available and try again.`;constructor(e,t){super(e,t),this.name=`TransportConnectionError`}},ho=class{server;transport=null;constructor(e){this.server=e}async start(){let e=new l.StdioServerTransport;try{await this.server.connect(e),this.transport=e,console.error(`browse-tool MCP server started on stdio`)}catch(t){try{await e.close()}catch{}let n=new mo(`Failed to establish stdio transport connection`,{cause:t});throw console.error(`[${n.code}] ${n.message}. Recovery: ${n.recovery}`),n}}async stop(){this.transport&&=(await this.transport.close(),null)}},go=class extends Error{code=`TRANSPORT_CONNECTION_ERROR`;recovery=`Check that the HTTP host and port are available and try again.`;constructor(e,t){super(e,t),this.name=`TransportConnectionError`}};async function _o(e){let t=[];for await(let n of e)t.push(typeof n==`string`?Buffer.from(n):n);if(t.length===0)return;let n=Buffer.concat(t).toString(`utf8`).trim();if(n)return JSON.parse(n)}function vo(e,t,n){e.headersSent||(e.writeHead(t,{"Content-Type":`application/json`}),e.end(JSON.stringify(n)))}var yo=class{sessions=new Map;get(e){return this.sessions.get(e)}set(e,t){this.sessions.set(e,t)}has(e){return this.sessions.has(e)}async delete(e){let t=this.sessions.get(e);t&&(this.sessions.delete(e),t.server.close(),await t.onClose?.())}async clear(){let e=[...this.sessions.keys()];for(let t of e)await this.delete(t)}},bo=class{sessionFactory;config;sessionManager=new yo;httpServer=null;constructor(e,t){this.sessionFactory=e,this.config={host:t.host,port:t.port,path:t.path??`/mcp`}}async createSession(e,t){if(!(0,u.isInitializeRequest)(t))throw Error(`No valid session ID provided`);let n=this.sessionFactory({headers:e.headers}),r=new ae.StreamableHTTPServerTransport({sessionIdGenerator:()=>(0,k.randomUUID)(),enableJsonResponse:!0,onsessioninitialized:e=>{this.sessionManager.set(e,{server:n.server,transport:r,onClose:n.onClose})},onsessionclosed:async e=>{await this.sessionManager.delete(e)}});return r.onclose=()=>{r.sessionId&&this.sessionManager.delete(r.sessionId)},await n.server.connect(r),r}async handleMcpRequest(e,t){let n=e.headers[`mcp-session-id`],r=Array.isArray(n)?n[0]:n,i;if(e.method===`POST`)try{i=await _o(e)}catch(e){vo(t,400,{jsonrpc:`2.0`,error:{code:-32700,message:e instanceof Error?e.message:`Invalid JSON body`},id:null});return}let a;if(r?a=this.sessionManager.get(r)?.transport:e.method===`POST`&&(a=await this.createSession(e,i)),!a){vo(t,r?404:400,{jsonrpc:`2.0`,error:{code:-32e3,message:r?`Session not found`:`Bad Request: No valid session ID provided`},id:null});return}await a.handleRequest(e,t,i)}async start(){if(this.httpServer)throw new go(`HTTP transport server is already running`);await new Promise((e,t)=>{let n=(0,ie.createServer)((e,t)=>{(async()=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??this.config.host}`).pathname;if(n===`/health`&&e.method===`GET`){vo(t,200,{status:`ok`,transport:`streamable-http`});return}if(n!==this.config.path){vo(t,404,{error:`Not found`});return}await this.handleMcpRequest(e,t)}catch(e){vo(t,500,{jsonrpc:`2.0`,error:{code:-32603,message:(e instanceof Error?e:Error(String(e))).message},id:null})}})()});n.once(`error`,e=>{t(new go(`Failed to establish streamable HTTP transport connection`,{cause:e}))}),n.listen(this.config.port,this.config.host,()=>{this.httpServer=n,process.stderr.write(`browse-tool MCP server started on http://${this.config.host}:${this.config.port}${this.config.path}\n`),process.stderr.write(`Health check: http://${this.config.host}:${this.config.port}/health\n`),e()})})}async stop(){if(await this.sessionManager.clear(),!this.httpServer)return;let e=this.httpServer;this.httpServer=null,await new Promise((t,n)=>{e.close(e=>{if(e){n(e);return}t()})})}};Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return nt}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return gt}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return lo}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return I}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return Er}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return Bn}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return mt}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return Bt}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return po}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return Ln}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return Wt}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return ho}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return co}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return Nn}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return fo}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return J}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return bo}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return pt}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return N}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return L}});
15
- //# sourceMappingURL=streamable-http-CDH-wHjE.cjs.map
14
+ Linux: sudo apt install google-chrome-stable`);let n=this.resolveExtensionPath(e.extensionPath),r=this.createUserDataDir(e.profileName);await this.lockManager.ensureAvailable(r);let i=`stealth-browser-${++this.browserIdCounter}`,a=[n];e.proxy?.username&&e.proxy?.password&&a.push(Xt(e.proxy.username,e.proxy.password));let o=a.join(`,`),s=(0,T.spawn)(t,[`--user-data-dir=${r}`,`--load-extension=${o}`,`--disable-extensions-except=${o}`,`--disable-blink-features=AutomationControlled`,`--disable-infobars`,`--no-first-run`,`--no-default-browser-check`,`--disable-background-timer-throttling`,`--disable-backgrounding-occluded-windows`,`--disable-renderer-backgrounding`,`--disable-component-update`,`--disable-features=TranslateUI`,`--disable-ipc-flooding-protection`,`--password-store=basic`,`--use-mock-keychain`,`--disable-dev-shm-usage`,`--disable-gpu-sandbox`,...e.windowSize?[`--window-size=${e.windowSize.width},${e.windowSize.height}`]:[`--window-size=1280,720`],...e.proxy?Zt(e.proxy):[],e.url??`about:blank`,...e.extraArgs??[]],{detached:!1,stdio:[`ignore`,`ignore`,`ignore`],env:{...process.env,DISPLAY:process.env.DISPLAY}});if(!s.pid)throw Error(`Failed to start Chrome process`);let c={id:i,process:s,pid:s.pid,userDataDir:r,extensionPath:n,profileName:e.profileName,createdAt:new Date,isRunning:!0};return s.on(`exit`,()=>{c.isRunning=!1}),s.on(`error`,e=>{console.error(`Chrome process ${i} error:`,e),c.isRunning=!1}),this.browsers.set(i,c),this.pageRegistry.registerExtensionPage(i),c}async close(e){let t=this.browsers.get(e);if(t&&(t.isRunning&&t.pid&&await Yt(t.pid),t.isRunning=!1,this.browsers.delete(e),!t.profileName&&t.userDataDir.includes(`stealth-chrome-`)))try{p.default.rmSync(t.userDataDir,{recursive:!0,force:!0})}catch{}}async closeAll(){let e=Array.from(this.browsers.keys()).map(e=>this.close(e));await Promise.all(e)}getBrowser(e){return this.browsers.get(e)}listBrowsers(){return Array.from(this.browsers.values()).filter(e=>e.isRunning)}};Yr=j([(0,d.injectable)(),P(0,(0,d.inject)(k.ProfileService)),P(1,(0,d.inject)(k.PageRegistry)),P(2,(0,d.inject)(k.BrowserLockManager)),A(`design:paramtypes`,[Object,Object,Object])],Yr);function Xr(e){if(!e.isError)return;let t=e.content[0];return t?.type===`text`&&typeof t.text==`string`?t.text:`Unknown tool execution error`}let Zr=class{constructor(e,t,n,r=new M){this.pageRegistry=e,this.browserService=t,this.delegator=n,this.telemetry=r}async execute(e,t,n,r){return this.telemetry.runInSpan(`browse_tool.tool_executor.page`,{attributes:{"browse_tool.tool.name":e,"browse_tool.page.id":t}},async i=>{let a=this.pageRegistry.get(t);if(!a)return i?.setStatus({code:h.SpanStatusCode.ERROR,message:`Page "${t}" not found`}),{content:[{type:`text`,text:`Page "${t}" not found`}],isError:!0};i?.setAttributes({"browse_tool.browser.id":a.browserId,"browse_tool.execution.mode":a.mode});let o=a.mode===`extension`?await this.delegator.executeTool(e,{pageId:t,browserId:a.browserId,...n}):await r(),s=Xr(o);if(s)i?.setStatus({code:h.SpanStatusCode.ERROR,message:s});else if(a.mode===`extension`)try{await this.browserService.ensureExtensionRecordingActive(a.browserId,t)}catch(e){console.warn(`[ToolExecutor] Failed to start extension recording for browser "${a.browserId}" on page "${t}":`,e)}return o})}isExtensionMode(e){return this.pageRegistry.get(e)?.mode===`extension`}async executeForBrowser(e,t,n,r){return this.telemetry.runInSpan(`browse_tool.tool_executor.browser`,{attributes:{"browse_tool.tool.name":e,"browse_tool.browser.id":t}},async i=>{let a=this.browserService.getBrowser(t);if(!a)return i?.setStatus({code:h.SpanStatusCode.ERROR,message:`Browser "${t}" not found`}),{content:[{type:`text`,text:`Browser "${t}" not found`}],isError:!0};i?.setAttributes({"browse_tool.execution.mode":a.mode});let o=a.mode===`extension`||a.mode===`vm`?await this.delegator.executeTool(e,{browserId:t,...n}):await r(),s=Xr(o);return s&&i?.setStatus({code:h.SpanStatusCode.ERROR,message:s}),o})}isBrowserExtensionMode(e){let t=this.browserService.getBrowser(e);return t?.mode===`extension`||t?.mode===`vm`}};Zr=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ExtensionToolDelegator)),P(3,(0,d.inject)(k.TelemetryService)),A(`design:paramtypes`,[Object,Object,Object,Object])],Zr);let Qr=class{serverProcess=null;currentUrl=null;cleanupRegistered=!1;constructor(){this.registerCleanup()}registerCleanup(){if(this.cleanupRegistered)return;this.cleanupRegistered=!0;let e=()=>this.cleanupSync();process.on(`exit`,e),process.on(`SIGINT`,e),process.on(`SIGTERM`,e)}async startServer(e,t){let{command:n,url:r,reuseExistingServer:i=!1,timeout:a=3e4,cwd:o}=e;if(i&&await this.isServerRunning(r))return this.currentUrl=r,{started:!1,url:r,reused:!0};await this.stopServer();let s=o?(0,m.resolve)(t,o):t,[c,...l]=this.parseCommand(n);if(this.serverProcess=(0,T.spawn)(c,l,{cwd:s,shell:!0,stdio:[`ignore`,`pipe`,`pipe`],detached:!1}),this.currentUrl=r,this.serverProcess.on(`error`,e=>{console.error(`Server process error: ${e.message}`)}),!await this.waitForServer(r,a))throw await this.stopServer(),Error(`Server failed to start within ${a}ms. URL: ${r}, Command: ${n}`);return{started:!0,url:r,reused:!1}}async waitForServer(e,t){let n=Date.now(),r=100;for(;Date.now()-n<t;){if(await this.isServerRunning(e))return!0;await this.sleep(r),r=Math.min(r*1.5,2e3)}return!1}async stopServer(){if(this.serverProcess)return new Promise(e=>{if(!this.serverProcess){e();return}let t=this.serverProcess;this.serverProcess=null,this.currentUrl=null;let n=setTimeout(()=>{try{t.kill(`SIGKILL`)}catch{}e()},5e3);t.on(`exit`,()=>{clearTimeout(n),e()});try{t.kill(`SIGTERM`)}catch{clearTimeout(n),e()}})}async isServerRunning(e){try{let t=new AbortController,n=setTimeout(()=>t.abort(),3e3),r=await fetch(e,{method:`HEAD`,signal:t.signal});return clearTimeout(n),r.status>=200&&r.status<400}catch{return!1}}parseCommand(e){let t=[],n=``,r=!1,i=``;for(let a of e)(a===`"`||a===`'`)&&!r?(r=!0,i=a):a===i&&r?(r=!1,i=``):a===` `&&!r?n&&=(t.push(n),``):n+=a;return n&&t.push(n),t}sleep(e){return new Promise(t=>setTimeout(t,e))}getCurrentUrl(){return this.currentUrl}cleanupSync(){if(this.serverProcess){try{this.serverProcess.kill(`SIGKILL`)}catch{}this.serverProcess=null,this.currentUrl=null}}};Qr=j([(0,d.injectable)(),A(`design:paramtypes`,[])],Qr);const $r=S.z.object({type:S.z.string(),text:S.z.string().optional(),data:S.z.string().optional(),mimeType:S.z.string().optional()}),ei=S.z.object({traceId:S.z.string().regex(/^[0-9a-f]{32}$/i).optional(),parentSpanId:S.z.string().regex(/^[0-9a-f]{16}$/i).optional()}),ti=S.z.object({content:S.z.array($r),isError:S.z.boolean().optional()}),ni=S.z.object({type:S.z.literal(`task:push`),id:S.z.string(),payload:S.z.object({taskId:S.z.string(),tool:S.z.string(),arguments:S.z.record(S.z.string(),S.z.unknown()),pageId:S.z.string().optional(),telemetry:ei.optional()})}),ri=S.z.object({type:S.z.literal(`page:created`),payload:S.z.object({pageId:S.z.string(),browserId:S.z.string(),url:S.z.string().optional()})}),ii=S.z.object({type:S.z.literal(`page:removed`),payload:S.z.object({pageId:S.z.string()})}),ai=S.z.object({type:S.z.literal(`session:ack`),id:S.z.string(),payload:S.z.object({sessionId:S.z.string(),controlMode:S.z.string()})}),oi=S.z.object({type:S.z.literal(`pong`)}),si=S.z.object({type:S.z.literal(`error`),payload:S.z.object({message:S.z.string(),code:S.z.string().optional()})}),ci=S.z.discriminatedUnion(`type`,[ni,ri,ii,ai,oi,si]),li=S.z.object({type:S.z.literal(`session:register`),id:S.z.string(),payload:S.z.object({browserId:S.z.string(),tabId:S.z.number().optional(),url:S.z.string().optional()})}),ui=S.z.object({type:S.z.literal(`task:result`),payload:S.z.object({taskId:S.z.string(),success:S.z.boolean(),result:ti.optional(),error:S.z.string().optional()})}),di=S.z.object({type:S.z.literal(`tab:mapped`),payload:S.z.object({pageId:S.z.string(),tabId:S.z.number()})}),fi=S.z.object({type:S.z.literal(`ping`)}),pi=S.z.object({type:S.z.literal(`heartbeat`),payload:S.z.object({sessionId:S.z.string(),tabId:S.z.number().optional(),url:S.z.string().optional()})}),mi=S.z.discriminatedUnion(`type`,[li,ui,di,fi,pi]);function hi(e){let t=mi.safeParse(e);return t.success?t.data:null}let gi=class{connections=new Map;browserConnections=new Map;eventHandlers={};maxConnections=100;setEventHandlers(e){this.eventHandlers=e}addConnection(e,t){if(this.connections.size>=this.maxConnections)throw Error(`Maximum connections (${this.maxConnections}) reached`);let n=crypto.randomUUID(),r={id:n,ws:e,browserId:t,connectedAt:new Date,lastMessageAt:new Date};return this.connections.set(n,r),this.browserConnections.has(t)||this.browserConnections.set(t,new Set),this.browserConnections.get(t).add(n),console.log(`[WebSocketHub] Connection added: ${n} for browser ${t}`),n}removeConnection(e){let t=this.connections.get(e);if(!t)return;this.eventHandlers.onDisconnect?.(t);let n=this.browserConnections.get(t.browserId);n&&(n.delete(e),n.size===0&&this.browserConnections.delete(t.browserId)),this.connections.delete(e),console.log(`[WebSocketHub] Connection removed: ${e}`)}getConnection(e){return this.connections.get(e)}getConnectionsByBrowser(e){let t=this.browserConnections.get(e);return t?Array.from(t).map(e=>this.connections.get(e)).filter(e=>e!==void 0):[]}hasConnection(e){return this.browserConnections.has(e)&&(this.browserConnections.get(e)?.size??0)>0}reassignConnection(e,t){let n=this.connections.get(e);if(!n)return!1;let r=n.browserId;if(r===t)return!0;let i=this.browserConnections.get(r);return i&&(i.delete(e),i.size===0&&this.browserConnections.delete(r)),this.browserConnections.has(t)||this.browserConnections.set(t,new Set),this.browserConnections.get(t).add(e),n.browserId=t,!0}handleMessage(e,t){let n=this.connections.get(e);if(!n){console.warn(`[WebSocketHub] Message from unknown connection: ${e}`);return}n.lastMessageAt=new Date;try{let r=typeof t==`string`?t:new TextDecoder().decode(t),i=JSON.parse(r),a=hi(i);if(!a){console.warn(`[WebSocketHub] Invalid message format from ${e}:`,i),this.sendError(n,`Invalid message format`);return}this.routeMessage(n,a)}catch(t){console.error(`[WebSocketHub] Error parsing message from ${e}:`,t),this.sendError(n,`Failed to parse message`)}}routeMessage(e,t){switch(t.type){case`session:register`:this.eventHandlers.onSessionRegister?.(e,t);break;case`task:result`:this.eventHandlers.onTaskResult?.(e,t);break;case`tab:mapped`:this.eventHandlers.onTabMapped?.(e,t);break;case`heartbeat`:this.eventHandlers.onHeartbeat?.(e,t);break;case`ping`:this.sendToConnection(e,{type:`pong`});break}}sendToConnection(e,t){try{return e.ws.send(JSON.stringify(t)),!0}catch(t){return console.error(`[WebSocketHub] Failed to send to ${e.id}:`,t),!1}}sendError(e,t,n){this.sendToConnection(e,{type:`error`,payload:{message:t,code:n}})}pushTask(e,t){let n=this.getConnectionsByBrowser(e);if(n.length===0)return console.warn(`[WebSocketHub] No connections for browser ${e}`),!1;let r=n[0];return this.sendToConnection(r,t)}broadcastPageCreated(e,t,n){let r={type:`page:created`,payload:{pageId:t,browserId:e,url:n}},i=this.getConnectionsByBrowser(e);for(let e of i)this.sendToConnection(e,r)}broadcastPageRemoved(e,t){let n={type:`page:removed`,payload:{pageId:t}},r=this.getConnectionsByBrowser(e);for(let e of r)this.sendToConnection(e,n)}sendSessionAck(e,t,n,r){e.sessionId=n;let i={type:`session:ack`,id:t,payload:{sessionId:n,controlMode:r}};this.sendToConnection(e,i)}getStats(){return{totalConnections:this.connections.size,browserCount:this.browserConnections.size,connections:Array.from(this.connections.values()).map(e=>({id:e.id,browserId:e.browserId,connectedAt:e.connectedAt}))}}closeAll(){for(let[e,t]of this.connections){try{t.ws.close()}catch{}this.removeConnection(e)}}};gi=j([(0,d.injectable)()],gi);let Q=class{constructor(e,t,n){this.pageRegistry=e,this.browserService=t,this.toolExecutor=n}getPage(e){return this.pageRegistry.get(e)}resolvePage(e){let t=this.pageRegistry.get(e);if(!t)throw Error(`Page "${e}" not found`);if(!t.page)throw Error(`Page "${e}" is in extension mode and has no Playwright page`);return t.page}resolvePageEntry(e){let t=this.pageRegistry.get(e);if(!t)throw Error(`Page "${e}" not found`);return t}success(e){return{content:[{type:`text`,text:e}]}}successJson(e){return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}successImage(e,t=`image/png`){return{content:[{type:`image`,data:e,mimeType:t}]}}error(e){return{content:[{type:`text`,text:e}],isError:!0}}async safeExecute(e){try{return await e()}catch(e){let t=e instanceof Error?e.message:String(e);return this.error(t)}}async executeWithMode(e,t,n,r){return this.toolExecutor.execute(e,t,n,r)}};Q=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],Q);var _i;let vi=class extends Q{static{_i=this}static TOOL_NAME=`browser_click`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:_i.TOOL_NAME,description:`Clicks on an element on the page. Supports CSS selector, XPath, text content, or accessibility snapshot UID for element identification.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},selector:{type:`string`,description:`CSS selector (e.g., "button.submit", "#login-btn")`},xpath:{type:`string`,description:`XPath expression (e.g., "//button[@type='submit']")`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID reference`},frame:{type:`string`,description:`Frame selector for iframe content`},clickCount:{type:`number`,description:`Number of clicks (default: 1, use 2 for double-click)`,default:1},button:{type:`string`,enum:[`left`,`middle`,`right`],description:`Mouse button to use`,default:`left`},modifiers:{type:`array`,items:{type:`string`,enum:[`Alt`,`Control`,`Meta`,`Shift`]},description:`Modifier keys to hold during click`},delay:{type:`number`,description:`Time to wait between mousedown and mouseup in ms`},position:{type:`object`,properties:{x:{type:`number`},y:{type:`number`}},description:`Position offset within the element`},timeout:{type:`number`,description:`Timeout in milliseconds (default: ${N})`,default:N}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(_i.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);return await(await this.elementLocator.locate(t,{selector:e.selector,xpath:e.xpath,text:e.text,uid:e.uid,frame:e.frame})).click({clickCount:e.clickCount,button:e.button,modifiers:e.modifiers,delay:e.delay,position:e.position,timeout:e.timeout}),this.success(`Clicked element successfully`)})}};vi=_i=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.ElementLocatorService)),A(`design:paramtypes`,[Object,Object,Object,Object])],vi);var yi;let bi=class extends Q{static{yi=this}static TOOL_NAME=`browser_close`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:yi.TOOL_NAME,description:`Closes a browser instance by its ID. Terminates the browser process, cleans up all associated pages, and releases resources. Works for all modes: playwright, extension, vm (Docker), and stealth.`,inputSchema:{type:`object`,properties:{browserId:{type:`string`,description:`The browser ID to close (returned by browser_launch)`}},required:[`browserId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.browserService.getBrowser(e.browserId);if(!t)return this.error(`Browser "${e.browserId}" not found`);let n=t.pageIds.size,r=t.mode??`playwright`;return await this.browserService.closeBrowser(e.browserId),this.successJson({closedBrowserId:e.browserId,mode:r,pagesRemoved:n,message:`Browser "${e.browserId}" closed successfully`})})}};bi=yi=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],bi);var xi;let Si=class extends Q{static{xi=this}static TOOL_NAME=`browser_close_page`;constructor(e,t,n,r){super(e,t,n),this.profileService=r}getDefinition(){return{name:xi.TOOL_NAME,description:`Closes a page (tab) by its ID. Removes the page from the session and registry. If closed page was current, another page becomes current.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to close`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.pageRegistry.get(e.pageId);if(!t)return this.error(`Page "${e.pageId}" not found`);let{browserId:n,profileName:r,mode:i}=t,a=this.browserService.getBrowser(n);if(!a)return this.error(`Browser "${n}" not found`);let o=a.currentPageId===e.pageId,s=a.pageIds.size===1;if(i===`extension`||i===`vm`){let t=await this.executeWithMode(xi.TOOL_NAME,e.pageId,e,async()=>this.error(`Page "${e.pageId}" is not in extension mode`));if(t.isError)return t;if(await this.browserService.finalizeExtensionRecording(n,e.pageId),this.pageRegistry.remove(e.pageId),a.pageIds.delete(e.pageId),a.currentPageId===e.pageId&&(a.currentPageId=Array.from(a.pageIds)[0]??null),s)try{await this.browserService.closeBrowser(n)}catch(e){console.error(`Failed to close extension browser "${n}" after last tab shutdown:`,e)}return this.successJson({closedPageId:e.pageId,browserId:n,wasCurrentPage:o,newCurrentPageId:a.currentPageId,browserKeptOpen:!s,message:s?`Page "${e.pageId}" closed. Browser "${n}" was also closed because no tabs remained.`:`Page "${e.pageId}" closed successfully`})}if(!t.page)return this.error(`Page "${e.pageId}" is in extension mode and cannot be closed via Playwright`);await t.page.close();let c=this.browserService.getBrowser(n)?.currentPageId??null;if(s){if(r&&a.context)try{let e=await a.context.storageState();await this.profileService.saveStorageState(r,e)}catch(e){console.error(`Failed to auto-save profile "${r}":`,e)}if(!r)try{await this.browserService.closeBrowser(n)}catch(e){console.error(`Failed to auto-close browser "${n}":`,e)}}return this.successJson({closedPageId:e.pageId,browserId:n,wasCurrentPage:o,newCurrentPageId:c,browserKeptOpen:s&&!!r,message:s&&r?`Page "${e.pageId}" closed. Browser kept open for profile "${r}" reuse.`:`Page "${e.pageId}" closed successfully`})})}};Si=xi=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.ProfileService)),A(`design:paramtypes`,[Object,Object,Object,Object])],Si);var Ci;let wi=class{static{Ci=this}static TOOL_NAME=`browser_create_profile`;constructor(e){this.profileService=e}getDefinition(){return{name:Ci.TOOL_NAME,description:`Creates a browser profile for persistent browser settings and session reuse.`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Unique profile name`},browserType:{type:`string`,enum:[`chromium`,`firefox`,`webkit`],description:`Preferred browser type for the profile`,default:`chromium`},viewport:{type:`object`,properties:{width:{type:`number`},height:{type:`number`}},required:[`width`,`height`],additionalProperties:!1},userAgent:{type:`string`},locale:{type:`string`},timezone:{type:`string`},colorScheme:{type:`string`,enum:[`light`,`dark`,`no-preference`]}},required:[`name`],additionalProperties:!1}}}async execute(e){try{let t=await this.profileService.create({name:e.name,browserType:e.browserType??`chromium`,viewport:e.viewport,userAgent:e.userAgent,locale:e.locale,timezone:e.timezone,colorScheme:e.colorScheme});return{content:[{type:`text`,text:JSON.stringify(t,null,2)}]}}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}}};wi=Ci=j([(0,d.injectable)(),P(0,(0,d.inject)(k.ProfileService)),A(`design:paramtypes`,[Object])],wi);var Ti;let Ei=class{static{Ti=this}static TOOL_NAME=`browser_delete_profile`;constructor(e){this.profileService=e}getDefinition(){return{name:Ti.TOOL_NAME,description:`Deletes a browser profile and all its associated storage state data.`,inputSchema:{type:`object`,properties:{name:{type:`string`,description:`Name of the profile to delete`}},required:[`name`],additionalProperties:!1}}}async execute(e){try{return await this.profileService.delete(e.name),{content:[{type:`text`,text:JSON.stringify({success:!0,message:`Profile "${e.name}" deleted successfully`},null,2)}]}}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}};Ei=Ti=j([(0,d.injectable)(),P(0,(0,d.inject)(k.ProfileService)),A(`design:paramtypes`,[Object])],Ei);var Di;let Oi=class{static{Di=this}static TOOL_NAME=`discover_specs`;constructor(e){this.specDiscoveryService=e}getDefinition(){return{name:Di.TOOL_NAME,description:`Discovers e2e projects (directories with playwright.config.ts) and their spec files. Use to find available specs before running them.`,inputSchema:{type:`object`,properties:{basePath:{type:`string`,description:`Absolute path to search for e2e projects (required)`},projectName:{type:`string`,description:`Filter by project name (e.g., 'boomlink-e2e')`},specPattern:{type:`string`,description:`Filter specs by name pattern (supports * and ? wildcards, e.g., "auth*", "*.spec.ts")`},includeMetadata:{type:`boolean`,description:`Include metadata like hasArgsSchema detection (default: true)`,default:!0}},required:[`basePath`],additionalProperties:!1}}}async execute(e){if(!e.basePath||!(0,m.isAbsolute)(e.basePath))return{content:[{type:`text`,text:`Error: basePath must be an absolute path (e.g., /Users/me/project)`}],isError:!0};try{let t=e.basePath,n=e.includeMetadata!==!1;if(e.projectName||e.specPattern){let r=await this.specDiscoveryService.filterSpecs(t,{projectName:e.projectName,specPattern:e.specPattern}),i={filter:{basePath:t,projectName:e.projectName,specPattern:e.specPattern},totalSpecs:r.length,specs:r.map(e=>({name:e.name,path:e.path,relativePath:e.relativePath,...n&&{hasArgsSchema:e.hasArgsSchema}}))};return{content:[{type:`text`,text:JSON.stringify(i,null,2)}]}}let r=await this.specDiscoveryService.discoverProjects(t),i={basePath:t,totalProjects:r.length,totalSpecs:r.reduce((e,t)=>e+t.specs.length,0),projects:r.map(e=>({name:e.name,path:e.path,configPath:e.configPath,testDir:e.testDir,specCount:e.specs.length,specs:e.specs.map(e=>({name:e.name,path:e.path,relativePath:e.relativePath,...n&&{hasArgsSchema:e.hasArgsSchema}}))}))};return{content:[{type:`text`,text:JSON.stringify(i,null,2)}]}}catch(e){return{content:[{type:`text`,text:`Error discovering specs: ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}};Oi=Di=j([(0,d.injectable)(),P(0,(0,d.inject)(k.SpecDiscoveryService)),A(`design:paramtypes`,[Object])],Oi);var ki;let Ai=class extends Q{static{ki=this}static TOOL_NAME=`browser_drag`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:ki.TOOL_NAME,description:`Drags an element to a target location or element.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},source:{type:`object`,description:`Source element selector`,properties:{selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`}}},target:{type:`object`,description:`Target element selector or coordinates`,properties:{selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`},x:{type:`number`,description:`X coordinate`},y:{type:`number`,description:`Y coordinate`}}},force:{type:`boolean`,description:`Bypass actionability checks`,default:!1},timeout:{type:`number`,description:`Timeout in milliseconds`,default:N}},required:[`pageId`,`source`,`target`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(ki.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId),n=await this.elementLocator.locate(t,e.source);if(`x`in e.target&&`y`in e.target)await n.dragTo(t.locator(`body`),{targetPosition:{x:e.target.x,y:e.target.y},force:e.force,timeout:e.timeout});else{let r=await this.elementLocator.locate(t,e.target);await n.dragTo(r,{force:e.force,timeout:e.timeout})}return this.success(`Dragged element successfully`)})}};Ai=ki=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.ElementLocatorService)),A(`design:paramtypes`,[Object,Object,Object,Object])],Ai);var ji;let Mi=class extends Q{static{ji=this}static TOOL_NAME=`browser_emulate`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:ji.TOOL_NAME,description:`Emulates device characteristics like geolocation, timezone, locale, color scheme, and network conditions.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},geolocation:{type:`object`,description:`Geolocation coordinates to emulate`,properties:{latitude:{type:`number`,minimum:-90,maximum:90},longitude:{type:`number`,minimum:-180,maximum:180},accuracy:{type:`number`,minimum:0}},required:[`latitude`,`longitude`]},locale:{type:`string`,description:`Locale to emulate (e.g., "en-US", "de-DE")`},timezone:{type:`string`,description:`Timezone to emulate (e.g., "America/New_York", "Europe/London")`},userAgent:{type:`string`,description:`User agent string to use`},offline:{type:`boolean`,description:`Whether to emulate offline mode`},colorScheme:{type:`string`,enum:[`light`,`dark`,`no-preference`],description:`Color scheme preference`},reducedMotion:{type:`string`,enum:[`reduce`,`no-preference`],description:`Reduced motion preference`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(ji.TOOL_NAME,e.pageId,e,async()=>this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId),n=t.context,r=t.page;if(!n||!r)return this.error(`Page "${e.pageId}" is in extension mode and cannot be emulated via Playwright`);let i={};return e.geolocation&&(await n.setGeolocation(e.geolocation),i.geolocation=e.geolocation),e.offline!==void 0&&(await n.setOffline(e.offline),i.offline=e.offline),e.colorScheme&&(await r.emulateMedia({colorScheme:e.colorScheme}),i.colorScheme=e.colorScheme),e.reducedMotion&&(await r.emulateMedia({reducedMotion:e.reducedMotion}),i.reducedMotion=e.reducedMotion),e.locale&&(i.locale=e.locale,i.localeNote=`Locale changes may require a new browser context to take full effect`),e.timezone&&(i.timezone=e.timezone,i.timezoneNote=`Timezone changes may require a new browser context to take full effect`),e.userAgent&&(i.userAgent=e.userAgent,i.userAgentNote=`User agent changes may require a new browser context to take full effect`),this.successJson({success:!0,pageId:t.id,appliedSettings:i})}))}};Mi=ji=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],Mi);var Ni;let Pi=class extends Q{static{Ni=this}static TOOL_NAME=`browser_evaluate_script`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ni.TOOL_NAME,description:`Executes JavaScript code in the page context and returns the result. The script can be a function body or an expression.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},script:{type:`string`,description:`JavaScript code to execute. Can be a function body or expression (e.g., "document.title" or "() => window.location.href")`},arg:{description:`Optional argument to pass to the script if it is a function`}},required:[`pageId`,`script`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ni.TOOL_NAME,e.pageId,{script:e.script,arg:e.arg},async()=>{let t=await this.resolvePage(e.pageId).evaluate(e.script,e.arg),n;try{n=JSON.stringify(t,null,2)}catch{n=String(t)}let r=`evaluate-${(0,O.randomUUID)()}.json`,i=(0,m.join)((0,x.tmpdir)(),r);return await(0,w.writeFile)(i,n,`utf-8`),this.success(`Result saved to: ${i}`)})}};Pi=Ni=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],Pi);var Fi;let Ii=class extends Q{static{Fi=this}static TOOL_NAME=`browser_expect`;constructor(e,t,n,r){super(e,t,n),this.extensionPageProxy=r}getDefinition(){return{name:Fi.TOOL_NAME,description:`Performs Playwright expect() assertions on page elements. Supports various assertion types like toBeVisible, toHaveText, toHaveValue, toBeEnabled, etc.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},selector:{type:`string`,description:`CSS selector for the element to assert on (not required for page-level assertions like toHaveTitle, toHaveURL)`},assertion:{type:`string`,enum:[`toBeVisible`,`toBeHidden`,`toBeEnabled`,`toBeDisabled`,`toBeChecked`,`toBeEditable`,`toBeFocused`,`toBeEmpty`,`toHaveText`,`toContainText`,`toHaveValue`,`toHaveAttribute`,`toHaveClass`,`toHaveCount`,`toHaveCSS`,`toHaveId`,`toHaveTitle`,`toHaveURL`],description:`Type of assertion to perform`},expected:{oneOf:[{type:`string`},{type:`number`}],description:`Expected value for assertions that require one (e.g., toHaveText, toHaveValue)`},attributeName:{type:`string`,description:`Attribute name for toHaveAttribute or toHaveCSS assertion`},not:{type:`boolean`,description:`Whether to negate the assertion (not.toBeVisible, etc.)`},timeout:{type:`number`,description:`Timeout in milliseconds for the assertion (default: 5000)`}},required:[`pageId`,`assertion`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId),n=t.mode===`extension`?(()=>(this.extensionPageProxy.setTarget(t.id,t.browserId),this.extensionPageProxy))():this.resolvePage(e.pageId),{selector:r,assertion:i,expected:a,attributeName:o,not:s,timeout:l=5e3}=e,u=[`toHaveTitle`,`toHaveURL`];if(!u.includes(i)&&!r)return this.error(`Selector is required for assertion type: ${i}`);try{if(u.includes(i)){let e=s?c.a(n).not:c.a(n);i===`toHaveTitle`?await e.toHaveTitle(a,{timeout:l}):i===`toHaveURL`&&await e.toHaveURL(a,{timeout:l})}else{let e=n.locator(r),t=s?c.a(e).not:c.a(e);switch(i){case`toBeVisible`:await t.toBeVisible({timeout:l});break;case`toBeHidden`:await t.toBeHidden({timeout:l});break;case`toBeEnabled`:await t.toBeEnabled({timeout:l});break;case`toBeDisabled`:await t.toBeDisabled({timeout:l});break;case`toBeChecked`:await t.toBeChecked({timeout:l});break;case`toBeEditable`:await t.toBeEditable({timeout:l});break;case`toBeFocused`:await t.toBeFocused({timeout:l});break;case`toBeEmpty`:await t.toBeEmpty({timeout:l});break;case`toHaveText`:await t.toHaveText(a,{timeout:l});break;case`toContainText`:await t.toContainText(a,{timeout:l});break;case`toHaveValue`:await t.toHaveValue(a,{timeout:l});break;case`toHaveAttribute`:if(!o)return this.error(`attributeName is required for toHaveAttribute assertion`);await t.toHaveAttribute(o,a,{timeout:l});break;case`toHaveClass`:await t.toHaveClass(a,{timeout:l});break;case`toHaveCount`:await t.toHaveCount(a,{timeout:l});break;case`toHaveCSS`:if(!o)return this.error(`attributeName (CSS property name) is required for toHaveCSS assertion`);await t.toHaveCSS(o,a,{timeout:l});break;case`toHaveId`:await t.toHaveId(a,{timeout:l});break;default:return this.error(`Unsupported assertion type: ${i}`)}}return this.successJson({success:!0,assertion:s?`not.${i}`:i,selector:r??null,passed:!0})}catch(e){let t=e instanceof Error?e.message:`Assertion failed`;return this.successJson({success:!0,assertion:s?`not.${i}`:i,selector:r??null,passed:!1,failureMessage:t})}})}};Ii=Fi=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.ExtensionPageProxy)),A(`design:paramtypes`,[Object,Object,Object,Object])],Ii);var Li;let Ri=class extends Q{static{Li=this}static TOOL_NAME=`browser_fill`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:Li.TOOL_NAME,description:`Fills an input field with text, clearing any existing content first. Use for form inputs, textareas, and contenteditable elements.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`},value:{type:`string`,description:`The text value to fill into the input`},force:{type:`boolean`,description:`Bypass actionability checks`,default:!1},timeout:{type:`number`,description:`Timeout in milliseconds`,default:N}},required:[`pageId`,`value`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Li.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);return await(await this.elementLocator.locate(t,e)).fill(e.value,{force:e.force,timeout:e.timeout}),this.success(`Filled element with: "${e.value}"`)})}};Ri=Li=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.ElementLocatorService)),A(`design:paramtypes`,[Object,Object,Object,Object])],Ri);var zi;let Bi=class extends Q{static{zi=this}static TOOL_NAME=`browser_get_network_request`;constructor(e,t,n,r){super(e,t,n),this.pageMonitor=r}getDefinition(){return{name:zi.TOOL_NAME,description:`Retrieves detailed information about a specific network request by ID, including headers, body, and response data.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},requestId:{type:`string`,description:`The ID of the network request to retrieve (e.g., "req-1")`}},required:[`pageId`,`requestId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId);return this.executeWithMode(zi.TOOL_NAME,t.id,e,async()=>{let n=this.pageMonitor.getNetworkRequest(t.id,e.requestId);return n?this.successJson({id:n.id,url:n.url,method:n.method,resourceType:n.resourceType,headers:n.headers,postData:n.postData,timestamp:n.timestamp.toISOString(),response:n.response?{status:n.response.status,statusText:n.response.statusText,headers:n.response.headers,timing:n.response.timing}:null}):this.error(`Network request "${e.requestId}" not found for page "${t.id}"`)})})}};Bi=zi=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.PageMonitorService)),A(`design:paramtypes`,[Object,Object,Object,Object])],Bi);var Vi;let Hi=class extends Q{static{Vi=this}static TOOL_NAME=`browser_go_back`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Vi.TOOL_NAME,description:`Navigates the browser back in history.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},waitUntil:{type:`string`,enum:[`load`,`domcontentloaded`,`networkidle`,`commit`],description:`Wait until condition`,default:`load`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:N}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Vi.TOOL_NAME,e.pageId,e,async()=>{let t=await this.resolvePage(e.pageId).goBack({waitUntil:e.waitUntil,timeout:e.timeout});if(t===null)return this.success(`No previous page in history`);let n=t.status();return this.success(`Navigated back (status: ${n})`)})}};Hi=Vi=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],Hi);var Ui;let Wi=class extends Q{static{Ui=this}static TOOL_NAME=`browser_go_forward`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ui.TOOL_NAME,description:`Navigates the browser forward in history.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},waitUntil:{type:`string`,enum:[`load`,`domcontentloaded`,`networkidle`,`commit`],description:`Wait until condition`,default:`load`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:N}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ui.TOOL_NAME,e.pageId,e,async()=>{let t=await this.resolvePage(e.pageId).goForward({waitUntil:e.waitUntil,timeout:e.timeout});if(t===null)return this.success(`No next page in history`);let n=t.status();return this.success(`Navigated forward (status: ${n})`)})}};Wi=Ui=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],Wi);var Gi;let Ki=class extends Q{static{Gi=this}static TOOL_NAME=`browser_handle_dialog`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Gi.TOOL_NAME,description:`Handles JavaScript dialogs (alert, confirm, prompt) by accepting or dismissing them. Set up a listener before triggering the action that opens the dialog.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},accept:{type:`boolean`,description:`Whether to accept (true) or dismiss (false) the dialog`},promptText:{type:`string`,description:`Text to enter for prompt dialogs (only used when accept is true)`},timeout:{type:`number`,description:`Timeout in milliseconds to wait for dialog (default: ${N})`,default:N}},required:[`pageId`,`accept`],additionalProperties:!1}}}async execute(e){return this.safeExecute(()=>this.executeWithMode(Gi.TOOL_NAME,e.pageId,{accept:e.accept,promptText:e.promptText,timeout:e.timeout},async()=>{let t=this.resolvePage(e.pageId),n=e.timeout??N,r=setTimeout(()=>{t.off(`dialog`,i)},n),i=async n=>{clearTimeout(r);try{e.accept?await n.accept(e.promptText):await n.dismiss()}finally{t.off(`dialog`,i)}};return t.once(`dialog`,i),this.successJson({armed:!0,action:e.accept?`accept`:`dismiss`,timeout:n,promptText:e.promptText??null})}))}};Ki=Gi=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],Ki);var qi;let Ji=class extends Q{static{qi=this}static TOOL_NAME=`browser_hover`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:qi.TOOL_NAME,description:`Hovers over an element to trigger hover states, tooltips, or dropdown menus.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`},position:{type:`object`,properties:{x:{type:`number`},y:{type:`number`}},description:`Position offset within element`},modifiers:{type:`array`,items:{type:`string`,enum:[`Alt`,`Control`,`Meta`,`Shift`]},description:`Modifier keys to hold`},force:{type:`boolean`,description:`Bypass actionability checks`,default:!1},timeout:{type:`number`,description:`Timeout in milliseconds`,default:N}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(qi.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);return await(await this.elementLocator.locate(t,e)).hover({position:e.position,modifiers:e.modifiers,force:e.force,timeout:e.timeout}),this.success(`Hovered over element successfully`)})}};Ji=qi=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.ElementLocatorService)),A(`design:paramtypes`,[Object,Object,Object,Object])],Ji);var Yi;const Xi=[`pnpm-workspace.yaml`,`nx.json`,`.git`],Zi=`about:blank`,Qi=`browser-extension-`,$i=process.env.BROWSE_TOOL_DEBUG_EXTENSION_RECORDING===`1`,ea=`browse-tool-http`,ta=`tool`,na=`development`,ra=`host.docker.internal`,ia=`[LaunchBrowserTool]`,aa=new Set([`docker`,`docker-vm`,`docker-chromium`,`docker-chrome-testing`]);function oa(e=process.cwd()){let t=m.default.resolve(e);for(;;){for(let e of Xi)if((0,p.existsSync)(m.default.join(t,e)))return t;let e=m.default.dirname(t);if(e===t)return process.cwd();t=e}}let sa=class{static{Yi=this}static TOOL_NAME=`browser_launch`;constructor(e,t){this.browserService=e,this.stealthLauncher=t}getDefinition(){return{name:Yi.TOOL_NAME,description:`Launches a new browser instance. Returns browserId and pageId for subsequent browser operations. Use mode "extension" for bot-detection-free automation via Chrome extension, or mode "vm" for isolated runtime launch.`,inputSchema:{type:`object`,properties:{mode:{type:`string`,enum:[`playwright`,`extension`,`vm`,`stealth`],description:`Execution mode. "playwright" uses Playwright APIs. "extension" uses Playwright with Chrome extension. "vm" launches in an isolated runtime (for example via Docker). "stealth" spawns Chrome directly without automation flags.`,default:`playwright`},browserType:{type:`string`,enum:[`chromium`,`firefox`,`webkit`],description:`Browser type to use (only applies to playwright mode)`,default:`chromium`},headless:{type:`boolean`,description:`Run browser in headless mode (only applies to playwright mode)`,default:!0},url:{type:`string`,description:`Optional URL to navigate to after launch`},profileName:{type:`string`,description:`Optional profile name to use for browser settings and persistent storage`},vmCommand:{type:`string`,description:`Executable/alias for vm mode launch (e.g., "docker" for isolated container runtime)`},vmCommandArgs:{type:`array`,description:`Browser arguments for vm command runtime`,items:{type:`string`}},vmUseChromeForTesting:{type:`boolean`,description:`When true, vm mode prefers Chrome for Testing. If command is omitted, "chrome-testing" alias, or generic "chrome", this resolves to Chrome for Testing.`,default:!0},vmBrowserId:{type:`string`,description:`Optional browserId override for vm mode`},startupDelayMs:{type:`number`,description:`Optional startup delay in milliseconds before returning in vm mode`},vmServerUrl:{type:`string`,description:`Explicit MCP server URL reachable from inside VM (e.g., "http://host.docker.internal:3200"). Overrides registry discovery.`},vmExtensionPath:{type:`string`,description:`Explicit extension path that exists inside VM filesystem. Useful when VM does not share host workspace paths.`},vmEnableVnc:{type:`boolean`,description:`Expose VNC/noVNC ports when using Docker VM runtime`,default:!1},vmVncPort:{type:`number`,description:`Host port for VNC (container port 5900) when vmEnableVnc is true`,minimum:1,maximum:65535},vmNoVncPort:{type:`number`,description:`Host port for noVNC web UI (container port 7900) when vmEnableVnc is true`,minimum:1,maximum:65535},vmVncPassword:{type:`string`,description:`Optional VNC password for Docker VM runtime`},baseURL:{type:`string`,description:`Base URL for relative navigation (e.g., page.goto("/") will use this as the base)`},videoDir:{type:`string`,description:`Directory to save video recordings. If provided, video will be recorded for all pages. Videos are saved when the page or context is closed.`},proxy:{type:`object`,description:`Proxy configuration for routing browser traffic through a proxy server. Supports authenticated residential proxies.`,properties:{server:{type:`string`,description:`Proxy server URL (e.g., "http://proxy.example.com:8080")`},username:{type:`string`,description:`Proxy username for authentication`},password:{type:`string`,description:`Proxy password for authentication`},bypass:{type:`string`,description:`Comma-separated list of hosts to bypass the proxy (e.g., "localhost,127.0.0.1")`}},required:[`server`],additionalProperties:!1}},required:[],additionalProperties:!1}}}async execute(e){let t=e.mode??`playwright`;try{return t===`stealth`?await this.launchStealthMode(e):t===`vm`?await this.launchVmMode(e):t===`extension`?await this.launchExtensionMode(e):await this.launchPlaywrightMode(e)}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}}async launchPlaywrightMode(e){let t=await this.browserService.launch({browserType:e.browserType,headless:e.headless,profileName:e.profileName,baseURL:e.baseURL,recordVideo:e.videoDir?{dir:e.videoDir}:void 0,proxy:e.proxy});return e.url&&await t.page.goto(e.url),{content:[{type:`text`,text:JSON.stringify({browserId:t.browserInstance.id,pageId:t.pageId,mode:`playwright`,url:e.url??t.page.url()},null,2)}]}}async launchStealthMode(e){let t=await this.stealthLauncher.launch({url:e.url,profileName:e.profileName,proxy:e.proxy});return{content:[{type:`text`,text:JSON.stringify({browserId:t.id,pageId:`page-${t.id}`,mode:`stealth`,url:e.url??`about:blank`,pid:t.pid},null,2)}]}}async launchExtensionMode(e){$i&&console.log(`[ExtensionRecordingDebug] launch tool mode=extension videoDir=${e.videoDir??``} url=${e.url??``}`);let t=e.profileName?`browser-${e.profileName}`:`browser-extension-${(0,O.randomUUID)()}`,n=e.url??Zi,r=await this.resolveExtensionBootstrapServerUrl(),i=this.buildVmBootstrapUrl(r,t,n),a=await this.browserService.launchWithExtension({url:i,baseURL:e.baseURL,profileName:e.profileName,recordVideo:e.videoDir?{dir:e.videoDir}:void 0,proxy:e.proxy,mode:`extension`,browserId:t});return{content:[{type:`text`,text:JSON.stringify({browserId:a.browserInstance.id,pageId:a.pageId,mode:`extension`,url:n,pid:a.process.pid},null,2)}]}}async launchVmMode(e){let t=e.vmBrowserId??`browser-vm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,n=e.url??Zi,r=e.vmCommand??`docker`,i=await this.resolveVmBootstrapServerUrl(e.vmServerUrl,r),a=this.buildVmBootstrapUrl(i,t,n),o=this.buildVmDockerRuntimeOptions(e),s=await this.browserService.launchWithExtension({url:a,baseURL:e.baseURL,profileName:e.profileName,recordVideo:e.videoDir?{dir:e.videoDir}:void 0,proxy:e.proxy,extensionPath:e.vmExtensionPath??process.env.PLAYWRIGHT_VM_EXTENSION_PATH,mode:`vm`,useChromeForTesting:e.vmUseChromeForTesting??!0,command:r,commandArgs:e.vmCommandArgs,dockerRunArgs:o.runArgs,dockerEnv:o.env,dockerEnableVnc:o.enableVnc,browserId:t,startupDelayMs:e.startupDelayMs}),c=o.vnc?{vncUrl:o.vnc.vncUrl,noVncUrl:o.vnc.noVncUrl}:void 0;return{content:[{type:`text`,text:JSON.stringify({browserId:s.browserInstance.id,pageId:s.pageId,mode:`vm`,url:n,pid:s.process.pid,...c?{vm:c}:{}},null,2)}]}}buildVmBootstrapUrl(e,t,n){let r=new URL(e);return r.searchParams.set(`playwright_mcp_connect`,`1`),r.searchParams.set(`playwright_mcp_server`,e),r.searchParams.set(`playwright_mcp_browser_id`,t),r.searchParams.set(`playwright_mcp_navigate`,n),r.toString()}async resolveVmBootstrapServerUrl(e,t){let n=e??process.env.PLAYWRIGHT_VM_SERVER_URL;if(n)return this.normalizeVmServerUrl(n);let r=B(),i=await this.getRegisteredPort(r);return this.isDockerVmCommand(t??`docker`)?V(`host.docker.internal`,i.port):V(i.host,i.port)}async resolveExtensionBootstrapServerUrl(){let e=B(),t=await this.getRegisteredPort(e);return V(t.host,t.port)}normalizeVmServerUrl(e){let t;try{t=new URL(e)}catch{throw Error(`Invalid vmServerUrl: "${e}"`)}if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`vmServerUrl must use http or https: "${e}"`);return t.origin}isDockerVmCommand(e){return aa.has(e.trim().toLowerCase())}buildVmDockerRuntimeOptions(e){let t=e.vmEnableVnc||e.vmVncPort!==void 0||e.vmNoVncPort!==void 0,n=[],r={},i;if(t){let t=e.vmVncPort??5901,r=e.vmNoVncPort??7901;n.push(`-p`,`${t}:5900`,`-p`,`${r}:7900`),i={vncUrl:`vnc://localhost:${t}`,noVncUrl:`http://localhost:${r}/`}}return e.vmVncPassword&&e.vmVncPassword.trim().length>0&&(r.SE_VNC_PASSWORD=e.vmVncPassword.trim()),{runArgs:n.length>0?n:void 0,env:Object.keys(r).length>0?r:void 0,enableVnc:t,vnc:i}}getFallbackPort(){try{return Bn()}catch{return 3200}}isValidPort(e){return typeof e==`number`&&Number.isInteger(e)&&e>0&&e<=65535}getLatestRegistryEntry(e){return e.length===0?null:[...e].sort((e,t)=>{let n=Number.isNaN(Date.parse(e.updatedAt))?0:Date.parse(e.updatedAt);return(Number.isNaN(Date.parse(t.updatedAt))?0:Date.parse(t.updatedAt))-n})[0]??null}async getRegisteredPort(e){let t={host:e,port:this.getFallbackPort()},n=oa(process.cwd()),r=process.env.NODE_ENV||`development`,i=new y.PortRegistryService(process.env.PORT_REGISTRY_PATH);try{let t=await i.getPort({repositoryPath:n,serviceName:ea,serviceType:ta,environment:r});if(t.success&&t.record&&this.isValidPort(t.record.port))return{host:t.record.host||e,port:t.record.port}}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`${ia} Scoped registry lookup failed for ${ea} in ${r}: ${t}`)}try{let n=await i.listAllocations({serviceName:ea,serviceType:ta,environment:r}),a=this.getLatestRegistryEntry(n);return!a||!this.isValidPort(a.port)?t:{host:a.host||e,port:a.port}}catch(e){let n=e instanceof Error?e.message:String(e);return console.warn(`${ia} Global registry lookup failed for ${ea} in ${r}: ${n}`),t}}};sa=Yi=j([(0,d.injectable)(),P(0,(0,d.inject)(k.BrowserService)),P(1,(0,d.inject)(k.StealthLauncher)),A(`design:paramtypes`,[Object,Object])],sa);var ca;let la=class extends Q{static{ca=this}static TOOL_NAME=`browser_list_console_messages`;constructor(e,t,n,r){super(e,t,n),this.pageMonitor=r}getDefinition(){return{name:ca.TOOL_NAME,description:`Lists all console messages captured during page automation. Requires monitoring to be started first.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},type:{type:`string`,description:`Filter by message type (log, info, warning, error, debug, trace, etc.)`,enum:[`log`,`info`,`warning`,`error`,`debug`,`trace`,`dir`,`dirxml`,`table`,`count`,`assert`]},limit:{type:`number`,description:`Maximum number of messages to return`,minimum:1}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId);return this.executeWithMode(ca.TOOL_NAME,t.id,e,async()=>{let n=this.pageMonitor.getConsoleMessages(t.id,e.type);return e.limit&&(n=n.slice(0,e.limit)),this.successJson({pageId:t.id,messageCount:n.length,messages:n.map(e=>({id:e.id,type:e.type,text:e.text,location:e.location,timestamp:e.timestamp.toISOString()}))})})})}};la=ca=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.PageMonitorService)),A(`design:paramtypes`,[Object,Object,Object,Object])],la);var ua;let da=class extends Q{static{ua=this}static TOOL_NAME=`browser_list_network_requests`;constructor(e,t,n,r){super(e,t,n),this.pageMonitor=r}getDefinition(){return{name:ua.TOOL_NAME,description:`Lists all network requests captured during page automation. Requires monitoring to be started first.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},resourceType:{type:`string`,description:`Filter by resource type (document, xhr, fetch, script, stylesheet, image, etc.)`},urlPattern:{type:`string`,description:`Filter by URL pattern (substring match)`},method:{type:`string`,description:`Filter by HTTP method (GET, POST, etc.)`},limit:{type:`number`,description:`Maximum number of requests to return`,minimum:1}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId);return this.executeWithMode(ua.TOOL_NAME,t.id,e,async()=>{let n=this.pageMonitor.getNetworkRequests(t.id);if(e.resourceType&&(n=n.filter(t=>t.resourceType===e.resourceType)),e.urlPattern){let t=e.urlPattern;n=n.filter(e=>e.url.includes(t))}return e.method&&(n=n.filter(t=>t.method===e.method)),e.limit&&(n=n.slice(0,e.limit)),this.successJson({pageId:t.id,requestCount:n.length,requests:n.map(e=>({id:e.id,url:e.url,method:e.method,resourceType:e.resourceType,status:e.response?.status,statusText:e.response?.statusText,timing:e.response?.timing,timestamp:e.timestamp.toISOString()}))})})})}};da=ua=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.PageMonitorService)),A(`design:paramtypes`,[Object,Object,Object,Object])],da);var fa;let pa=class extends Q{static{fa=this}static TOOL_NAME=`browser_list_pages`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:fa.TOOL_NAME,description:`Lists all pages (tabs) in a browser. Returns page IDs, URLs, titles, and indicates which page is currently active.`,inputSchema:{type:`object`,properties:{browserId:{type:`string`,description:`Browser ID to list pages for`}},required:[`browserId`],additionalProperties:!1}}}async execute(e){return this.toolExecutor.executeForBrowser(fa.TOOL_NAME,e.browserId,e,async()=>{let t=this.browserService.getBrowser(e.browserId);if(!t)return this.error(`Browser "${e.browserId}" not found`);let n=this.pageRegistry.findByBrowser(e.browserId),r=await Promise.all(n.map(async e=>{await this.pageRegistry.updateMetadata(e.id);let n=this.pageRegistry.get(e.id);return{pageId:e.id,url:n?.url??e.url,title:n?.title??e.title,isActive:e.id===t.currentPageId,browserId:e.browserId,profileName:e.profileName,createdAt:e.createdAt.toISOString()}}));return this.successJson({browserId:e.browserId,currentPageId:t.currentPageId,pageCount:r.length,pages:r})})}};pa=fa=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],pa);var ma;let ha=class{static{ma=this}static TOOL_NAME=`browser_list_profiles`;constructor(e){this.profileService=e}getDefinition(){return{name:ma.TOOL_NAME,description:`Lists all available browser profiles with their settings, browser type, viewport, and timestamps.`,inputSchema:{type:`object`,properties:{},required:[],additionalProperties:!1}}}async execute(){try{let e=await this.profileService.list();return{content:[{type:`text`,text:JSON.stringify({profileCount:e.length,profiles:e.map(e=>({name:e.name,browserType:e.browserType,viewport:e.viewport??null,userAgent:e.userAgent??null,locale:e.locale??null,timezone:e.timezone??null,colorScheme:e.colorScheme??null,createdAt:e.createdAt,updatedAt:e.updatedAt}))},null,2)}]}}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}};ha=ma=j([(0,d.injectable)(),P(0,(0,d.inject)(k.ProfileService)),A(`design:paramtypes`,[Object])],ha);var ga;let _a=class{static{ga=this}static TOOL_NAME=`browser_list_snippets`;constructor(e){this.snippetService=e}getDefinition(){return{name:ga.TOOL_NAME,description:`Lists saved code snippets by name, description, and snippetPath for reuse with browser_run_code.`,inputSchema:{type:`object`,properties:{},required:[],additionalProperties:!1}}}async execute(){try{let e=await this.snippetService.listSnippets();return{content:[{type:`text`,text:JSON.stringify({snippetCount:e.length,snippets:e},null,2)}]}}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}};_a=ga=j([(0,d.injectable)(),P(0,(0,d.inject)(k.CodeSnippetService)),A(`design:paramtypes`,[Object])],_a);var va;let ya=class extends Q{static{va=this}static TOOL_NAME=`browser_navigate`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:va.TOOL_NAME,description:`Navigates the browser to a specified URL.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},url:{type:`string`,description:`URL to navigate to`},waitUntil:{type:`string`,enum:[`load`,`domcontentloaded`,`networkidle`,`commit`],description:`Wait until condition`,default:`load`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:N},referer:{type:`string`,description:`Referer header value`}},required:[`pageId`,`url`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(va.TOOL_NAME,e.pageId,e,async()=>{let t=(await this.resolvePage(e.pageId).goto(e.url,{waitUntil:e.waitUntil,timeout:e.timeout,referer:e.referer}))?.status()??`unknown`;return this.success(`Navigated to ${e.url} (status: ${t})`)})}};ya=va=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],ya);var ba;let xa=class extends Q{static{ba=this}static TOOL_NAME=`browser_new_page`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:ba.TOOL_NAME,description:`Creates a new page (tab) in a browser instance. Uses the default browser if browserId is not specified, launching one if needed.`,inputSchema:{type:`object`,properties:{browserId:{type:`string`,description:`Browser ID to create the page in (optional - uses default browser if not specified)`},url:{type:`string`,description:`Optional URL to navigate to after creation`},setAsCurrent:{type:`boolean`,description:`Whether to set as current page for the browser (default: true)`,default:!0}},required:[],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=e.browserId?this.browserService.getBrowser(e.browserId):await this.browserService.getOrCreateDefaultBrowser();if(!t)return this.error(`Browser "${e.browserId}" not found`);let n=t.id,r=e.setAsCurrent!==!1;if(t.mode===`extension`||t.mode===`vm`){let i=this.pageRegistry.registerExtensionPage(n,void 0,e.url,!1),a=await this.toolExecutor.executeForBrowser(ba.TOOL_NAME,n,{...e,pageId:i},async()=>this.error(`Browser "${n}" is not in extension mode`));if(a.isError)return this.pageRegistry.remove(i),a;t.pageIds.add(i),(r||!t.currentPageId)&&(t.currentPageId=i);let o=a.content[0]?.type===`text`?a.content[0].text:void 0,s={};if(typeof o==`string`)try{s=JSON.parse(o)}catch{s={}}let c=this.pageRegistry.get(i);return c&&(c.url=s.url??c.url,c.title=s.title??c.title,c.extensionTabId=s.tabId??c.extensionTabId),this.browserService.recordBrowserActivity(n,i),this.successJson({pageId:i,url:c?.url??e.url??`about:blank`,title:c?.title??``,browserId:n,isActive:t.currentPageId===i})}let{pageId:i,page:a}=await this.browserService.newPage(n);if(e.url)try{await a.goto(e.url),await this.pageRegistry.updateMetadata(i)}catch(e){throw await a.close(),e}r&&this.browserService.setCurrentPage(n,i);let o=this.pageRegistry.get(i);return this.successJson({pageId:i,url:o?.url??a.url(),title:o?.title??``,browserId:n,isActive:r})})}};xa=ba=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],xa);var Sa;let Ca=class extends Q{static{Sa=this}static TOOL_NAME=`browser_pdf`;constructor(e,t,n,r){super(e,t,n),this.extensionTaskQueue=r}getDefinition(){return{name:Sa.TOOL_NAME,description:`Generates a PDF of the page with configurable format options. Saves to temp directory and returns the file path.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},format:{type:`string`,enum:[`Letter`,`Legal`,`Tabloid`,`Ledger`,`A0`,`A1`,`A2`,`A3`,`A4`,`A5`,`A6`],description:`Paper format`,default:`Letter`},printBackground:{type:`boolean`,description:`Print background graphics`,default:!1},landscape:{type:`boolean`,description:`Landscape orientation`,default:!1},scale:{type:`number`,description:`Page scale (0.1 to 2)`,minimum:.1,maximum:2,default:1},marginTop:{type:`string`,description:`Top margin (e.g., "1cm", "0.5in")`},marginBottom:{type:`string`,description:`Bottom margin`},marginLeft:{type:`string`,description:`Left margin`},marginRight:{type:`string`,description:`Right margin`},filename:{type:`string`,description:`Custom filename without extension`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){let t=this.getPage(e.pageId);return t?t.mode===`extension`?this.safeExecute(async()=>{let n=e.filename??`page-${(0,O.randomUUID)()}`,r=(0,m.join)((0,x.tmpdir)(),`${n}.pdf`),i=await this.extensionTaskQueue.queueTask(Sa.TOOL_NAME,{pageId:e.pageId,format:e.format,printBackground:e.printBackground,landscape:e.landscape,scale:e.scale,marginTop:e.marginTop,marginBottom:e.marginBottom,marginLeft:e.marginLeft,marginRight:e.marginRight,filename:n},void 0,t.browserId),a=JSON.parse(i.result?.content?.[0]?.text??`{}`);if(!a.pdfBase64)throw Error(`Extension mode PDF generation returned no data`);return await(0,w.writeFile)(r,Buffer.from(a.pdfBase64,`base64`)),this.success(`PDF saved to: ${r}`)}):this.executeWithMode(Sa.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId),n=e.filename??`page-${(0,O.randomUUID)()}`,r=(0,m.join)((0,x.tmpdir)(),`${n}.pdf`);return await t.pdf({path:r,format:e.format??`Letter`,printBackground:e.printBackground??!1,landscape:e.landscape??!1,scale:e.scale??1,margin:{top:e.marginTop,bottom:e.marginBottom,left:e.marginLeft,right:e.marginRight}}),this.success(`PDF saved to: ${r}`)}):this.error(`Page "${e.pageId}" not found`)}};Ca=Sa=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.ExtensionTaskQueue)),A(`design:paramtypes`,[Object,Object,Object,Object])],Ca);var wa;let Ta=class extends Q{static{wa=this}static TOOL_NAME=`browser_press_key`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:wa.TOOL_NAME,description:`Presses a keyboard key or key combination. Supports modifier keys like Control, Shift, Alt, Meta.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},key:{type:`string`,description:`Key or key combination (e.g., "Enter", "Tab", "Control+a", "Meta+Shift+t", "ArrowDown")`},element:{type:`object`,description:`Optional element to focus before pressing key`,properties:{selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`}}},delay:{type:`number`,description:`Delay between keydown and keyup in ms`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:N}},required:[`pageId`,`key`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(wa.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);return e.element?await(await this.elementLocator.locate(t,e.element)).press(e.key,{delay:e.delay,timeout:e.timeout}):await t.keyboard.press(e.key,{delay:e.delay}),this.success(`Pressed key: "${e.key}"`)})}};Ta=wa=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.ElementLocatorService)),A(`design:paramtypes`,[Object,Object,Object,Object])],Ta);var Ea;let Da=class extends Q{static{Ea=this}static TOOL_NAME=`browser_reload`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ea.TOOL_NAME,description:`Reloads the current page.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},waitUntil:{type:`string`,enum:[`load`,`domcontentloaded`,`networkidle`,`commit`],description:`Wait until condition`,default:`load`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:N}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ea.TOOL_NAME,e.pageId,e,async()=>{let t=(await this.resolvePage(e.pageId).reload({waitUntil:e.waitUntil,timeout:e.timeout}))?.status()??`unknown`;return this.success(`Page reloaded (status: ${t})`)})}};Da=Ea=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],Da);var Oa;let ka=class extends Q{static{Oa=this}static TOOL_NAME=`browser_resize_page`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Oa.TOOL_NAME,description:`Resizes the viewport of a page to specified width and height dimensions.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},width:{type:`number`,description:`Viewport width in pixels`,minimum:1},height:{type:`number`,description:`Viewport height in pixels`,minimum:1},deviceScaleFactor:{type:`number`,description:`Device scale factor (default: 1)`,minimum:1,maximum:3},isMobile:{type:`boolean`,description:`Whether the meta viewport tag is taken into account`},hasTouch:{type:`boolean`,description:`Whether the viewport supports touch events`}},required:[`pageId`,`width`,`height`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Oa.TOOL_NAME,e.pageId,{width:e.width,height:e.height},async()=>{let t=this.resolvePage(e.pageId);await t.setViewportSize({width:e.width,height:e.height});let n=t.viewportSize();return this.successJson({success:!0,viewport:{width:n?.width??e.width,height:n?.height??e.height}})})}};ka=Oa=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],ka);var Aa;let ja=class extends Q{static{Aa=this}static TOOL_NAME=`browser_run_code`;constructor(e,t,n,r,i){super(e,t,n),this.extensionPageProxy=r,this.snippetService=i}getDefinition(){return{name:Aa.TOOL_NAME,description:`Runs a Playwright code snippet. The code should be an async function body that receives { page, context, browser } and can perform any Playwright operation. Return a value to include it in the response.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},code:{type:`string`,description:`JavaScript code to execute. Receives { page, context, browser } as arguments. Example: "await page.goto('https://example.com'); return await page.title();"`},snippetPath:{type:`string`,description:`Relative snippet path inside the configured snippets directory. When provided, executes the saved snippet instead of inline code.`},saveAs:{type:`object`,description:`Optional snippet metadata used to save the inline code into the configured snippets directory.`,properties:{name:{type:`string`,description:`Human-readable snippet name. The filename is generated from a sanitized version of this value.`},description:{type:`string`,description:`Short description shown by browser_list_snippets.`}},required:[`name`,`description`],additionalProperties:!1}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{if(!e.code&&!e.snippetPath)return this.error(`Either "code" or "snippetPath" is required`);if(e.saveAs&&!e.code)return this.error(`"saveAs" requires inline "code"`);let t=this.resolvePageEntry(e.pageId),{page:n,context:r,browser:i}=t,a=t.mode===`extension`?(()=>(this.extensionPageProxy.setTarget(t.id,t.browserId),this.extensionPageProxy))():n,o=t.mode===`extension`?this.extensionPageProxy.context():r,s=t.mode===`extension`?{id:t.browserId,mode:this.browserService.getBrowser(t.browserId)?.mode??`extension`,pageId:t.id}:i,c;e.saveAs&&(c=await this.snippetService.saveSnippet({name:e.saveAs.name,description:e.saveAs.description,code:e.code}));let l=e.snippetPath?await this.snippetService.loadSnippet(e.snippetPath).then(e=>e.run({page:a,context:o,browser:s})):await Function(`page`,`context`,`browser`,`return (async () => { ${e.code} })();`)(a,o,s);return l===void 0?c?this.successJson({savedSnippet:c}):this.success(`Code executed successfully`):this.successJson(c?{result:l,savedSnippet:c}:{result:l})})}};ja=Aa=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.ExtensionPageProxy)),P(4,(0,d.inject)(k.CodeSnippetService)),A(`design:paramtypes`,[Object,Object,Object,Object,Object])],ja);var Ma;const Na=`run-spec-hooks.ts`,Pa=4,Fa={width:1920,height:1080};let Ia=class{static{Ma=this}static TOOL_NAME=`run_spec`;constructor(e,t,n,r,i){this.automationRunner=e,this.specMetadataService=t,this.extensionSpecRunner=n,this.extensionPageProxy=r,this.specBundlerService=i}getDefinition(){return{name:Ma.TOOL_NAME,description:`Runs a Playwright spec file with optional test filtering and dynamic arguments. Supports filtering by test name, pattern, or test.only markers.`,inputSchema:{type:`object`,properties:{specPath:{type:`string`,description:`Absolute path to the Playwright spec file to execute`},automationId:{type:`string`,description:`Optional automation session ID (auto-generated if not provided)`},mode:{type:`string`,enum:[`playwright`,`extension`],description:`Execution mode: playwright (standard) or extension (Chrome extension)`,default:`playwright`},browserId:{type:`string`,description:`Browser ID to use (required for extension mode)`},pageId:{type:`string`,description:`Page ID to use (required for extension mode)`},browserType:{type:`string`,enum:[`chromium`,`firefox`,`webkit`],description:`Browser type to use (only applies to playwright mode)`,default:`chromium`},headless:{type:`boolean`,description:`Run browser in headless mode (only applies to playwright mode)`,default:!0},baseURL:{type:`string`,description:`Base URL for relative navigation (e.g., page.goto("/") will use this as the base)`},keepBrowserOpen:{type:`boolean`,description:`Keep browser open after spec execution completes for further interaction`,default:!1},hooksPath:{type:`string`,description:`Explicit absolute path to run-spec-hooks.ts file. Skips auto-discovery when provided. The source directory is injected as process.env.__HOOKS_SOURCE_DIR__ so hooks can resolve paths relative to their original location.`},env:{type:`object`,description:`Environment variables to set before running the spec. Applied before hooks execution. Useful for passing config like API endpoints without relying on hooks file path resolution.`,additionalProperties:{type:`string`}},testName:{type:`string`,description:`Filter by exact test name`},testPattern:{type:`string`,description:`Filter by regex pattern on full test title (e.g., "login.*success")`},onlyMarked:{type:`boolean`,description:`Run only tests marked with test.only()`,default:!1},describeFilter:{type:`string`,description:`Filter by describe block name pattern`},specArgs:{type:`object`,description:`Arguments to pass to the spec (available as fixtures.specArgs)`,additionalProperties:!0},loadArgsFromEnv:{type:`boolean`,description:`Load specArgs from environment variables using spec's envPrefix export`,default:!1},videoDir:{type:`string`,description:`Absolute directory path to save video recordings. Supported in both playwright and extension modes.`}},required:[`specPath`],additionalProperties:!1}}}async execute(e){if(!(0,m.isAbsolute)(e.specPath))return{content:[{type:`text`,text:`Error: specPath must be an absolute path (e.g., /Users/me/project/tests/my-spec.ts)`}],isError:!0};if(e.hooksPath&&!(0,m.isAbsolute)(e.hooksPath))return{content:[{type:`text`,text:`Error: hooksPath must be an absolute path`}],isError:!0};if(e.videoDir&&!(0,m.isAbsolute)(e.videoDir))return{content:[{type:`text`,text:`Error: videoDir must be an absolute path`}],isError:!0};try{if(e.env)for(let[t,n]of Object.entries(e.env))process.env[t]=n;let t=this.resolveHooksPath(e.specPath,e.hooksPath),n=t?await this.runHooks(t):null;return n?.baseURL&&!e.baseURL&&(e.baseURL=n.baseURL),(e.mode??`playwright`)===`extension`?await this.executeExtensionMode(e):e.testName||e.testPattern||e.onlyMarked||e.describeFilter||e.loadArgsFromEnv?await this.executeEnhanced(e,t):await this.executeBasic(e,t)}catch(e){return{content:[{type:`text`,text:`Error: ${e instanceof Error?e.message:`Unknown error`}`}],isError:!0}}}findHooksFile(e){let t=(0,m.dirname)(e);for(let e=0;e<4;e++){let e=(0,m.join)(t,`run-spec-hooks.ts`);if((0,p.existsSync)(e))return e;let n=(0,m.dirname)(t);if(n===t)break;t=n}return null}async runHooks(e){let t=(0,m.dirname)((0,m.resolve)(e)),n=await this.specBundlerService.bundle(e);try{process.env.__HOOKS_SOURCE_DIR__=t;let e=await import(`${n.outputPath}?t=${Date.now()}`);return typeof e.setup==`function`?await e.setup():void 0}finally{process.env.__HOOKS_SOURCE_DIR__=void 0,await n.cleanup()}}resolveHooksPath(e,t){return t?(0,m.resolve)(t):this.findHooksFile(e)}async executeExtensionMode(e){if(!e.pageId||!e.browserId)return{content:[{type:`text`,text:`Error: pageId and browserId are required for extension mode`}],isError:!0};this.extensionPageProxy.setTarget(e.pageId,e.browserId);let t=e.specArgs??{};if(e.loadArgsFromEnv){let n=await this.specMetadataService.extractSpecMetadata(e.specPath);n.argsSchema&&n.envPrefix&&(t={...this.specMetadataService.parseArgsFromEnv(n.argsSchema,n.envPrefix),...t})}let n={};e.testName&&(n.testName=e.testName),e.testPattern&&(n.testPattern=e.testPattern),e.onlyMarked&&(n.onlyMarked=e.onlyMarked),e.describeFilter&&(n.describeFilter=e.describeFilter);let r=e.automationId??`ext-spec-${Date.now()}`,i=!!e.videoDir;i&&await this.extensionPageProxy.startRecording();let a;try{a=await this.extensionSpecRunner.executeSpec({specPath:e.specPath,sessionId:r,testFilter:Object.keys(n).length>0?n:void 0,specArgs:Object.keys(t).length>0?t:void 0})}finally{if(i&&e.videoDir)try{let t=await this.extensionPageProxy.stopRecording();if(t){(0,p.mkdirSync)(e.videoDir,{recursive:!0});let n=(0,m.join)(e.videoDir,`recording-${r}.webm`);(0,p.writeFileSync)(n,Buffer.from(t,`base64`)),a.videoPath=n}}catch{}}return this.formatExtensionResult(a)}async executeBasic(e,t){let n=await this.automationRunner.runSpec({specPath:e.specPath,automationId:e.automationId,browserId:e.browserId,pageId:e.pageId,keepBrowserOpen:e.keepBrowserOpen??!1,recordVideo:e.videoDir?{dir:e.videoDir,size:Fa}:void 0,browserOptions:{browserType:e.browserType,headless:e.headless,baseURL:e.baseURL},hooksPath:t??void 0});return this.formatResult(n,e.keepBrowserOpen??!1)}async executeEnhanced(e,t){let n=e.specArgs??{};if(e.loadArgsFromEnv){let t=await this.specMetadataService.extractSpecMetadata(e.specPath);t.argsSchema&&t.envPrefix&&(n={...this.specMetadataService.parseArgsFromEnv(t.argsSchema,t.envPrefix),...n})}let r={};e.testName&&(r.testName=e.testName),e.testPattern&&(r.testPattern=e.testPattern),e.onlyMarked&&(r.onlyMarked=e.onlyMarked),e.describeFilter&&(r.describeFilter=e.describeFilter);let i=await this.automationRunner.runSpecEnhanced({specPath:e.specPath,automationId:e.automationId,browserId:e.browserId,pageId:e.pageId,keepBrowserOpen:e.keepBrowserOpen??!1,recordVideo:e.videoDir?{dir:e.videoDir,size:Fa}:void 0,browserOptions:{browserType:e.browserType,headless:e.headless,baseURL:e.baseURL},testFilter:Object.keys(r).length>0?r:void 0,specArgs:Object.keys(n).length>0?n:void 0,hooksPath:t??void 0});return this.formatResult(i,e.keepBrowserOpen??!1)}formatResult(e,t){let n=t?`Spec completed. Browser kept open for further interaction.`:`Spec completed.`;return{content:[{type:`text`,text:JSON.stringify({automationId:e.automationId,status:e.status,pageIds:e.pageIds,browserId:e.browserId,specResult:e.specResult,message:n},null,2)}]}}formatExtensionResult(e){let t=e.success?`Spec completed: ${e.passed}/${e.totalTests} tests passed`:`Spec failed: ${e.failed}/${e.totalTests} tests failed`;return{content:[{type:`text`,text:JSON.stringify({sessionId:e.sessionId,status:e.success?`completed`:`failed`,totalTests:e.totalTests,passed:e.passed,failed:e.failed,duration:e.duration,handoffOccurred:e.handoffOccurred,testResults:e.testResults,videoPath:e.videoPath,message:t},null,2)}],isError:!e.success}}};Ia=Ma=j([(0,d.injectable)(),P(0,(0,d.inject)(k.AutomationRunner)),P(1,(0,d.inject)(k.SpecMetadataService)),P(2,(0,d.inject)(k.ExtensionSpecRunner)),P(3,(0,d.inject)(k.ExtensionPageProxy)),P(4,(0,d.inject)(k.SpecBundlerService)),A(`design:paramtypes`,[Object,Object,Object,Object,Object])],Ia);var La;let Ra=class{static{La=this}static TOOL_NAME=`browser_save_profile_state`;constructor(e,t,n){this.profileService=e,this.browserService=t,this.extensionPageProxy=n}getDefinition(){return{name:La.TOOL_NAME,description:`Saves the current browser state to the named profile for reuse across future launches.`,inputSchema:{type:`object`,properties:{profileName:{type:`string`,description:`Profile to save state into`},browserId:{type:`string`,description:`Browser to read state from`}},required:[`profileName`],additionalProperties:!1}}}async execute(e){try{let t=e.browserId?this.browserService.getBrowser(e.browserId):this.browserService.getBrowserByProfile(e.profileName);if(!t)throw Error(`Browser for profile "${e.profileName}" not found`);if(t.context){let n=await t.context.storageState();await this.profileService.saveStorageState(e.profileName,n)}else{let n=t.currentPageId??[...t.pageIds][0];if(!n)throw Error(`Browser "${t.id}" has no active page`);this.extensionPageProxy.setTarget(n,t.id);let r=await this.extensionPageProxy.getStorageState();await this.profileService.saveStorageState(e.profileName,r)}return{content:[{type:`text`,text:JSON.stringify({profileName:e.profileName,browserId:t.id,saved:!0},null,2)}]}}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}}};Ra=La=j([(0,d.injectable)(),P(0,(0,d.inject)(k.ProfileService)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ExtensionPageProxy)),A(`design:paramtypes`,[Object,Object,Object])],Ra);var za;let Ba=class extends Q{static{za=this}static TOOL_NAME=`browser_screenshot`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:za.TOOL_NAME,description:`Captures a screenshot of the page or specific element. Saves to temp directory and returns the file path.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},fullPage:{type:`boolean`,description:`Capture full page scrollable area`,default:!1},selector:{type:`string`,description:`CSS selector for element to screenshot`},clip:{type:`object`,description:`Clip region to capture by coordinates (cannot be used with selector)`,properties:{x:{type:`number`,description:`X coordinate of top-left corner`,minimum:0},y:{type:`number`,description:`Y coordinate of top-left corner`,minimum:0},width:{type:`number`,description:`Width of clipping region`,minimum:1},height:{type:`number`,description:`Height of clipping region`,minimum:1}},required:[`x`,`y`,`width`,`height`],additionalProperties:!1},type:{type:`string`,enum:[`png`,`jpeg`],description:`Image format`,default:`png`},quality:{type:`number`,description:`Quality for jpeg format (0-100)`,minimum:0,maximum:100},omitBackground:{type:`boolean`,description:`Omit background for transparent PNG`,default:!1},filename:{type:`string`,description:`Custom filename without extension`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(za.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);if(e.clip&&e.selector)throw Error(`Cannot use both clip and selector options together`);let n=e.type??`png`,r=e.filename??`screenshot-${(0,O.randomUUID)()}`,i=(0,m.join)((0,x.tmpdir)(),`${r}.${n}`);if(e.selector){let r=await t.$(e.selector);if(!r)throw Error(`Element not found: ${e.selector}`);await r.screenshot({path:i,type:n,omitBackground:e.omitBackground??!1,quality:n===`jpeg`?e.quality:void 0})}else await t.screenshot({path:i,type:n,fullPage:e.fullPage??!1,omitBackground:e.omitBackground??!1,quality:n===`jpeg`?e.quality:void 0,clip:e.clip});return this.success(`Screenshot saved to: ${i}`)})}};Ba=za=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],Ba);var Va;let Ha=class extends Q{static{Va=this}static TOOL_NAME=`browser_select_page`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Va.TOOL_NAME,description:`Switches the active page for a browser. Updates the current page ID so subsequent operations use this page by default.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to set as current`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.pageRegistry.get(e.pageId);if(!t)return this.error(`Page "${e.pageId}" not found`);let{browserId:n}=t;if(t.mode===`extension`||t.mode===`vm`){let t=await this.executeWithMode(Va.TOOL_NAME,e.pageId,e,async()=>this.error(`Page "${e.pageId}" is not in extension mode`));if(t.isError)return t}this.browserService.setCurrentPage(n,e.pageId),this.browserService.recordBrowserActivity(n,e.pageId),await this.pageRegistry.updateMetadata(e.pageId);let r=this.pageRegistry.get(e.pageId);return this.successJson({browserId:n,pageId:e.pageId,url:r?.url??t.url,title:r?.title??t.title,message:`Page "${e.pageId}" is now the active page for browser "${n}"`})})}};Ha=Va=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],Ha);var Ua;let Wa=class extends Q{static{Ua=this}static TOOL_NAME=`browser_select`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:Ua.TOOL_NAME,description:`Selects option(s) from a dropdown/select element. Can select by value, label, or index.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`},values:{type:`array`,items:{type:`string`},description:`Option value(s) to select`},labels:{type:`array`,items:{type:`string`},description:`Option label(s) to select`},indexes:{type:`array`,items:{type:`number`},description:`Option index(es) to select`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:N}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ua.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId),n=await this.elementLocator.locate(t,e),r=[];e.values?r=e.values.map(e=>({value:e})):e.labels?r=e.labels.map(e=>({label:e})):e.indexes&&(r=e.indexes.map(e=>({index:e})));let i=await n.selectOption(r,{timeout:e.timeout});return this.success(`Selected ${i.length} option(s): ${i.join(`, `)}`)})}};Wa=Ua=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.ElementLocatorService)),A(`design:paramtypes`,[Object,Object,Object,Object])],Wa);var Ga;const Ka=1e4;let qa=class extends Q{static{Ga=this}static TOOL_NAME=`browser_snapshot`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ga.TOOL_NAME,description:`Returns the accessibility tree snapshot of the page. Preferred for LLM processing as it provides structured, semantic information about page content.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},root:{type:`string`,description:`CSS selector for root element to snapshot (defaults to body)`},sizeThreshold:{type:`number`,description:`Size threshold in bytes; snapshots larger than this are saved to file (default: 10000)`,default:1e4}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(Ga.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId),n=e.root??`body`,r=t.locator(n);if(await r.count()===0)throw Error(`Root element not found: ${n}`);let i=await r.ariaSnapshot();if(!i)return this.success(`No accessibility tree available for this page`);let a=e.sizeThreshold??1e4;if(Buffer.byteLength(i,`utf-8`)<=a)return this.success(i);let o=`snapshot-${(0,O.randomUUID)()}.yaml`,s=(0,m.join)((0,x.tmpdir)(),o);return await(0,w.writeFile)(s,i,`utf-8`),this.success(`Snapshot saved to: ${s}`)})}};qa=Ga=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],qa);var Ja;let Ya=class extends Q{static{Ja=this}static TOOL_NAME=`browser_start_trace`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Ja.TOOL_NAME,description:`Starts Playwright performance tracing with configurable options for screenshots, snapshots, and sources. Use browser_stop_trace to stop and save the trace.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},name:{type:`string`,description:`Name for the trace (used in trace filename)`},screenshots:{type:`boolean`,description:`Whether to capture screenshots during tracing (default: true)`},snapshots:{type:`boolean`,description:`Whether to capture snapshots during tracing (default: true)`},sources:{type:`boolean`,description:`Whether to include source files in the trace (default: false)`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId),n=t.context;if(!n)return this.error(`Page "${e.pageId}" is in extension mode and cannot start tracing`);let{name:r,screenshots:i=!0,snapshots:a=!0,sources:o=!1}=e;return await n.tracing.start({name:r,screenshots:i,snapshots:a,sources:o}),this.successJson({success:!0,message:`Tracing started`,pageId:t.id,options:{name:r??null,screenshots:i,snapshots:a,sources:o}})})}};Ya=Ja=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],Ya);var Xa;let Za=class extends Q{static{Xa=this}static TOOL_NAME=`browser_start_recording`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Xa.TOOL_NAME,description:`Starts recording an existing extension/vm browser page and saves the artifact to the provided path or a temporary .webm file.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`The page ID to record.`},path:{type:`string`,description:`Optional absolute output path for the .webm file. If omitted, browse-tool creates a temporary recording path.`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId);if(t.mode!==`extension`&&t.mode!==`vm`)return this.error(`Page "${e.pageId}" is in "${t.mode}" mode and cannot use extension recording`);if(e.path){if(!m.default.isAbsolute(e.path))return this.error(`Recording path must be an absolute path (e.g., /Users/me/project/recording.webm)`);if(m.default.extname(e.path).toLowerCase()!==`.webm`)return this.error(`Recording path must end with .webm`)}let n=await this.browserService.startPageRecording(t.browserId,t.id,e.path);return this.successJson({started:!0,browserId:t.browserId,pageId:t.id,outputPath:n.outputPath})})}};Za=Xa=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],Za);var Qa;let $a=class extends Q{static{Qa=this}static TOOL_NAME=`browser_stop_trace`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:Qa.TOOL_NAME,description:`Stops Playwright performance tracing and saves the trace file to a specified path. The trace can be viewed using Playwright Trace Viewer.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Optional page ID to override browser current page`},path:{type:`string`,description:`Absolute path where the trace file should be saved (e.g., "/Users/me/project/traces/trace.zip"). Must end with .zip extension.`}},required:[`pageId`,`path`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId),n=t.context;if(!n)return this.error(`Page "${e.pageId}" is in extension mode and cannot stop tracing`);let r=e.path;return m.default.isAbsolute(r)?r.endsWith(`.zip`)?(await n.tracing.stop({path:r}),this.successJson({success:!0,message:`Tracing stopped and saved`,pageId:t.id,tracePath:r,viewCommand:`npx playwright show-trace ${r}`})):this.error(`Trace path must end with .zip extension`):this.error(`Trace path must be an absolute path (e.g., /Users/me/project/traces/trace.zip)`)})}};$a=Qa=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],$a);var eo;let to=class extends Q{static{eo=this}static TOOL_NAME=`browser_stop_recording`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:eo.TOOL_NAME,description:`Stops an active extension/vm browser recording and returns the saved .webm path with optional base64 payload.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`The page ID whose recording should be stopped.`},includeBase64:{type:`boolean`,description:`Whether to include the base64-encoded WebM payload in the response.`}},required:[`pageId`],additionalProperties:!1}}}async execute(e){return this.safeExecute(async()=>{let t=this.resolvePageEntry(e.pageId);if(t.mode!==`extension`&&t.mode!==`vm`)return this.error(`Page "${e.pageId}" is in "${t.mode}" mode and cannot use extension recording`);let n=await this.browserService.stopPageRecording(t.browserId,t.id,{includeBase64:e.includeBase64});return this.successJson({stopped:!0,browserId:t.browserId,pageId:t.id,outputPath:n.outputPath,fileSizeBytes:n.fileSizeBytes,...n.videoBase64?{videoBase64:n.videoBase64}:{}})})}};to=eo=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],to);var no;let ro=class extends Q{static{no=this}static TOOL_NAME=`browser_type`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:no.TOOL_NAME,description:`Types text into an element character by character, simulating real keyboard input. Does not clear existing content. Use browser_fill for replacing content.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`},text:{type:`string`,description:`The text to type character by character`},delay:{type:`number`,description:`Delay between key presses in ms`,default:0},timeout:{type:`number`,description:`Timeout in milliseconds`,default:N}},required:[`pageId`,`text`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(no.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);return await(await this.elementLocator.locate(t,{selector:e.selector,xpath:e.xpath,uid:e.uid,frame:e.frame})).pressSequentially(e.text,{delay:e.delay,timeout:e.timeout}),this.success(`Typed: "${e.text}"`)})}};ro=no=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.ElementLocatorService)),A(`design:paramtypes`,[Object,Object,Object,Object])],ro);var io;let ao=class extends Q{static{io=this}static TOOL_NAME=`browser_upload_file`;constructor(e,t,n,r){super(e,t,n),this.elementLocator=r}getDefinition(){return{name:io.TOOL_NAME,description:`Uploads file(s) to a file input element.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},selector:{type:`string`,description:`CSS selector`},xpath:{type:`string`,description:`XPath expression`},text:{type:`string`,description:`Text content to match`},uid:{type:`string`,description:`Accessibility snapshot UID`},frame:{type:`string`,description:`Frame selector`},files:{oneOf:[{type:`string`,description:`Single file path to upload`},{type:`array`,items:{type:`string`},description:`Multiple file paths to upload`}],description:`File path(s) to upload`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:N}},required:[`pageId`,`files`],additionalProperties:!1}}}async execute(e){return this.executeWithMode(io.TOOL_NAME,e.pageId,e,async()=>{let t=this.resolvePage(e.pageId);await(await this.elementLocator.locate(t,e)).setInputFiles(e.files,{timeout:e.timeout});let n=Array.isArray(e.files)?e.files.length:1;return this.success(`Uploaded ${n} file(s) successfully`)})}};ao=io=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),P(3,(0,d.inject)(k.ElementLocatorService)),A(`design:paramtypes`,[Object,Object,Object,Object])],ao);var oo;let so=class extends Q{static{oo=this}static TOOL_NAME=`browser_wait_for`;constructor(e,t,n){super(e,t,n)}getDefinition(){return{name:oo.TOOL_NAME,description:`Waits for a condition to be met: element visibility, text appearance, timeout duration, or page load state.`,inputSchema:{type:`object`,properties:{pageId:{type:`string`,description:`Page ID to operate on`},type:{type:`string`,enum:[`element`,`text`,`timeout`,`loadState`],description:`Type of wait condition`},selector:{type:`string`,description:`CSS selector for element wait`},text:{type:`string`,description:`Text to wait for (supports regex patterns)`},duration:{type:`number`,description:`Duration in milliseconds for timeout wait`},state:{type:`string`,enum:[`load`,`domcontentloaded`,`networkidle`],description:`Load state to wait for`},elementState:{type:`string`,enum:[`attached`,`detached`,`visible`,`hidden`],description:`Element state to wait for`,default:`visible`},timeout:{type:`number`,description:`Timeout in milliseconds`,default:N}},required:[`pageId`],additionalProperties:!1}}}async execute(e){let t=e.type??(e.text?`text`:e.selector||e.elementState?`element`:e.duration===void 0?e.state?`loadState`:void 0:`timeout`);if(!t)return this.error(`Unable to infer wait type. Provide "type" or one of selector, text, duration, or state.`);if(t===`timeout`){let t=e.duration??1e3;return await new Promise(e=>setTimeout(e,t)),this.success(`Waited for ${t}ms`)}return this.executeWithMode(oo.TOOL_NAME,e.pageId,{...e,type:t},async()=>{let n=this.resolvePage(e.pageId);switch(t){case`element`:if(!e.selector)throw Error(`selector is required for element wait`);return await n.locator(e.selector).waitFor({state:e.elementState??`visible`,timeout:e.timeout}),this.success(`Element "${e.selector}" is ${e.elementState??`visible`}`);case`text`:if(!e.text)throw Error(`text is required for text wait`);return await n.getByText(e.text).waitFor({state:`visible`,timeout:e.timeout}),this.success(`Text "${e.text}" appeared on page`);case`loadState`:{let t=e.state??`load`;return await n.waitForLoadState(t,{timeout:e.timeout}),this.success(`Page reached "${t}" state`)}default:throw Error(`Unknown wait type: ${t}`)}})}};so=oo=j([(0,d.injectable)(),P(0,(0,d.inject)(k.PageRegistry)),P(1,(0,d.inject)(k.BrowserService)),P(2,(0,d.inject)(k.ToolExecutor)),A(`design:paramtypes`,[Object,Object,Object])],so);const co=new d.ContainerModule(e=>{e.bind(k.PortRegistryService).toDynamicValue(()=>new y.PortRegistryService(process.env.PORT_REGISTRY_PATH)).inSingletonScope(),e.bind(k.ProcessRegistryService).toDynamicValue(()=>new C.ProcessRegistryService(process.env.PROCESS_REGISTRY_PATH)).inSingletonScope(),e.bind(k.HttpServerHealthCheck).to(H).inSingletonScope(),e.bind(k.HttpServerManager).to(Tr).inSingletonScope(),e.bind(k.McpSessionTracker).to(q).inSingletonScope()}),lo=new d.ContainerModule(e=>{e.bind(k.ProfileService).to(Fr).inSingletonScope(),e.bind(k.PageRegistry).to(Nr).inSingletonScope(),e.bind(k.BrowserService).to(Cn).inSingletonScope(),e.bind(k.BrowserLockManager).to(ft).inSingletonScope(),e.bind(k.ChromeForTestingService).to(Tt).inSingletonScope(),e.bind(k.ElementLocatorService).to(kn).inSingletonScope(),e.bind(k.PageMonitorService).to(Mr).inSingletonScope(),e.bind(k.PauseController).to(Pr).inSingletonScope(),e.bind(k.SpecBundlerService).to(Gr).inSingletonScope(),e.bind(k.SpecDiscoveryService).to(Kr).inSingletonScope(),e.bind(k.SpecMetadataService).to(qr).inSingletonScope(),e.bind(k.SetupRunner).to(Lr).inSingletonScope(),e.bind(k.WebServerManager).to(Qr).inSingletonScope(),e.bind(k.SpecRunner).to(Jr).inSingletonScope(),e.bind(k.AutomationRunner).to(ut).inSingletonScope(),e.bind(k.TelemetryService).to(M).inSingletonScope(),e.bind(k.CodeSnippetService).toDynamicValue(()=>new On(process.env.BROWSE_TOOL_SNIPPETS_DIR)).inSingletonScope(),e.bind(k.ExtensionTaskQueue).to(F).inSingletonScope(),e.bind(k.ExtensionToolDelegator).to(I).inSingletonScope(),e.bind(k.ToolExecutor).to(Zr).inSingletonScope(),e.bind(k.ExtensionSessionRegistry).to(Pn).inSingletonScope(),e.bind(k.ExtensionPageProxy).to(Nn).inSingletonScope(),e.bind(k.ExtensionSpecRunner).to(Fn).inSingletonScope(),e.bind(k.StealthLauncher).to(Yr).inSingletonScope(),e.bind(k.HttpServerHealthCheck).to(H).inSingletonScope(),e.bind(k.HttpBrowserClient).to(Vn).inSingletonScope(),e.bind(k.RemoteToolExecutor).to(Ir).inSingletonScope(),e.bind(k.ProcessRegistryService).toDynamicValue(()=>new C.ProcessRegistryService(process.env.PROCESS_REGISTRY_PATH)).inSingletonScope(),e.bind(k.WebSocketHub).to(gi).inSingletonScope(),e.bind(k.IdleCleanupService).to(jr).inSingletonScope()}),uo=new d.ContainerModule(e=>{e.bind(k.Tool).to(vi).inSingletonScope(),e.bind(k.Tool).to(Ri).inSingletonScope(),e.bind(k.Tool).to(ro).inSingletonScope(),e.bind(k.Tool).to(Wa).inSingletonScope(),e.bind(k.Tool).to(Ji).inSingletonScope(),e.bind(k.Tool).to(Ai).inSingletonScope(),e.bind(k.Tool).to(Ta).inSingletonScope(),e.bind(k.Tool).to(ao).inSingletonScope(),e.bind(k.Tool).to(ya).inSingletonScope(),e.bind(k.Tool).to(Hi).inSingletonScope(),e.bind(k.Tool).to(Wi).inSingletonScope(),e.bind(k.Tool).to(Da).inSingletonScope(),e.bind(k.Tool).to(so).inSingletonScope(),e.bind(k.Tool).to(qa).inSingletonScope(),e.bind(k.Tool).to(Ba).inSingletonScope(),e.bind(k.Tool).to(Ca).inSingletonScope(),e.bind(k.Tool).to(pa).inSingletonScope(),e.bind(k.Tool).to(xa).inSingletonScope(),e.bind(k.Tool).to(Ha).inSingletonScope(),e.bind(k.Tool).to(Si).inSingletonScope(),e.bind(k.Tool).to(Ki).inSingletonScope(),e.bind(k.Tool).to(da).inSingletonScope(),e.bind(k.Tool).to(Bi).inSingletonScope(),e.bind(k.Tool).to(la).inSingletonScope(),e.bind(k.Tool).to(Pi).inSingletonScope(),e.bind(k.Tool).to(Mi).inSingletonScope(),e.bind(k.Tool).to(ka).inSingletonScope(),e.bind(k.Tool).to(Ii).inSingletonScope(),e.bind(k.Tool).to(Za).inSingletonScope(),e.bind(k.Tool).to(to).inSingletonScope(),e.bind(k.Tool).to(Ya).inSingletonScope(),e.bind(k.Tool).to($a).inSingletonScope(),e.bind(k.Tool).to(ha).inSingletonScope(),e.bind(k.Tool).to(_a).inSingletonScope(),e.bind(k.Tool).to(wi).inSingletonScope(),e.bind(k.Tool).to(Ei).inSingletonScope(),e.bind(k.Tool).to(Ra).inSingletonScope(),e.bind(k.Tool).to(Ia).inSingletonScope(),e.bind(k.Tool).to(Oi).inSingletonScope(),e.bind(k.Tool).to(sa).inSingletonScope(),e.bind(k.Tool).to(bi).inSingletonScope(),e.bind(k.Tool).to(ja).inSingletonScope()});function fo(){let e=new d.Container({defaultScope:`Singleton`});return e.load(co),e}function po(){let e=new d.Container({defaultScope:`Singleton`});return e.load(lo,uo),e}const mo=new d.ContainerModule(e=>{e.bind(k.PortRegistryService).toDynamicValue(()=>new y.PortRegistryService(process.env.PORT_REGISTRY_PATH)).inSingletonScope(),e.bind(k.ProfileService).to(Fr).inSingletonScope(),e.bind(k.PageRegistry).to(Nr).inSingletonScope(),e.bind(k.BrowserService).to(Cn).inSingletonScope(),e.bind(k.ElementLocatorService).to(kn).inSingletonScope(),e.bind(k.PageMonitorService).to(Mr).inSingletonScope(),e.bind(k.PauseController).to(Pr).inSingletonScope(),e.bind(k.SpecBundlerService).to(Gr).inSingletonScope(),e.bind(k.SpecDiscoveryService).to(Kr).inSingletonScope(),e.bind(k.SpecMetadataService).to(qr).inSingletonScope(),e.bind(k.SetupRunner).to(Lr).inSingletonScope(),e.bind(k.WebServerManager).to(Qr).inSingletonScope(),e.bind(k.SpecRunner).to(Jr).inSingletonScope(),e.bind(k.AutomationRunner).to(ut).inSingletonScope(),e.bind(k.HttpServerHealthCheck).to(H).inSingletonScope(),e.bind(k.HttpServerManager).to(Tr).inSingletonScope(),e.bind(k.HttpBrowserClient).to(Vn).inSingletonScope(),e.bind(k.RemoteToolExecutor).to(Ir).inSingletonScope(),e.bind(k.ProcessRegistryService).toDynamicValue(()=>new C.ProcessRegistryService(process.env.PROCESS_REGISTRY_PATH)).inSingletonScope(),e.bind(k.ExtensionTaskQueue).to(F).inSingletonScope(),e.bind(k.ExtensionToolDelegator).to(I).inSingletonScope(),e.bind(k.ToolExecutor).to(Zr).inSingletonScope(),e.bind(k.StealthLauncher).to(Yr).inSingletonScope(),e.bind(k.BrowserLockManager).to(ft).inSingletonScope(),e.bind(k.ExtensionSessionRegistry).to(Pn).inSingletonScope(),e.bind(k.ExtensionPageProxy).to(Nn).inSingletonScope(),e.bind(k.ExtensionSpecRunner).to(Fn).inSingletonScope(),e.bind(k.McpSessionTracker).to(q).inSingletonScope(),e.bind(k.ChromeForTestingService).to(Tt).inSingletonScope(),e.bind(k.IdleCleanupService).to(jr).inSingletonScope()}),ho=new d.Container({defaultScope:`Singleton`});ho.load(mo,uo);function go(){let e=new d.Container({defaultScope:`Singleton`});return e.load(mo,uo),e}var _o=class extends Error{code=`TRANSPORT_CONNECTION_ERROR`;recovery=`Check that stdio streams are available and try again.`;constructor(e,t){super(e,t),this.name=`TransportConnectionError`}},vo=class{server;transport=null;constructor(e){this.server=e}async start(){let e=new l.StdioServerTransport;try{await this.server.connect(e),this.transport=e,console.error(`browse-tool MCP server started on stdio`)}catch(t){try{await e.close()}catch{}let n=new _o(`Failed to establish stdio transport connection`,{cause:t});throw console.error(`[${n.code}] ${n.message}. Recovery: ${n.recovery}`),n}}async stop(){this.transport&&=(await this.transport.close(),null)}},yo=class extends Error{code=`TRANSPORT_CONNECTION_ERROR`;recovery=`Check that the HTTP host and port are available and try again.`;constructor(e,t){super(e,t),this.name=`TransportConnectionError`}};async function bo(e){let t=[];for await(let n of e)t.push(typeof n==`string`?Buffer.from(n):n);if(t.length===0)return;let n=Buffer.concat(t).toString(`utf8`).trim();if(n)return JSON.parse(n)}function $(e,t,n){e.headersSent||(e.writeHead(t,{"Content-Type":`application/json`}),e.end(JSON.stringify(n)))}var xo=class{sessions=new Map;get(e){return this.sessions.get(e)}set(e,t){this.sessions.set(e,t)}has(e){return this.sessions.has(e)}async delete(e){let t=this.sessions.get(e);t&&(this.sessions.delete(e),t.server.close(),await t.onClose?.())}async clear(){let e=[...this.sessions.keys()];for(let t of e)await this.delete(t)}},So=class{sessionFactory;config;sessionManager=new xo;httpServer=null;constructor(e,t){this.sessionFactory=e,this.config={host:t.host,port:t.port,path:t.path??`/mcp`}}async createSession(e,t){if(!(0,u.isInitializeRequest)(t))throw Error(`No valid session ID provided`);let n=this.sessionFactory({headers:e.headers}),r=new ae.StreamableHTTPServerTransport({sessionIdGenerator:()=>(0,O.randomUUID)(),enableJsonResponse:!0,onsessioninitialized:e=>{this.sessionManager.set(e,{server:n.server,transport:r,onClose:n.onClose})},onsessionclosed:async e=>{await this.sessionManager.delete(e)}});return r.onclose=()=>{r.sessionId&&this.sessionManager.delete(r.sessionId)},await n.server.connect(r),r}async handleMcpRequest(e,t){let n=e.headers[`mcp-session-id`],r=Array.isArray(n)?n[0]:n,i;if(e.method===`POST`)try{i=await bo(e)}catch(e){$(t,400,{jsonrpc:`2.0`,error:{code:-32700,message:e instanceof Error?e.message:`Invalid JSON body`},id:null});return}let a;if(r?a=this.sessionManager.get(r)?.transport:e.method===`POST`&&(a=await this.createSession(e,i)),!a){$(t,r?404:400,{jsonrpc:`2.0`,error:{code:-32e3,message:r?`Session not found`:`Bad Request: No valid session ID provided`},id:null});return}await a.handleRequest(e,t,i)}async start(){if(this.httpServer)throw new yo(`HTTP transport server is already running`);await new Promise((e,t)=>{let n=(0,ie.createServer)((e,t)=>{(async()=>{try{let n=new URL(e.url??`/`,`http://${e.headers.host??this.config.host}`).pathname;if(n===`/health`&&e.method===`GET`){$(t,200,{status:`ok`,transport:`streamable-http`});return}if(n!==this.config.path){$(t,404,{error:`Not found`});return}await this.handleMcpRequest(e,t)}catch(e){$(t,500,{jsonrpc:`2.0`,error:{code:-32603,message:(e instanceof Error?e:Error(String(e))).message},id:null})}})()});n.once(`error`,e=>{t(new yo(`Failed to establish streamable HTTP transport connection`,{cause:e}))}),n.listen(this.config.port,this.config.host,()=>{this.httpServer=n,process.stderr.write(`browse-tool MCP server started on http://${this.config.host}:${this.config.port}${this.config.path}\n`),process.stderr.write(`Health check: http://${this.config.host}:${this.config.port}/health\n`),e()})})}async stop(){if(await this.sessionManager.clear(),!this.httpServer)return;let e=this.httpServer;this.httpServer=null,await new Promise((t,n)=>{e.close(e=>{if(e){n(e);return}t()})})}};Object.defineProperty(exports,`C`,{enumerable:!0,get:function(){return k}}),Object.defineProperty(exports,`S`,{enumerable:!0,get:function(){return rt}}),Object.defineProperty(exports,`_`,{enumerable:!0,get:function(){return gt}}),Object.defineProperty(exports,`a`,{enumerable:!0,get:function(){return po}}),Object.defineProperty(exports,`b`,{enumerable:!0,get:function(){return F}}),Object.defineProperty(exports,`c`,{enumerable:!0,get:function(){return kr}}),Object.defineProperty(exports,`d`,{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,`f`,{enumerable:!0,get:function(){return Bn}}),Object.defineProperty(exports,`g`,{enumerable:!0,get:function(){return mt}}),Object.defineProperty(exports,`h`,{enumerable:!0,get:function(){return Bt}}),Object.defineProperty(exports,`i`,{enumerable:!0,get:function(){return go}}),Object.defineProperty(exports,`l`,{enumerable:!0,get:function(){return Ln}}),Object.defineProperty(exports,`m`,{enumerable:!0,get:function(){return Wt}}),Object.defineProperty(exports,`n`,{enumerable:!0,get:function(){return vo}}),Object.defineProperty(exports,`o`,{enumerable:!0,get:function(){return fo}}),Object.defineProperty(exports,`p`,{enumerable:!0,get:function(){return Nn}}),Object.defineProperty(exports,`r`,{enumerable:!0,get:function(){return ho}}),Object.defineProperty(exports,`s`,{enumerable:!0,get:function(){return q}}),Object.defineProperty(exports,`t`,{enumerable:!0,get:function(){return So}}),Object.defineProperty(exports,`u`,{enumerable:!0,get:function(){return V}}),Object.defineProperty(exports,`v`,{enumerable:!0,get:function(){return pt}}),Object.defineProperty(exports,`w`,{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,`x`,{enumerable:!0,get:function(){return M}}),Object.defineProperty(exports,`y`,{enumerable:!0,get:function(){return I}});
15
+ //# sourceMappingURL=streamable-http-O6YYT3Yr.cjs.map