@agimon-ai/browse-tool 0.2.0

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.
Files changed (38) hide show
  1. package/LICENSE +52 -0
  2. package/README.md +375 -0
  3. package/dist/cli.cjs +674 -0
  4. package/dist/cli.d.cts +1 -0
  5. package/dist/cli.d.mts +2 -0
  6. package/dist/cli.mjs +434 -0
  7. package/dist/cli.mjs.map +1 -0
  8. package/dist/extension/background.js +7248 -0
  9. package/dist/extension/background.js.map +1 -0
  10. package/dist/extension/content.js +446 -0
  11. package/dist/extension/content.js.map +1 -0
  12. package/dist/extension/manifest.json +36 -0
  13. package/dist/extension/offscreen.html +9 -0
  14. package/dist/extension/offscreen.js +137 -0
  15. package/dist/extension/offscreen.js.map +1 -0
  16. package/dist/extension/popup.html +195 -0
  17. package/dist/extension/popup.js +132 -0
  18. package/dist/extension/popup.js.map +1 -0
  19. package/dist/index.cjs +1 -0
  20. package/dist/index.d.cts +309 -0
  21. package/dist/index.d.cts.map +1 -0
  22. package/dist/index.d.mts +310 -0
  23. package/dist/index.d.mts.map +1 -0
  24. package/dist/index.mjs +2 -0
  25. package/dist/index.mjs.map +1 -0
  26. package/dist/playwright-test-BwI7HgW7.mjs +253 -0
  27. package/dist/playwright-test-BwI7HgW7.mjs.map +1 -0
  28. package/dist/playwright-test-CnsuVfC9.cjs +252 -0
  29. package/dist/stdio-BP3yiSxK.mjs +9 -0
  30. package/dist/stdio-BP3yiSxK.mjs.map +1 -0
  31. package/dist/stdio-ynNFGBY4.cjs +9 -0
  32. package/dist/stubs/playwright-test.cjs +1 -0
  33. package/dist/stubs/playwright-test.d.cts +111 -0
  34. package/dist/stubs/playwright-test.d.cts.map +1 -0
  35. package/dist/stubs/playwright-test.d.mts +111 -0
  36. package/dist/stubs/playwright-test.d.mts.map +1 -0
  37. package/dist/stubs/playwright-test.mjs +1 -0
  38. package/package.json +77 -0
package/dist/cli.cjs ADDED
@@ -0,0 +1,674 @@
1
+ #!/usr/bin/env node
2
+ const e=require(`./stdio-ynNFGBY4.cjs`);require(`./playwright-test-CnsuVfC9.cjs`),require(`reflect-metadata/lite`);let t=require(`commander`),n=require(`@hono/node-server`),r=require(`@modelcontextprotocol/sdk/server/index.js`),i=require(`@modelcontextprotocol/sdk/server/stdio.js`),a=require(`@modelcontextprotocol/sdk/types.js`),o=require(`hono`),s=require(`hono/cors`),c=require(`inversify`),l=require(`node:fs`),u=require(`node:os`),d=require(`node:path`);d=e.m(d);let f=require(`zod`),p=require(`@agimon-ai/foundation-port-registry`),m=require(`@hono/node-ws`),h=require(`hono/html`),g=require(`hono/jsx/jsx-runtime`);var _=`0.2.0`;function v(t){let n=new o.Hono;return n.get(`/tasks`,n=>{try{let r=t.get(e.p.ExtensionTaskQueue).getNextTask();return r?n.json({task:{id:r.id,tool:r.tool,arguments:r.arguments}}):n.json({})}catch(e){return n.json({error:e instanceof Error?e.message:String(e)},500)}}),n.post(`/result`,async n=>{try{let r=await n.req.json();if(!r.taskId)return n.json({success:!1,error:`Missing taskId in request body`},400);let i=t.get(e.p.ExtensionTaskQueue),a={taskId:r.taskId,success:r.success,result:r.result,error:r.error};return i.submitResult(a)?n.json({success:!0}):n.json({success:!1,error:`Task ${r.taskId} not found or already completed`},404)}catch(e){return n.json({success:!1,error:e instanceof Error?e.message:String(e)},500)}}),n.get(`/status`,n=>{try{let r=t.get(e.p.ExtensionTaskQueue),i=r.getConnectionStatus(),a={connected:i.connected,lastPollAt:i.lastPollAt?.toISOString(),lastResultAt:i.lastResultAt?.toISOString(),pendingTasks:i.pendingTasks,queueSize:r.queueSize};return n.json(a)}catch(e){return n.json({connected:!1,error:e instanceof Error?e.message:String(e)},500)}}),n.post(`/register`,async n=>{try{let r=await n.req.json();if(!r.browserId)return n.json({success:!1,error:`Missing browserId in request body`},400);let i=t.get(e.p.ExtensionSessionRegistry).register(r);return n.json({success:!0,session:{id:i.id,browserId:i.browserId,controlMode:i.controlMode,createdAt:i.createdAt.toISOString()}})}catch(e){return n.json({success:!1,error:e instanceof Error?e.message:String(e)},500)}}),n.post(`/heartbeat`,async n=>{try{let r=await n.req.json();if(!r.sessionId)return n.json({success:!1,error:`Missing sessionId in request body`},400);let i=t.get(e.p.ExtensionSessionRegistry).heartbeat(r);return i?n.json({success:!0,session:{id:i.id,controlMode:i.controlMode,handoffRequested:i.handoffRequested,lastHeartbeatAt:i.lastHeartbeatAt.toISOString()}}):n.json({success:!1,error:`Session ${r.sessionId} not found`},404)}catch(e){return n.json({success:!1,error:e instanceof Error?e.message:String(e)},500)}}),n.post(`/handoff`,async n=>{try{let r=await n.req.json();if(!r.sessionId)return n.json({success:!1,error:`Missing sessionId in request body`},400);let i=t.get(e.p.ExtensionSessionRegistry).requestHandoff(r);return i?n.json({success:!0,message:`Handoff requested. AI will take control when ready.`,session:{id:i.id,controlMode:i.controlMode,handoffRequested:i.handoffRequested}}):n.json({success:!1,error:`Session ${r.sessionId} not found`},404)}catch(e){return n.json({success:!1,error:e instanceof Error?e.message:String(e)},500)}}),n.post(`/handoff/acknowledge`,async n=>{try{let r=await n.req.json();if(!r.sessionId)return n.json({success:!1,error:`Missing sessionId in request body`},400);let i=t.get(e.p.ExtensionSessionRegistry).acknowledgeHandoff(r.sessionId);return i?n.json({success:!0,message:`Handoff acknowledged. AI now has control.`,session:{id:i.id,controlMode:i.controlMode,handoffRequested:i.handoffRequested}}):n.json({success:!1,error:`Session ${r.sessionId} not found or no handoff pending`},404)}catch(e){return n.json({success:!1,error:e instanceof Error?e.message:String(e)},500)}}),n.get(`/sessions`,n=>{try{let r=t.get(e.p.ExtensionSessionRegistry).listSessions();return n.json({sessions:r.map(e=>({id:e.id,browserId:e.browserId,tabId:e.tabId,currentUrl:e.currentUrl,controlMode:e.controlMode,activeSpecPath:e.activeSpecPath,handoffRequested:e.handoffRequested,createdAt:e.createdAt.toISOString(),lastHeartbeatAt:e.lastHeartbeatAt.toISOString()}))})}catch(e){return n.json({error:e instanceof Error?e.message:String(e)},500)}}),n}function y(){return new c.ContainerModule(t=>{t.bind(e.p.ExtensionTaskQueue).to(e.f).inSingletonScope(),t.bind(e.p.ExtensionToolDelegator).to(e.d).inSingletonScope()})}function b(e){let t=new r.Server({name:`browse-tool-chrome`,version:`0.1.0`},{capabilities:{tools:{}}}),n=e.getSupportedTools().map(e=>({name:e,description:`Browser automation tool (Chrome extension mode): ${e}`,inputSchema:{type:`object`,properties:{},additionalProperties:!0}}));return t.setRequestHandler(a.ListToolsRequestSchema,async()=>({tools:n})),t.setRequestHandler(a.CallToolRequestSchema,async t=>{let{name:n,arguments:r}=t.params;return await e.executeTool(n,r||{})}),t}const x=new t.Command(`chrome-serve`).description(`[DEPRECATED] Start MCP server with Chrome extension HTTP polling for bot-detection-free browser automation`).option(`-p, --port <port>`,`HTTP server port for extension polling`,`3200`).option(`-v, --verbose`,`Enable verbose output`,!1).option(`--wait-for-extension`,`Wait for extension to connect before accepting MCP requests`,!1).action(async t=>{console.error(``),console.error(`╔════════════════════════════════════════════════════════════════╗`),console.error(`║ DEPRECATED: chrome-serve is deprecated. ║`),console.error(`║ Use mcp-serve instead - extension routes are now ║`),console.error(`║ automatically available in the HTTP server at /extension/*. ║`),console.error(`╚════════════════════════════════════════════════════════════════╝`),console.error(``);try{let r=typeof t.port==`string`?Number.parseInt(t.port,10):t.port;t.verbose&&(console.error(`Chrome Extension MCP Server starting...`),console.error(` HTTP Port: ${r}`),console.error(` Wait for extension: ${t.waitForExtension}`));let a=new c.Container({defaultScope:`Singleton`});a.load(y());let l=a.get(e.p.ExtensionTaskQueue),u=a.get(e.p.ExtensionToolDelegator),d=new o.Hono;d.use(`*`,(0,s.cors)({origin:e=>e??null,credentials:!0,allowMethods:[`GET`,`POST`,`OPTIONS`],allowHeaders:[`Content-Type`,`Accept`]}));let f=v(a);d.route(`/extension`,f),d.get(`/health`,e=>{let t=l.getConnectionStatus();return e.json({status:`healthy`,service:`browse-tool-chrome`,extension:t})});let p=(0,n.serve)({fetch:d.fetch,port:r});p.on(`error`,e=>{e.code===`EADDRINUSE`?(console.error(`Error [PORT_IN_USE]: Port ${r} is already in use.`),console.error(`Recovery: Try a different port with --port <port>`)):console.error(`Error [SERVER_ERROR]: HTTP server error: ${e.message}`),process.exit(1)}),console.error(`HTTP server started on port ${r}`),console.error(`Waiting for Chrome extension to connect...`),console.error(`Extension should poll: http://localhost:${r}/extension/tasks`),t.waitForExtension&&(console.error(`Waiting for extension connection before starting MCP...`),await new Promise(e=>{let t=setInterval(()=>{l.getConnectionStatus().connected&&(clearInterval(t),console.error(`Extension connected!`),e())},500)}));let m=b(u),h=new i.StdioServerTransport;await m.connect(h),console.error(`Chrome extension MCP server started on stdio`);let g=async e=>{console.error(`\nReceived ${e}, shutting down gracefully...`);try{l.clearAllTasks(`Server shutting down`),await h.close(),p.close(),process.exit(0)}catch(e){console.error(`Error during shutdown:`,e),process.exit(1)}};process.on(`SIGINT`,()=>g(`SIGINT`)),process.on(`SIGTERM`,()=>g(`SIGTERM`))}catch(e){let t=e instanceof Error?e.message:String(e);console.error(`Error [SERVER_ERROR]: Failed to start Chrome extension MCP server: ${t}`),console.error(`Recovery: Check that the port is available and try again.`),process.exit(1)}}),S=`BROWSE_TOOL_CONFIG`,C=`.browse-tool`,w=`config.json`,T=[`json`,`text`,`quiet`],E={commands:{},tools:{}},ee=f.z.record(f.z.string(),f.z.unknown()),te=f.z.object({mcpServe:f.z.object({type:f.z.string().optional(),browser:f.z.string().optional(),headless:f.z.boolean().optional(),profile:f.z.string().optional(),mode:f.z.string().optional(),host:f.z.string().optional(),tags:f.z.string().optional(),exclude:f.z.string().optional(),registryPath:f.z.string().optional(),registryDir:f.z.string().optional(),pidsDir:f.z.string().optional(),profilesDir:f.z.string().optional()}).partial().optional(),httpServe:f.z.object({port:f.z.coerce.number().int().positive().optional(),headless:f.z.boolean().optional(),idleTimeout:f.z.coerce.number().positive().optional(),host:f.z.string().optional(),registryDir:f.z.string().optional(),registryPath:f.z.string().optional(),pidsDir:f.z.string().optional(),profilesDir:f.z.string().optional()}).partial().optional(),exec:f.z.object({format:f.z.enum(T).optional(),color:f.z.boolean().optional(),port:f.z.coerce.number().int().positive().optional()}).partial().optional(),tools:f.z.object({format:f.z.enum(T).optional(),color:f.z.boolean().optional(),port:f.z.coerce.number().int().positive().optional()}).partial().optional(),status:f.z.record(f.z.string(),f.z.unknown()).optional(),stop:f.z.record(f.z.string(),f.z.unknown()).optional()}),ne=f.z.object({commands:te.default({}),tools:f.z.record(f.z.string(),ee).default({})});let D={config:E};function re(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n===`--config`)return e[t+1];if(n.startsWith(`--config=`))return n.slice(9)}}function ie(e){let t=d.default.resolve(e);if(!(0,l.existsSync)(t))throw Error(`Config path not found: ${t}`);return(0,l.statSync)(t).isDirectory()?d.default.join(t,w):t}function ae(e,t){let n=t.env??process.env,r=t.cwd??process.cwd(),i=t.homeDir??(0,u.homedir)(),a=re(e);if(a)return ie(a);if(n[S])return ie(n[S]);let o=d.default.join(r,C,w);if((0,l.existsSync)(o))return o;let s=d.default.join(i,C,w);if((0,l.existsSync)(s))return s}function oe(e){let t=(0,l.readFileSync)(e,`utf8`),n=JSON.parse(t);return ne.parse(n)}function se(e,t={}){let n=ae(e,t);return n?{configPath:n,config:oe(n)}:{config:E}}function ce(e,t={}){return D=se(e,t),D}function O(e){return(D.config.commands??{})[e]??{}}function le(e){return D.config.tools?.[e]??{}}function k(e,t,n,r,i){let a=e.getOptionValueSourceWithGlobals(t);return a!==void 0&&a!==`default`&&a!==`implied`?n:i===void 0?r===void 0?n:r:i}const ue=6e4;var de=class{port;timeout;serverPort=null;constructor(e={}){this.port=e.port??3200,this.timeout=e.timeout??6e4}async ensureServer(){if(this.serverPort!==null)return this.serverPort;let t=await e.a().get(e.p.HttpServerManager).ensureRunning(this.port);if(!t.running||!t.port)throw Error(t.error??`Failed to start HTTP server. Try running "browse-tool http-serve" manually.`);return this.serverPort=t.port,t.port}async getBaseUrl(){return`http://localhost:${await this.ensureServer()}`}async listTools(){let e=await this.getBaseUrl(),t=new AbortController,n=setTimeout(()=>t.abort(),this.timeout);try{let n=await fetch(`${e}/tools`,{method:`GET`,headers:{Accept:`application/json`},signal:t.signal});if(!n.ok)throw Error(`HTTP ${n.status}: ${n.statusText}`);return(await n.json()).tools}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`Request timeout after ${this.timeout}ms`):this.wrapConnectionError(e)}finally{clearTimeout(n)}}async listBrowsers(){let e=await this.getBaseUrl(),t=new AbortController,n=setTimeout(()=>t.abort(),this.timeout);try{let n=await fetch(`${e}/browsers`,{method:`GET`,headers:{Accept:`application/json`},signal:t.signal});if(!n.ok)throw Error(`HTTP ${n.status}: ${n.statusText}`);let r=await n.json();if(r.error)throw Error(r.error);return r.browsers}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`Request timeout after ${this.timeout}ms`):this.wrapConnectionError(e)}finally{clearTimeout(n)}}async execute(e,t){let n=await this.getBaseUrl(),r=e===`run_spec`?void 0:this.timeout,i=new AbortController,a=r===void 0?void 0:setTimeout(()=>i.abort(),r);try{let a=await fetch(`${n}/execute`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({tool:e,arguments:t}),signal:r===void 0?void 0:i.signal});if(!a.ok){let e=await a.text();throw Error(`HTTP ${a.status}: ${e||a.statusText}`)}let o=await a.json();return o.success?o.result??{content:[{type:`text`,text:`No result returned`}]}:{content:[{type:`text`,text:o.error??`Unknown error`}],isError:!0}}catch(e){throw e instanceof Error&&e.name===`AbortError`?Error(`Request timeout after ${this.timeout}ms`):this.wrapConnectionError(e)}finally{a&&clearTimeout(a)}}wrapConnectionError(e){return e instanceof Error?e.message.includes(`ECONNREFUSED`)||e.message.includes(`fetch failed`)?Error(`Cannot connect to browse-tool HTTP server.\n\nTry one of the following:\n 1. Start the server: browse-tool http-serve\n 2. Check if another process is using port ${this.port}\n 3. Run with a different port: browse-tool --port 3201 <command>\n\nOriginal error: ${e.message}`):e:Error(String(e))}};function A(e){return new de(e)}const j={reset:`\x1B[0m`,red:`\x1B[31m`,green:`\x1B[32m`,yellow:`\x1B[33m`,blue:`\x1B[34m`,magenta:`\x1B[35m`,cyan:`\x1B[36m`,gray:`\x1B[90m`,bold:`\x1B[1m`};function M(e,t,n){return n?`${j[t]}${e}${j.reset}`:e}function fe(e,t){let{format:n,color:r}=t;return n===`quiet`?``:n===`json`?pe(e):me(e,r)}function pe(e){return JSON.stringify(e,null,2)}function me(e,t){let n=[];e.isError&&n.push(M(`Error:`,`red`,t));for(let r of e.content)r.type===`text`?n.push(he(r,t)):r.type===`image`?n.push(ve(r,t)):n.push(M(`[Unknown content type: ${r.type}]`,`yellow`,t));return n.join(`
3
+ `)}function he(e,t){let n=e.text;try{return ge(JSON.parse(n),t)}catch{return n}}function ge(e,t){if(typeof e!=`object`||!e)return String(e);let n=[];for(let[r,i]of Object.entries(e)){let e=M(r,`cyan`,t),a=_e(i,t);n.push(`${e}: ${a}`)}return n.join(`
4
+ `)}function _e(e,t){return e===null?M(`null`,`gray`,t):e===void 0?M(`undefined`,`gray`,t):typeof e==`boolean`?M(String(e),e?`green`:`red`,t):typeof e==`number`?M(String(e),`yellow`,t):typeof e==`string`?e.startsWith(`http://`)||e.startsWith(`https://`)?M(e,`blue`,t):e:Array.isArray(e)?e.length===0?M(`[]`,`gray`,t):JSON.stringify(e,null,2):typeof e==`object`?JSON.stringify(e,null,2):String(e)}function ve(e,t){let{mimeType:n,data:r}=e;return M(`[Image: ${n}, ~${Math.round(r.length*3/4/1024)}KB base64 data]`,`magenta`,t)}function N(e,t){return M(`Error: ${e instanceof Error?e.message:e}`,`red`,t)}const ye=new t.Command(`exec`).description(`Execute a tool directly with JSON arguments`).argument(`<tool>`,`Tool name to execute (e.g., browser_launch)`).argument(`[args]`,`JSON arguments for the tool`,`{}`).option(`-f, --format <format>`,`Output format: json, text, quiet`,`json`).option(`--no-color`,`Disable colored output`).option(`-p, --port <port>`,`HTTP server port`,String(e.s)).action(async function(e,t,n){let r=O(`exec`),i=k(this,`format`,n.format,r.format),a=k(this,`color`,n.color,r.color),o=k(this,`port`,n.port,r.port===void 0?void 0:String(r.port),process.env.PLAYWRIGHT_PORT),s={format:i,color:a};try{let n;try{n=JSON.parse(t)}catch{console.error(N(`Invalid JSON arguments: ${t}`,s.color)),process.exit(1)}let r=await A({port:Number.parseInt(o,10)}).execute(e,n),i=fe(r,s);i&&console.log(i),r.isError&&process.exit(1)}catch(e){console.error(N(e instanceof Error?e:String(e),s.color)),process.exit(1)}});function be(t){let n=new o.Hono;return n.get(`/browsers`,async n=>{try{let r=t.get(e.p.BrowserService),i=t.get(e.p.PageRegistry),a=r.listBrowsers(),o=i.list(),s=a.map(e=>{let t=o.filter(t=>t.browserId===e.id);return{id:e.id,profileName:e.profileName,currentPageId:e.currentPageId,createdAt:e.createdAt.toISOString(),pages:t.map(e=>({id:e.id,url:e.url,title:e.title,createdAt:e.createdAt.toISOString()}))}}),c={totalBrowsers:a.length,totalPages:o.length};return n.json({browsers:s,stats:c})}catch(e){return console.error(`Failed to list browsers:`,e),n.json({error:`Failed to list browsers`,message:e instanceof Error?e.message:String(e)},500)}}),n.delete(`/browsers`,async n=>{try{return await t.get(e.p.BrowserService).closeAll(),n.json({success:!0,message:`All browsers closed`})}catch(e){return console.error(`Failed to close all browsers:`,e),n.json({error:`Failed to close all browsers`,message:e instanceof Error?e.message:String(e)},500)}}),n.delete(`/browsers/:id`,async n=>{try{let r=n.req.param(`id`),i=t.get(e.p.BrowserService);return i.getBrowser(r)?(await i.closeBrowser(r),n.json({success:!0,message:`Browser "${r}" closed`})):n.json({error:`Browser "${r}" not found`},404)}catch(e){return console.error(`Failed to close browser:`,e),n.json({error:`Failed to close browser`,message:e instanceof Error?e.message:String(e)},500)}}),n.delete(`/pages/:id`,async n=>{try{let r=n.req.param(`id`),i=t.get(e.p.PageRegistry).get(r);return i?i.page?(await i.page.close(),n.json({success:!0,message:`Page "${r}" closed`})):n.json({error:`Page "${r}" is in extension mode and cannot be closed via API`},400):n.json({error:`Page "${r}" not found`},404)}catch(e){return console.error(`Failed to close page:`,e),n.json({error:`Failed to close page`,message:e instanceof Error?e.message:String(e)},500)}}),n}function P(e){return e.toLocaleString(`en-US`,{year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hour12:!1})}function xe(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),r=Math.floor(n/60);return r>0?`${r}h ${n%60}m`:n>0?`${n}m ${t%60}s`:`${t}s`}function F(e){return xe(new Date().getTime()-e.getTime())}const Se=`dashboard-container`,Ce=`dashboard-header`,we=`btn`,Te=`btn-danger`,I=`table-container`,Ee=`browser-table`,De=`stats-container`,L=`stat-card`,R=`browser-row`,z=`page-row`,B=`status-active`,V=`url-cell`,H=`timestamp-cell`,U=`actions-cell`,W=`kill-btn`,Oe=`refresh-btn`,G=`empty-state`,ke=`
5
+ * {
6
+ margin: 0;
7
+ padding: 0;
8
+ box-sizing: border-box;
9
+ }
10
+
11
+ body {
12
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
13
+ font-size: 14px;
14
+ line-height: 1.5;
15
+ color: #333;
16
+ background-color: #f5f5f5;
17
+ }
18
+
19
+ h1, h2, h3 {
20
+ margin-bottom: 1rem;
21
+ }
22
+
23
+ .dashboard-container {
24
+ max-width: 1400px;
25
+ margin: 0 auto;
26
+ padding: 2rem;
27
+ }
28
+
29
+ .dashboard-header {
30
+ background-color: #fff;
31
+ padding: 1.5rem;
32
+ margin-bottom: 1.5rem;
33
+ border-radius: 8px;
34
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
35
+ display: flex;
36
+ justify-content: space-between;
37
+ align-items: center;
38
+ }
39
+
40
+ .dashboard-header h1 {
41
+ margin-bottom: 0;
42
+ }
43
+
44
+ .controls-section {
45
+ background-color: #fff;
46
+ padding: 1rem;
47
+ margin-bottom: 1rem;
48
+ border-radius: 8px;
49
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
50
+ display: flex;
51
+ gap: 1rem;
52
+ align-items: center;
53
+ flex-wrap: wrap;
54
+ }
55
+
56
+ .btn {
57
+ padding: 0.5rem 1rem;
58
+ border: none;
59
+ border-radius: 4px;
60
+ font-size: 14px;
61
+ cursor: pointer;
62
+ background-color: #2196f3;
63
+ color: white;
64
+ transition: background-color 0.2s;
65
+ }
66
+
67
+ .btn:hover {
68
+ background-color: #1976d2;
69
+ }
70
+
71
+ .btn:disabled {
72
+ background-color: #ccc;
73
+ cursor: not-allowed;
74
+ }
75
+
76
+ .btn-danger {
77
+ background-color: #f44336;
78
+ }
79
+
80
+ .btn-danger:hover {
81
+ background-color: #d32f2f;
82
+ }
83
+
84
+ .table-container {
85
+ background-color: #fff;
86
+ border-radius: 8px;
87
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
88
+ overflow: hidden;
89
+ }
90
+
91
+ .browser-table {
92
+ width: 100%;
93
+ border-collapse: collapse;
94
+ table-layout: fixed;
95
+ }
96
+
97
+ .browser-table th {
98
+ background-color: #f8f9fa;
99
+ padding: 0.75rem;
100
+ text-align: left;
101
+ font-weight: 600;
102
+ border-bottom: 2px solid #dee2e6;
103
+ position: sticky;
104
+ top: 0;
105
+ }
106
+
107
+ .browser-table th:nth-child(1) {
108
+ width: 12%;
109
+ }
110
+
111
+ .browser-table th:nth-child(2) {
112
+ width: 10%;
113
+ }
114
+
115
+ .browser-table th:nth-child(3) {
116
+ width: 38%;
117
+ }
118
+
119
+ .browser-table th:nth-child(4) {
120
+ width: 15%;
121
+ }
122
+
123
+ .browser-table th:nth-child(5) {
124
+ width: 15%;
125
+ }
126
+
127
+ .browser-table th:nth-child(6) {
128
+ width: 10%;
129
+ }
130
+
131
+ .browser-table td {
132
+ padding: 0.75rem;
133
+ border-bottom: 1px solid #dee2e6;
134
+ vertical-align: middle;
135
+ }
136
+
137
+ .browser-row {
138
+ background-color: #e3f2fd;
139
+ font-weight: 500;
140
+ }
141
+
142
+ .browser-row:hover {
143
+ background-color: #bbdefb;
144
+ }
145
+
146
+ .page-row {
147
+ background-color: #fff;
148
+ }
149
+
150
+ .page-row:hover {
151
+ background-color: #f8f9fa;
152
+ }
153
+
154
+ .page-row td:first-child {
155
+ padding-left: 2rem;
156
+ }
157
+
158
+ .status-active {
159
+ color: #4caf50;
160
+ font-weight: 600;
161
+ }
162
+
163
+ .status-inactive {
164
+ color: #9e9e9e;
165
+ }
166
+
167
+ .url-cell {
168
+ max-width: 400px;
169
+ overflow: hidden;
170
+ text-overflow: ellipsis;
171
+ white-space: nowrap;
172
+ font-family: 'Courier New', monospace;
173
+ font-size: 13px;
174
+ }
175
+
176
+ .timestamp-cell {
177
+ white-space: nowrap;
178
+ font-size: 12px;
179
+ color: #666;
180
+ }
181
+
182
+ .actions-cell {
183
+ text-align: center;
184
+ }
185
+
186
+ .kill-btn {
187
+ padding: 0.25rem 0.5rem;
188
+ font-size: 12px;
189
+ background-color: #ff5722;
190
+ border: none;
191
+ border-radius: 4px;
192
+ color: white;
193
+ cursor: pointer;
194
+ transition: background-color 0.2s;
195
+ }
196
+
197
+ .kill-btn:hover {
198
+ background-color: #e64a19;
199
+ }
200
+
201
+ .refresh-btn {
202
+ background-color: #4caf50;
203
+ }
204
+
205
+ .refresh-btn:hover {
206
+ background-color: #388e3c;
207
+ }
208
+
209
+ .stats-container {
210
+ display: flex;
211
+ gap: 1.5rem;
212
+ margin-bottom: 1rem;
213
+ }
214
+
215
+ .stat-card {
216
+ background-color: #fff;
217
+ padding: 1rem;
218
+ border-radius: 8px;
219
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
220
+ flex: 1;
221
+ }
222
+
223
+ .stat-card h3 {
224
+ font-size: 0.875rem;
225
+ color: #666;
226
+ margin-bottom: 0.5rem;
227
+ }
228
+
229
+ .stat-card .value {
230
+ font-size: 1.5rem;
231
+ font-weight: 700;
232
+ color: #333;
233
+ }
234
+
235
+ .empty-state {
236
+ padding: 3rem;
237
+ text-align: center;
238
+ color: #666;
239
+ }
240
+
241
+ .empty-state h3 {
242
+ margin-bottom: 0.5rem;
243
+ color: #999;
244
+ }
245
+ `;function Ae({browsers:e}){return e.length===0?(0,g.jsx)(`div`,{class:I,children:(0,g.jsxs)(`div`,{class:G,children:[(0,g.jsx)(`h3`,{children:`No Active Browsers`}),(0,g.jsx)(`p`,{children:`Launch a browser using MCP tools to see it here.`})]})}):(0,g.jsx)(`div`,{class:I,children:(0,g.jsxs)(`table`,{class:`browser-table`,children:[(0,g.jsx)(`thead`,{children:(0,g.jsxs)(`tr`,{children:[(0,g.jsx)(`th`,{children:`ID`}),(0,g.jsx)(`th`,{children:`Status`}),(0,g.jsx)(`th`,{children:`URL / Title`}),(0,g.jsx)(`th`,{children:`Created`}),(0,g.jsx)(`th`,{children:`Age`}),(0,g.jsx)(`th`,{children:`Actions`})]})}),(0,g.jsx)(`tbody`,{id:`browser-table-body`,children:e.map(e=>(0,g.jsxs)(g.Fragment,{children:[(0,g.jsxs)(`tr`,{class:R,children:[(0,g.jsx)(`td`,{children:e.id}),(0,g.jsx)(`td`,{children:(0,g.jsxs)(`span`,{class:B,children:[e.pages.length,` page`,e.pages.length===1?``:`s`]})}),(0,g.jsx)(`td`,{children:e.profileName||`Default Profile`}),(0,g.jsx)(`td`,{class:H,children:P(e.createdAt)}),(0,g.jsx)(`td`,{class:H,children:F(e.createdAt)}),(0,g.jsx)(`td`,{class:U,children:(0,g.jsx)(`button`,{class:W,onclick:`dashboard.killBrowser('${e.id}')`,children:`Kill`})})]}),e.pages.map(t=>(0,g.jsxs)(`tr`,{class:z,children:[(0,g.jsxs)(`td`,{children:[t.id,e.currentPageId===t.id&&` (active)`]}),(0,g.jsx)(`td`,{children:(0,g.jsx)(`span`,{class:B,children:`Open`})}),(0,g.jsx)(`td`,{class:V,title:t.url,children:t.title||t.url||`about:blank`}),(0,g.jsx)(`td`,{class:H,children:P(t.createdAt)}),(0,g.jsx)(`td`,{class:H,children:F(t.createdAt)}),(0,g.jsx)(`td`,{class:U,children:(0,g.jsx)(`button`,{class:W,onclick:`dashboard.killPage('${t.id}')`,children:`Close`})})]}))]}))})]})})}function je({stats:e}){return(0,g.jsxs)(`div`,{class:`stats-container`,children:[(0,g.jsxs)(`div`,{class:L,children:[(0,g.jsx)(`h3`,{children:`Active Browsers`}),(0,g.jsx)(`div`,{class:`value`,children:e.totalBrowsers})]}),(0,g.jsxs)(`div`,{class:L,children:[(0,g.jsx)(`h3`,{children:`Active Pages`}),(0,g.jsx)(`div`,{class:`value`,children:e.totalPages})]})]})}function Me({browsers:e,stats:t}){return(0,g.jsxs)(`div`,{class:`dashboard-container`,children:[(0,g.jsxs)(`div`,{class:`dashboard-header`,children:[(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`h1`,{children:`Playwright MCP Dashboard`}),(0,g.jsx)(`p`,{children:`Browser automation management (auto-refresh every 3 seconds)`})]}),(0,g.jsxs)(`div`,{children:[(0,g.jsx)(`button`,{id:`refresh-btn`,class:`btn refresh-btn`,onclick:`dashboard.manualRefresh()`,children:`Refresh Now`}),(0,g.jsx)(`button`,{id:`kill-all-btn`,class:`btn btn-danger`,onclick:`dashboard.killAllBrowsers()`,children:`Kill All Browsers`})]})]}),(0,g.jsx)(je,{stats:t}),(0,g.jsx)(Ae,{browsers:e}),(0,g.jsx)(`script`,{children:(0,h.raw)(`
246
+ class DashboardManager {
247
+ constructor() {
248
+ this.autoRefreshInterval = null;
249
+ this.isRefreshing = false;
250
+ this.startAutoRefresh();
251
+ }
252
+
253
+ startAutoRefresh() {
254
+ this.autoRefreshInterval = setInterval(() => {
255
+ this.fetchBrowsers();
256
+ }, 3000);
257
+ }
258
+
259
+ stopAutoRefresh() {
260
+ if (this.autoRefreshInterval) {
261
+ clearInterval(this.autoRefreshInterval);
262
+ this.autoRefreshInterval = null;
263
+ }
264
+ }
265
+
266
+ async fetchBrowsers() {
267
+ if (this.isRefreshing) return;
268
+ this.isRefreshing = true;
269
+
270
+ try {
271
+ const response = await fetch('/api/browsers');
272
+ const data = await response.json();
273
+ this.updateStats(data.stats);
274
+ this.updateBrowserTable(data.browsers);
275
+ } catch (error) {
276
+ console.error('Failed to fetch browsers:', error);
277
+ } finally {
278
+ this.isRefreshing = false;
279
+ }
280
+ }
281
+
282
+ updateStats(stats) {
283
+ const cards = document.querySelectorAll('.${L} .value');
284
+ if (cards.length >= 2) {
285
+ cards[0].textContent = stats.totalBrowsers;
286
+ cards[1].textContent = stats.totalPages;
287
+ }
288
+ }
289
+
290
+ updateBrowserTable(browsers) {
291
+ const tbody = document.getElementById('browser-table-body');
292
+ if (!tbody) return;
293
+
294
+ if (browsers.length === 0) {
295
+ const container = tbody.closest('.${I}');
296
+ if (container) {
297
+ container.innerHTML = \`
298
+ <div class="${G}">
299
+ <h3>No Active Browsers</h3>
300
+ <p>Launch a browser using MCP tools to see it here.</p>
301
+ </div>
302
+ \`;
303
+ }
304
+ return;
305
+ }
306
+
307
+ // Rebuild table content
308
+ tbody.innerHTML = '';
309
+ browsers.forEach(browser => {
310
+ // Browser row
311
+ const browserRow = document.createElement('tr');
312
+ browserRow.className = '${R}';
313
+ browserRow.innerHTML = \`
314
+ <td>\${browser.id}</td>
315
+ <td><span class="${B}">\${browser.pages.length} page\${browser.pages.length !== 1 ? 's' : ''}</span></td>
316
+ <td>\${browser.profileName || 'Default Profile'}</td>
317
+ <td class="${H}">\${this.formatTimestamp(browser.createdAt)}</td>
318
+ <td class="${H}">\${this.formatAge(browser.createdAt)}</td>
319
+ <td class="${U}"><button class="${W}" onclick="dashboard.killBrowser('\${browser.id}')">Kill</button></td>
320
+ \`;
321
+ tbody.appendChild(browserRow);
322
+
323
+ // Page rows
324
+ browser.pages.forEach(page => {
325
+ const pageRow = document.createElement('tr');
326
+ pageRow.className = '${z}';
327
+ const isActive = browser.currentPageId === page.id;
328
+ pageRow.innerHTML = \`
329
+ <td>\${page.id}\${isActive ? ' (active)' : ''}</td>
330
+ <td><span class="${B}">Open</span></td>
331
+ <td class="${V}" title="\${this.escapeHtml(page.url)}">\${this.escapeHtml(page.title || page.url || 'about:blank')}</td>
332
+ <td class="${H}">\${this.formatTimestamp(page.createdAt)}</td>
333
+ <td class="${H}">\${this.formatAge(page.createdAt)}</td>
334
+ <td class="${U}"><button class="${W}" onclick="dashboard.killPage('\${page.id}')">Close</button></td>
335
+ \`;
336
+ tbody.appendChild(pageRow);
337
+ });
338
+ });
339
+ }
340
+
341
+ formatTimestamp(timestamp) {
342
+ const date = new Date(timestamp);
343
+ return date.toLocaleString('en-US', {
344
+ year: 'numeric',
345
+ month: '2-digit',
346
+ day: '2-digit',
347
+ hour: '2-digit',
348
+ minute: '2-digit',
349
+ second: '2-digit',
350
+ hour12: false,
351
+ });
352
+ }
353
+
354
+ formatAge(timestamp) {
355
+ const now = new Date();
356
+ const date = new Date(timestamp);
357
+ const ms = now.getTime() - date.getTime();
358
+ const seconds = Math.floor(ms / 1000);
359
+ const minutes = Math.floor(seconds / 60);
360
+ const hours = Math.floor(minutes / 60);
361
+
362
+ if (hours > 0) return \`\${hours}h \${minutes % 60}m\`;
363
+ if (minutes > 0) return \`\${minutes}m \${seconds % 60}s\`;
364
+ return \`\${seconds}s\`;
365
+ }
366
+
367
+ escapeHtml(str) {
368
+ if (typeof str !== 'string') return str;
369
+ return str
370
+ .replace(/&/g, '&amp;')
371
+ .replace(/</g, '&lt;')
372
+ .replace(/>/g, '&gt;')
373
+ .replace(/"/g, '&quot;')
374
+ .replace(/'/g, '&#039;');
375
+ }
376
+
377
+ manualRefresh() {
378
+ this.fetchBrowsers();
379
+ }
380
+
381
+ async killBrowser(browserId) {
382
+ try {
383
+ const response = await fetch(\`/api/browsers/\${browserId}\`, { method: 'DELETE' });
384
+ if (response.ok) {
385
+ this.fetchBrowsers();
386
+ } else {
387
+ console.error('Failed to kill browser:', await response.text());
388
+ }
389
+ } catch (error) {
390
+ console.error('Failed to kill browser:', error);
391
+ }
392
+ }
393
+
394
+ async killPage(pageId) {
395
+ try {
396
+ const response = await fetch(\`/api/pages/\${pageId}\`, { method: 'DELETE' });
397
+ if (response.ok) {
398
+ this.fetchBrowsers();
399
+ } else {
400
+ console.error('Failed to close page:', await response.text());
401
+ }
402
+ } catch (error) {
403
+ console.error('Failed to close page:', error);
404
+ }
405
+ }
406
+
407
+ async killAllBrowsers() {
408
+ if (!confirm('Are you sure you want to close all browsers?')) return;
409
+
410
+ try {
411
+ const response = await fetch('/api/browsers', { method: 'DELETE' });
412
+ if (response.ok) {
413
+ this.fetchBrowsers();
414
+ } else {
415
+ console.error('Failed to kill all browsers:', await response.text());
416
+ }
417
+ } catch (error) {
418
+ console.error('Failed to kill all browsers:', error);
419
+ }
420
+ }
421
+ }
422
+
423
+ // Initialize dashboard
424
+ const dashboard = new DashboardManager();
425
+
426
+ // Cleanup on page unload
427
+ window.addEventListener('beforeunload', () => {
428
+ dashboard.stopAutoRefresh();
429
+ });
430
+ `)})]})}function K({title:e,children:t}){return(0,g.jsxs)(`html`,{lang:`en`,children:[(0,g.jsxs)(`head`,{children:[(0,g.jsx)(`meta`,{charset:`UTF-8`}),(0,g.jsx)(`meta`,{name:`viewport`,content:`width=device-width, initial-scale=1.0`}),(0,g.jsx)(`title`,{children:e}),(0,g.jsx)(`style`,{children:(0,h.raw)(`
431
+ * {
432
+ margin: 0;
433
+ padding: 0;
434
+ box-sizing: border-box;
435
+ }
436
+
437
+ body {
438
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
439
+ font-size: 14px;
440
+ line-height: 1.5;
441
+ color: #333;
442
+ background-color: #f5f5f5;
443
+ }
444
+
445
+ h1, h2, h3 {
446
+ margin-bottom: 1rem;
447
+ }
448
+
449
+ .dashboard-container {
450
+ max-width: 1400px;
451
+ margin: 0 auto;
452
+ padding: 2rem;
453
+ }
454
+
455
+ .dashboard-header {
456
+ background-color: #fff;
457
+ padding: 1.5rem;
458
+ margin-bottom: 1.5rem;
459
+ border-radius: 8px;
460
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
461
+ display: flex;
462
+ justify-content: space-between;
463
+ align-items: center;
464
+ }
465
+
466
+ .dashboard-header h1 {
467
+ margin-bottom: 0;
468
+ }
469
+
470
+ .controls-section {
471
+ background-color: #fff;
472
+ padding: 1rem;
473
+ margin-bottom: 1rem;
474
+ border-radius: 8px;
475
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
476
+ display: flex;
477
+ gap: 1rem;
478
+ align-items: center;
479
+ flex-wrap: wrap;
480
+ }
481
+
482
+ .btn {
483
+ padding: 0.5rem 1rem;
484
+ border: none;
485
+ border-radius: 4px;
486
+ font-size: 14px;
487
+ cursor: pointer;
488
+ background-color: #2196f3;
489
+ color: white;
490
+ transition: background-color 0.2s;
491
+ }
492
+
493
+ .btn:hover {
494
+ background-color: #1976d2;
495
+ }
496
+
497
+ .btn:disabled {
498
+ background-color: #ccc;
499
+ cursor: not-allowed;
500
+ }
501
+
502
+ .btn-danger {
503
+ background-color: #f44336;
504
+ }
505
+
506
+ .btn-danger:hover {
507
+ background-color: #d32f2f;
508
+ }
509
+
510
+ .table-container {
511
+ background-color: #fff;
512
+ border-radius: 8px;
513
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
514
+ overflow: hidden;
515
+ }
516
+
517
+ .browser-table {
518
+ width: 100%;
519
+ border-collapse: collapse;
520
+ table-layout: fixed;
521
+ }
522
+
523
+ .browser-table th {
524
+ background-color: #f8f9fa;
525
+ padding: 0.75rem;
526
+ text-align: left;
527
+ font-weight: 600;
528
+ border-bottom: 2px solid #dee2e6;
529
+ position: sticky;
530
+ top: 0;
531
+ }
532
+
533
+ .browser-table th:nth-child(1) {
534
+ width: 12%;
535
+ }
536
+
537
+ .browser-table th:nth-child(2) {
538
+ width: 10%;
539
+ }
540
+
541
+ .browser-table th:nth-child(3) {
542
+ width: 38%;
543
+ }
544
+
545
+ .browser-table th:nth-child(4) {
546
+ width: 15%;
547
+ }
548
+
549
+ .browser-table th:nth-child(5) {
550
+ width: 15%;
551
+ }
552
+
553
+ .browser-table th:nth-child(6) {
554
+ width: 10%;
555
+ }
556
+
557
+ .browser-table td {
558
+ padding: 0.75rem;
559
+ border-bottom: 1px solid #dee2e6;
560
+ vertical-align: middle;
561
+ }
562
+
563
+ .browser-row {
564
+ background-color: #e3f2fd;
565
+ font-weight: 500;
566
+ }
567
+
568
+ .browser-row:hover {
569
+ background-color: #bbdefb;
570
+ }
571
+
572
+ .page-row {
573
+ background-color: #fff;
574
+ }
575
+
576
+ .page-row:hover {
577
+ background-color: #f8f9fa;
578
+ }
579
+
580
+ .page-row td:first-child {
581
+ padding-left: 2rem;
582
+ }
583
+
584
+ .status-active {
585
+ color: #4caf50;
586
+ font-weight: 600;
587
+ }
588
+
589
+ .status-inactive {
590
+ color: #9e9e9e;
591
+ }
592
+
593
+ .url-cell {
594
+ max-width: 400px;
595
+ overflow: hidden;
596
+ text-overflow: ellipsis;
597
+ white-space: nowrap;
598
+ font-family: 'Courier New', monospace;
599
+ font-size: 13px;
600
+ }
601
+
602
+ .timestamp-cell {
603
+ white-space: nowrap;
604
+ font-size: 12px;
605
+ color: #666;
606
+ }
607
+
608
+ .actions-cell {
609
+ text-align: center;
610
+ }
611
+
612
+ .kill-btn {
613
+ padding: 0.25rem 0.5rem;
614
+ font-size: 12px;
615
+ background-color: #ff5722;
616
+ border: none;
617
+ border-radius: 4px;
618
+ color: white;
619
+ cursor: pointer;
620
+ transition: background-color 0.2s;
621
+ }
622
+
623
+ .kill-btn:hover {
624
+ background-color: #e64a19;
625
+ }
626
+
627
+ .refresh-btn {
628
+ background-color: #4caf50;
629
+ }
630
+
631
+ .refresh-btn:hover {
632
+ background-color: #388e3c;
633
+ }
634
+
635
+ .stats-container {
636
+ display: flex;
637
+ gap: 1.5rem;
638
+ margin-bottom: 1rem;
639
+ }
640
+
641
+ .stat-card {
642
+ background-color: #fff;
643
+ padding: 1rem;
644
+ border-radius: 8px;
645
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
646
+ flex: 1;
647
+ }
648
+
649
+ .stat-card h3 {
650
+ font-size: 0.875rem;
651
+ color: #666;
652
+ margin-bottom: 0.5rem;
653
+ }
654
+
655
+ .stat-card .value {
656
+ font-size: 1.5rem;
657
+ font-weight: 700;
658
+ color: #333;
659
+ }
660
+
661
+ .empty-state {
662
+ padding: 3rem;
663
+ text-align: center;
664
+ color: #666;
665
+ }
666
+
667
+ .empty-state h3 {
668
+ margin-bottom: 0.5rem;
669
+ color: #999;
670
+ }
671
+ `)})]}),(0,g.jsx)(`body`,{children:t})]})}function Ne(t){let n=new o.Hono;return n.get(`/`,async n=>{try{let r=t.get(e.p.BrowserService),i=t.get(e.p.PageRegistry),a=r.listBrowsers(),o=i.list(),s=a.map(e=>{let t=o.filter(t=>t.browserId===e.id);return{id:e.id,profileName:e.profileName,currentPageId:e.currentPageId,createdAt:e.createdAt,pages:t.map(e=>({id:e.id,url:e.url,title:e.title,createdAt:e.createdAt}))}}),c={totalBrowsers:a.length,totalPages:o.length};return n.html((0,g.jsx)(K,{title:`Playwright MCP Dashboard`,children:(0,g.jsx)(Me,{browsers:s,stats:c})}))}catch(e){return console.error(`Failed to render dashboard:`,e),n.html((0,g.jsx)(K,{title:`Playwright MCP Dashboard - Error`,children:(0,g.jsxs)(`div`,{style:`padding: 2rem; text-align: center;`,children:[(0,g.jsx)(`h1`,{children:`Failed to load dashboard`}),(0,g.jsx)(`p`,{children:e instanceof Error?e.message:String(e)}),(0,g.jsx)(`a`,{href:`/`,style:`color: #2196f3; text-decoration: underline;`,children:`Retry`})]})}),500)}}),n}function Pe(t){let n=new o.Hono;n.use(`*`,(0,s.cors)({origin:e=>e??null,credentials:!0,allowMethods:[`GET`,`POST`,`DELETE`,`OPTIONS`],allowHeaders:[`Content-Type`,`Accept`,`Authorization`]})),n.get(`/health`,n=>{try{let r=t.get(e.p.BrowserService).listBrowsers(),i={status:`healthy`,service:`browse-tool-http`,serviceName:`browse-tool-http`,timestamp:new Date().toISOString(),browsers:{count:r.length,instances:r.map(e=>({id:e.id,pageCount:e.pageIds.size,createdAt:e.createdAt.toISOString()}))}};return n.json(i)}catch(e){return n.json({status:`unhealthy`,service:`browse-tool-http`,serviceName:`browse-tool-http`,error:e instanceof Error?e.message:String(e)},503)}}),n.post(`/execute`,async n=>{try{let r=await n.req.json();if(!r.tool)return n.json({success:!1,error:`Missing "tool" field in request body`},400);let i=t.getAll(e.p.Tool).find(e=>e.getDefinition().name===r.tool);if(!i)return n.json({success:!1,error:`Tool "${r.tool}" not found`},404);let a=await i.execute(r.arguments||{}),o=(r.arguments||{}).pageId;if(o){let n=t.get(e.p.PageRegistry),r=t.get(e.p.BrowserService);n.touchPage(o);let i=n.get(o);i&&r.touchBrowser(i.browserId)}let s=a.isError?a.content[0]?.text:void 0;return n.json({success:!a.isError,result:a,error:s})}catch(e){return n.json({success:!1,error:e instanceof Error?e.message:String(e)},500)}}),n.get(`/browsers`,n=>{try{let r=t.get(e.p.BrowserService).listBrowsers();return n.json({browsers:r.map(e=>({id:e.id,profileName:e.profileName,pageIds:Array.from(e.pageIds),currentPageId:e.currentPageId,createdAt:e.createdAt.toISOString()}))})}catch(e){return n.json({error:e instanceof Error?e.message:String(e)},500)}}),n.get(`/tools`,n=>{try{let r=t.getAll(e.p.Tool);return n.json({tools:r.map(e=>e.getDefinition())})}catch(e){return n.json({error:e instanceof Error?e.message:String(e)},500)}});let r=v(t);n.route(`/extension`,r);let i=be(t);n.route(`/api`,i);let a=Ne(t);return n.route(`/`,a),n}function Fe(t,n,r){t.get(`/ws/extension/:browserId`,r(t=>{let r=t.req.param(`browserId`),i=null;return{onOpen(t,a){try{i=n.get(e.p.WebSocketHub).addConnection(a,r)}catch{a.close(1011,`Internal server error`)}},onMessage(t){if(i)try{let r=n.get(e.p.WebSocketHub),a=typeof t.data==`string`?t.data:t.data.toString();r.handleMessage(i,a)}catch{}},onClose(){if(i)try{n.get(e.p.WebSocketHub).removeConnection(i)}catch{}},onError(){if(i)try{n.get(e.p.WebSocketHub).removeConnection(i)}catch{}}}})),t.get(`/ws/stats`,t=>{try{let r=n.get(e.p.WebSocketHub).getStats();return t.json({totalConnections:r.totalConnections,browserCount:r.browserCount,connections:r.connections.map(e=>({id:e.id,browserId:e.browserId,connectedAt:e.connectedAt.toISOString()}))})}catch(e){return t.json({error:e instanceof Error?e.message:String(e)},500)}})}const Ie=[`pnpm-workspace.yaml`,`nx.json`,`.git`];function Le(e=process.cwd()){let t=d.default.resolve(e);for(;;){for(let e of Ie)if((0,l.existsSync)(d.default.join(t,e)))return t;let e=d.default.dirname(t);if(e===t)return process.cwd();t=e}}const Re=new t.Command(`http-serve`).description(`Start HTTP server for browser automation`).option(`-p, --port <port>`,`Port to listen on`,String(e.s)).option(`--host <host>`,`Host to bind`,e.l()).option(`--headless`,`Run browsers in headless mode by default`,!0).option(`--idle-timeout <minutes>`,`Idle timeout in minutes before closing browsers`,`30`).option(`--registry-dir <path>`,`Custom registry path or directory for service discovery`).option(`--registry-path <path>`,`Custom registry path or directory for service discovery`).option(`--pids-dir <path>`,`Custom PIDs directory for process tracking (deprecated)`).option(`--profiles-dir <path>`,`Custom profiles directory for browser profiles`).action(async function(t){let r=O(`httpServe`),i={port:k(this,`port`,t.port,r.port===void 0?void 0:String(r.port),process.env.PLAYWRIGHT_PORT),headless:k(this,`headless`,t.headless,r.headless),idleTimeout:k(this,`idleTimeout`,t.idleTimeout,r.idleTimeout===void 0?void 0:String(r.idleTimeout)),host:k(this,`host`,t.host,r.host,process.env.PLAYWRIGHT_HOST),registryDir:k(this,`registryDir`,t.registryDir,r.registryDir,process.env.PLAYWRIGHT_REGISTRY_DIR),registryPath:k(this,`registryPath`,t.registryPath,r.registryPath,process.env.PLAYWRIGHT_REGISTRY_PATH??process.env.PORT_REGISTRY_PATH),pidsDir:k(this,`pidsDir`,t.pidsDir,r.pidsDir,process.env.PLAYWRIGHT_PIDS_DIR),profilesDir:k(this,`profilesDir`,t.profilesDir,r.profilesDir,process.env.PLAYWRIGHT_PROFILES_DIR)};try{let t=Number.parseInt(i.port,10),r=`browse-tool-http`,a=process.env.NODE_ENV||`development`,o=Le(process.cwd()),s=i.registryPath||i.registryDir||process.env.PLAYWRIGHT_REGISTRY_PATH;s&&(process.env.PLAYWRIGHT_REGISTRY_DIR=s,process.env.PORT_REGISTRY_PATH=s),process.env.PLAYWRIGHT_HOST=i.host,process.env.PLAYWRIGHT_PORT=i.port,i.pidsDir&&(process.env.PLAYWRIGHT_PIDS_DIR=i.pidsDir),i.profilesDir&&(process.env.PLAYWRIGHT_PROFILES_DIR=i.profilesDir),console.log(`Starting HTTP server for browser automation...`),console.log(` Port: ${t}`),console.log(` Host: ${i.host}`),console.log(` Headless: ${i.headless}`),console.log(` Idle Timeout: ${i.idleTimeout} minutes`);let c=e.i(),l=Pe(c),{injectWebSocket:u,upgradeWebSocket:d}=(0,m.createNodeWebSocket)({app:l});Fe(l,c,d);let f=c.get(e.p.WebSocketHub),h=c.get(e.p.ExtensionTaskQueue),g=c.get(e.p.BrowserService),_=c.get(e.p.PageRegistry),v=c.get(e.p.IdleCleanupService);v.start(),f.setEventHandlers({onSessionRegister:(e,t)=>{if(t.type===`session:register`){let n=g.listBrowsers().find(e=>(e.mode===`extension`||e.mode===`vm`)&&!f.hasConnection(e.id)),r,i;if(n)r=n.id,i=n.currentPageId||Array.from(n.pageIds)[0]||``,f.reassignConnection(e.id,r),console.log(`[WebSocket] Extension connected to existing browser: ${r}, pageId: ${i}`);else{r=e.browserId,g.registerExtensionBrowserWithId(r),i=_.registerExtensionPage(r);let t=g.getBrowser(r);t&&(t.pageIds.add(i),t.currentPageId=i),console.log(`[WebSocket] Extension connected with new browser: ${r}, pageId: ${i}`)}let a=`session-${Date.now()}`;f.sendSessionAck(e,t.id??``,a,`extension`),f.broadcastPageCreated(r,i)}},onTaskResult:(e,t)=>{t.type===`task:result`&&h.submitResult({taskId:t.payload.taskId,success:t.payload.success,result:t.payload.result,error:t.payload.error})},onDisconnect:e=>{console.log(`[WebSocket] Extension disconnected: ${e.browserId}`)}});let y=new p.PortRegistryService(process.env.PORT_REGISTRY_PATH);s?console.log(` Registry path: ${s}`):console.log(` Registry path: default (~/.port-registry/ports.json)`);let b=await y.reservePort({repositoryPath:o,serviceName:r,serviceType:`tool`,environment:a,preferredPort:t,pid:process.pid,host:i.host,force:!0,portRange:{min:t,max:t},metadata:{healthCheckUrl:`${e.c(i.host,t)}/health`,headless:i.headless,idleTimeout:i.idleTimeout}});if(!b.success||!b.record)throw Error(b.error||`Failed to reserve port ${t} in global registry`);let x=t,S;try{S=(0,n.serve)({fetch:l.fetch,port:x,hostname:i.host})}catch(e){throw await y.releasePort({repositoryPath:o,serviceName:r,serviceType:`tool`,environment:a,pid:process.pid}),e}u(S);let C=e.c(i.host,x);console.log(`HTTP server listening on ${C}`),console.log(` Health check: ${C}/health`),console.log(` Execute tool: POST ${C}/execute`),console.log(`
672
+ Press Ctrl+C to stop the server`);let w=async t=>{console.log(`\n\n${t} received. Shutting down gracefully...`);try{v.stop(),S.close(),console.log(`Server closed`);try{await c.get(e.p.BrowserService).closeAll(),console.log(`All browsers closed`)}catch{}try{await y.releasePort({repositoryPath:o,serviceName:r,serviceType:`tool`,environment:a,pid:process.pid}),console.log(`Service deregistered`)}catch{}console.log(`Goodbye!`),process.exit(0)}catch(e){console.error(`Error during shutdown:`,e),process.exit(1)}};process.on(`SIGINT`,()=>w(`SIGINT`)),process.on(`SIGTERM`,()=>w(`SIGTERM`))}catch(e){console.error(`Error starting HTTP server:`,e),process.exit(1)}}),ze={browser_click:[`input`],browser_fill:[`input`],browser_type:[`input`],browser_select:[`input`],browser_hover:[`input`],browser_drag:[`input`],browser_press_key:[`input`],browser_upload_file:[`input`],browser_navigate:[`navigation`],browser_go_back:[`navigation`],browser_go_forward:[`navigation`],browser_reload:[`navigation`],browser_wait_for:[`navigation`],browser_snapshot:[`snapshot`],browser_screenshot:[`snapshot`],browser_pdf:[`snapshot`],browser_list_pages:[`page`],browser_new_page:[`page`],browser_select_page:[`page`],browser_close_page:[`page`],browser_resize_page:[`page`,`emulation`],browser_handle_dialog:[`dialog`],browser_list_network_requests:[`network`],browser_get_network_request:[`network`],browser_list_console_messages:[`console`],browser_evaluate_script:[`script`],browser_emulate:[`emulation`],browser_expect:[`testing`],browser_start_trace:[`tracing`],browser_stop_trace:[`tracing`],browser_list_profiles:[`profile`],browser_delete_profile:[`profile`],run_spec:[`spec`,`testing`],discover_specs:[`spec`,`testing`],browser_launch:[`browser`],browser_close:[`browser`],browser_run_code:[`code`,`script`]};function Be(e){let t=new Set;for(let[n,r]of Object.entries(ze))r.some(t=>e.includes(t))&&t.add(n);return t}const Ve=3e3,He=4,Ue=150,We=[`browser_launch`],Ge=[`browser_new_page`];function q(e){if(!e?.content?.[0]?.text)return null;try{let t=JSON.parse(e.content[0].text);return{browserId:t.browserId,pageId:t.pageId,mode:t.mode,url:t.url}}catch{return null}}async function Ke(e){await new Promise(t=>setTimeout(t,e))}async function qe(e){let t=new AbortController,n=setTimeout(()=>t.abort(),3e3);try{let n=await fetch(`${e}/tools`,{signal:t.signal});if(!n.ok)throw Error(`HTTP error ${n.status}: ${n.statusText}`);let r=await n.json();if(r.error)throw Error(r.error);if(!Array.isArray(r.tools))throw Error(`Invalid /tools response: missing tools array`);if(r.tools.length===0)throw Error(`HTTP server returned an empty tool list`);return r.tools}finally{clearTimeout(n)}}async function Je(e){let t;for(let n=1;n<=4;n+=1)try{return await qe(e)}catch(e){t=e instanceof Error?e:Error(String(e)),n<4&&await Ke(150*n)}throw Error(`Failed to fetch tools after 4 attempts: ${t?.message??`Unknown error`}`,{cause:t})}function Ye(e){if(!e?.tags?.length&&!e?.exclude?.length)return null;let t=e.tags?.length?Be(e.tags):null,n=new Set(e.exclude??[]);if(!t)return n.size>0?n:null;for(let e of n)t.delete(e);return t}function Xe(e){let{httpBaseUrl:t,sessionTracker:n,defaultMode:i,toolFilter:o}=e,s=o?.tags?.length?Ye(o):null,c=new Set(o?.exclude??[]),l=s!==null||c.size>0,u=new r.Server({name:`browse-tool`,version:`0.1.0`},{capabilities:{tools:{}}}),d={name:`browser_list_session`,description:`List all browsers and pages created in this MCP session. Use this to see what resources you have available.`,inputSchema:{type:`object`,properties:{},required:[],additionalProperties:!1}},f=[];function p(e){return l?e.filter(e=>c.has(e.name)?!1:s===null?!0:s.has(e.name)):e}function m(e){return c.has(e)?!1:s===null?!0:s.has(e)}return u.setRequestHandler(a.ListToolsRequestSchema,async()=>{try{let e=await Je(t);f=e;let r=p(e);return n&&r.push(d),{tools:r}}catch(e){if(f.length>0){console.error(`Failed to refresh tools from HTTP server. Returning cached tools:`,e instanceof Error?e.message:String(e));let t=p(f);return n&&t.push(d),{tools:t}}let r=e instanceof Error?e.message:String(e);throw Error(`Failed to list tools from HTTP server at ${t}: ${r}`,{cause:e instanceof Error?e:void 0})}}),u.setRequestHandler(a.CallToolRequestSchema,async e=>{let{name:r,arguments:a}=e.params;if(r!==`browser_list_session`&&!m(r))return{content:[{type:`text`,text:`Tool "${r}" is not available (filtered by --tags or --exclude)`}],isError:!0};if(r===`browser_list_session`&&n){let e=n.getSessionState();return{content:[{type:`text`,text:JSON.stringify(e,null,2)}]}}let o=a||{};r===`browser_launch`&&i&&(o={...o,mode:i});try{let e=await fetch(`${t}/execute`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tool:r,arguments:o})});if(!e.ok){let t=await e.text();return{content:[{type:`text`,text:`HTTP error ${e.status}: ${t}`}],isError:!0}}let i=await e.json();if(!i.success)return{content:[{type:`text`,text:i.error||i.result?.content?.[0]?.text||`Unknown error from HTTP server`}],isError:!0};if(n&&i.result){if(We.includes(r)){let e=q(i.result);e?.browserId&&(n.trackBrowser(e.browserId,e.mode||`playwright`),e.pageId&&n.trackPage(e.pageId,e.browserId,e.url))}else if(Ge.includes(r)){let e=q(i.result);e?.pageId&&e?.browserId&&n.trackPage(e.pageId,e.browserId,e.url)}}return i.result||{content:[{type:`text`,text:`No result returned`}]}}catch(e){return{content:[{type:`text`,text:`Failed to execute tool via HTTP server: ${e instanceof Error?e.message:String(e)}`}],isError:!0}}}),u}const J=`stdio`,Ze=new Set([J]),Y=`chromium`,X=new Set([Y,`firefox`,`webkit`]),Z=new Set([`playwright`,`extension`,`vm`,`stealth`]),Qe=`browser_close`,$e=`,`,et=`spawned`,tt=`reused`,Q=`SIGINT`,nt=`SIGTERM`,rt=`PLAYWRIGHT_REGISTRY_DIR`,it=`PORT_REGISTRY_PATH`,at=`PLAYWRIGHT_PIDS_DIR`,ot=`PLAYWRIGHT_PROFILES_DIR`,st=`PLAYWRIGHT_HOST`,ct=`PLAYWRIGHT_PORT`,lt=0,ut=1;var dt=class extends Error{code=`INVALID_TRANSPORT`;recovery=`Use --type ${J} (currently the only supported transport)`;transportType;constructor(e,t){super(`Unknown transport type: ${e}`,t),this.name=`InvalidTransportError`,this.transportType=e}},ft=class extends Error{code=`INVALID_BROWSER_TYPE`;recovery=`Use --browser ${[...X].join(`, `)}`;browserType;constructor(e,t){super(`Unknown browser type: ${e}`,t),this.name=`InvalidBrowserTypeError`,this.browserType=e}},pt=class extends Error{code=`INVALID_LAUNCH_MODE`;recovery=`Use --mode ${[...Z].join(`, `)}`;launchMode;constructor(e,t){super(`Unknown launch mode: ${e}`,t),this.name=`InvalidLaunchModeError`,this.launchMode=e}};function mt(e){let t=e.toLowerCase();if(!X.has(t))throw new ft(e);return t}function ht(e){let t=e.toLowerCase();if(!Z.has(t))throw new pt(e);return t}function gt(e){return e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0)}function _t(e){let t=e.tags?gt(e.tags):void 0,n=e.exclude?gt(e.exclude):void 0;if(!(!t?.length&&!n?.length))return{tags:t,exclude:n}}var vt=class extends Error{code=`BROWSER_CLEANUP_FAILED`;recovery=`Browsers may still be running; check the HTTP server or kill processes manually`;failedBrowserIds;httpBaseUrl;constructor(e,t,n){super(`Failed to close ${e.length} browser(s): ${e.join(`, `)}`,n),this.name=`BrowserCleanupError`,this.failedBrowserIds=e,this.httpBaseUrl=t}},yt=class extends Error{code=`SESSION_SHUTDOWN_FAILED`;recovery=`Check logs for cleanup and transport errors; processes may need manual cleanup`;signal;constructor(e,t){super(`Shutdown failed for signal ${e}`,t),this.name=`SessionShutdownError`,this.signal=e}},bt=class extends Error{code=`HTTP_SERVER_START_FAILED`;recovery=`Check if the HTTP server binary exists and the port is available`;constructor(e){super(`Failed to start HTTP server`,e),this.name=`HttpServerStartError`}},xt=class extends Error{code=`MCP_SERVER_BOOTSTRAP_FAILED`;recovery=`Check if all dependencies are installed and try again`;constructor(e){super(`Failed to start MCP server`,e),this.name=`McpServerBootstrapError`}};async function St(e,t){let n=e.getBrowserIds(),r=[],i;for(let e of n)try{let n=await fetch(`${t}/execute`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({tool:`browser_close`,arguments:{browserId:e}})});if(!n.ok){let e=await n.text().catch(()=>``);throw Error(`HTTP ${n.status} from ${t}/execute: ${e}`)}console.error(` Closed browser: ${e}`)}catch(t){let n=t instanceof Error?t:Error(String(t));console.error(` Failed to close browser: ${e}`,n),r.push(e),i??=n}if(r.length>0)throw new vt(r,t,{cause:i});e.clear()}async function Ct(e,t,n){await e.start();let r=!1,i=async i=>{if(r)return;r=!0,console.error(`\nReceived ${i}, shutting down gracefully...`);let a;try{let e=t.getSessionState();e.totalBrowsers>0&&(console.error(` Cleaning up ${e.totalBrowsers} browser(s) from this session...`),await St(t,n))}catch(e){a=e instanceof Error?e:Error(String(e)),console.error(`Browser cleanup error:`,a)}finally{try{await e.stop()}catch(e){let t=e instanceof Error?e:Error(String(e));console.error(`Transport stop error:`,t),a??=t}if(a){let e=new yt(i,{cause:a});console.error(`Error during shutdown:`,e),process.exit(1)}process.exit(0)}};process.once(Q,()=>i(Q)),process.once(nt,()=>i(nt))}const wt=new t.Command(`mcp-serve`).description(`Start Playwright MCP server for browser automation`).option(`-t, --type <type>`,`Transport type: ${J}`,J).option(`-b, --browser <browser>`,`Default browser type: ${[...X].join(`, `)}`,Y).option(`--headless`,`Run browsers in headless mode by default`,!1).option(`--no-headless`,`Run browsers in headed mode (visible window)`).option(`--host <host>`,`Default host for HTTP services`,e.l()).option(`-p, --profile <name>`,`Default profile name for browser sessions`).option(`-m, --mode <mode>`,`Default launch mode: ${[...Z].join(`, `)}`).option(`--tags <tags>`,`Comma-separated tags to filter tools (e.g. input,navigation,snapshot)`).option(`--exclude <tools>`,`Comma-separated tool names to exclude (applied after --tags)`).option(`--registry-path <path>`,`Custom registry path or directory for service discovery`).option(`--registry-dir <path>`,`Custom registry directory for service discovery`).option(`--pids-dir <path>`,`Custom PIDs directory for process tracking`).option(`--profiles-dir <path>`,`Custom profiles directory for browser profiles`).action(async function(t){let n=O(`mcpServe`),r={type:k(this,`type`,t.type,n.type),browser:k(this,`browser`,t.browser,n.browser),headless:k(this,`headless`,t.headless,n.headless),profile:k(this,`profile`,t.profile,n.profile),mode:k(this,`mode`,t.mode,n.mode),host:k(this,`host`,t.host,n.host,process.env.PLAYWRIGHT_HOST),tags:k(this,`tags`,t.tags,n.tags),exclude:k(this,`exclude`,t.exclude,n.exclude),registryPath:k(this,`registryPath`,t.registryPath,n.registryPath,process.env.PLAYWRIGHT_REGISTRY_PATH??process.env.PORT_REGISTRY_PATH),registryDir:k(this,`registryDir`,t.registryDir,n.registryDir,process.env.PLAYWRIGHT_REGISTRY_DIR),pidsDir:k(this,`pidsDir`,t.pidsDir,n.pidsDir,process.env.PLAYWRIGHT_PIDS_DIR),profilesDir:k(this,`profilesDir`,t.profilesDir,n.profilesDir,process.env.PLAYWRIGHT_PROFILES_DIR)},i=r.type.toLowerCase();try{if(!Ze.has(i))throw new dt(i);let t=mt(r.browser),n=r.mode?ht(r.mode):void 0,a=_t(r);console.error(`Playwright MCP Server starting...`),console.error(` Transport: ${i}`),console.error(` Default browser: ${t}`),console.error(` Headless: ${r.headless}`),n&&console.error(` Default mode: ${n}`),r.profile&&console.error(` Profile: ${r.profile}`),a?.tags?.length&&console.error(` Tags: ${a.tags.join(`, `)}`),a?.exclude?.length&&console.error(` Exclude: ${a.exclude.join(`, `)}`);let o=r.registryPath||r.registryDir;o&&(process.env.PLAYWRIGHT_REGISTRY_DIR=o,process.env.PORT_REGISTRY_PATH=o,console.error(` Registry path: ${o}`)),r.pidsDir&&(process.env.PLAYWRIGHT_PIDS_DIR=r.pidsDir,console.error(` PIDs dir: ${r.pidsDir}`)),r.profilesDir&&(process.env.PLAYWRIGHT_PROFILES_DIR=r.profilesDir,console.error(` Profiles dir: ${r.profilesDir}`)),r.host&&(process.env.PLAYWRIGHT_HOST=r.host),process.env.PLAYWRIGHT_PORT=e.u().toString();let s=await e.a().get(e.p.HttpServerManager).ensureRunning();if(!s.running)throw new bt;let c=e.c(e.l(),s.port),l=s.spawned?`spawned`:`reused`;console.error(` HTTP server: ${l} on port ${s.port}`);let u=new e.o;await Ct(new e.t(Xe({httpBaseUrl:c,sessionTracker:u,defaultMode:n,toolFilter:a})),u,c)}catch(e){(e instanceof dt||e instanceof ft||e instanceof pt||e instanceof bt)&&(console.error(`Error [${e.code}]: ${e.message}`),console.error(`Recovery: ${e.recovery}`),process.exit(1));let t=new xt({cause:e instanceof Error?e:Error(String(e))});console.error(`Error [${t.code}]: ${t.message}`,t.cause),console.error(`Recovery: ${t.recovery}`),process.exit(1)}}),Tt=new t.Command(`status`).description(`Show status of HTTP server and diagnostics`).action(async()=>{try{let t=O(`httpServe`),n=process.env.PLAYWRIGHT_REGISTRY_PATH??process.env.PORT_REGISTRY_PATH??t.registryPath??t.registryDir;n&&(process.env.PLAYWRIGHT_REGISTRY_DIR=n,process.env.PLAYWRIGHT_REGISTRY_PATH=n,process.env.PORT_REGISTRY_PATH=n),!process.env.PLAYWRIGHT_PIDS_DIR&&t.pidsDir&&(process.env.PLAYWRIGHT_PIDS_DIR=t.pidsDir),console.log(`browse-tool Status
673
+ `),console.log(`-`.repeat(50));let r=await e.r().get(e.p.HttpServerManager).getStatus();if(r.running){let n=process.env.PLAYWRIGHT_HOST??t.host??e.l();console.log(`HTTP Server: Running`),console.log(` PID: ${r.pid}`),console.log(` Port: ${r.port}`),console.log(` Health: ${e.c(n,r.port)}/health`),r.browserCount!==void 0&&console.log(` Browsers: ${r.browserCount}`)}else console.log(`HTTP Server: Not Running`),r.error&&console.log(` Error: ${r.error}`);console.log(``),console.log(`-`.repeat(50)),process.exit(0)}catch(e){console.error(`Error getting status:`,e),process.exit(1)}}),Et=new t.Command(`stop`).description(`Stop HTTP server and clean up registry/PID files`).action(async()=>{try{let t=O(`httpServe`),n=process.env.PLAYWRIGHT_REGISTRY_PATH??process.env.PORT_REGISTRY_PATH??t.registryPath??t.registryDir;n&&(process.env.PLAYWRIGHT_REGISTRY_DIR=n,process.env.PLAYWRIGHT_REGISTRY_PATH=n,process.env.PORT_REGISTRY_PATH=n),!process.env.PLAYWRIGHT_PIDS_DIR&&t.pidsDir&&(process.env.PLAYWRIGHT_PIDS_DIR=t.pidsDir),console.log(`Stopping browse-tool services...`),await e.r().get(e.p.HttpServerManager).stop()?(console.log(`HTTP server stopped`),console.log(`Registry and PID files cleaned up`)):console.log(`No HTTP server was running`),console.log(`Done!`),process.exit(0)}catch(e){console.error(`Error stopping services:`,e),process.exit(1)}}),Dt=new Set([`--config`]);function Ot(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(Dt.has(n)){t+=1;continue}if(![...Dt].some(e=>n.startsWith(`${e}=`))&&!n.startsWith(`-`))return n}}function kt(e,t=!1){if(t)return!1;let n=Ot(e);return n?n===`tools`?!0:n===`help`&&e.includes(`tools`):!1}function At(e){return e.replace(/_/g,`-`)}function $(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function jt(e){let t=new Set;e.type&&t.add(e.type);for(let n of e.oneOf??[])n.type&&t.add(n.type);return t}function Mt(e,t){let n=jt(t);if(t.type===`number`||t.type===`integer`){let t=Number(e);if(Number.isNaN(t))throw Error(`Invalid number: ${e}`);return t}if(t.type===`boolean`){if(e===`true`||e===`1`)return!0;if(e===`false`||e===`0`)return!1;throw Error(`Invalid boolean: ${e}`)}if(n.has(`array`)||n.has(`object`))try{return JSON.parse(e)}catch{if(t.type===`array`||t.type===`object`)throw Error(`Invalid JSON: ${e}`)}if(n.has(`number`)||n.has(`integer`)){let t=Number(e);if(!Number.isNaN(t)&&e.trim()!==``)return t}return e}function Nt(e,t){let n=$(e);return t.type===`boolean`?`--${n}`:`--${n} <value>`}function Pt(n){let{definition:r,execute:i}=n,a=new t.Command(At(r.name));a.description(r.description);let o=r.inputSchema,s=o.properties||{},c=new Set(o.required||[]);for(let[e,n]of Object.entries(s)){let r=n,i=Nt(e,r),o=r.description||``;r.enum&&r.enum.length>0&&(o+=` (choices: ${r.enum.join(`, `)})`),r.default!==void 0&&(o+=` (default: ${JSON.stringify(r.default)})`),c.has(e)&&(o+=` [required]`),r.type===`boolean`?r.default===!0?a.option(`--no-${$(e)}`,`Disable ${o}`):a.option(i,o,r.default):r.enum&&r.enum.length>0?a.addOption(new t.Option(i,o).choices(r.enum)):a.option(i,o)}return a.action(async function(){let t=this.optsWithGlobals(),n=O(`tools`),a=k(this,`format`,t.format??`json`,n.format),o=k(this,`color`,t.color??!0,n.color),l=k(this,`port`,String(t.port??e.s),n.port===void 0?void 0:String(n.port),process.env.PLAYWRIGHT_PORT),u={format:a,color:o},d=le(r.name);try{let e={};for(let[n,r]of Object.entries(s)){let i=r,a=$(n).replace(/-([a-z])/g,(e,t)=>t.toUpperCase()),o=this.getOptionValueSourceWithGlobals(a),s=t[a];i.type===`boolean`&&i.default===!0&&(s=t[a]),(o===void 0||o===`default`||o===`implied`)&&d[n]!==void 0&&(s=d[n]),s!==void 0&&(typeof s==`string`&&i.type!==`string`?e[n]=Mt(s,i):e[n]=s)}for(let t of c)if(e[t]===void 0){let e=$(t);console.error(N(`Missing required option: --${e}`,u.color)),process.exit(1)}let n=Number.parseInt(l,10),a=A({port:n}),o=i?await i(e,{command:this,formatterOptions:u,port:n}):await a.execute(r.name,e),f=fe(o,u);f&&console.log(f),o.isError&&process.exit(1)}catch(e){console.error(N(e instanceof Error?e:String(e),u.color)),process.exit(1)}}),a}function Ft(e){return e.map(Pt)}const It=`browser_list_session`,Lt=`List browsers and pages currently tracked by the browse-tool HTTP server.`,Rt={name:`browser_list_session`,description:`List browsers and pages currently tracked by the browse-tool HTTP server.`,inputSchema:{type:`object`,properties:{},required:[],additionalProperties:!1}};function zt(){return new t.Command(`tools`).description(`Execute browser automation tools`).option(`-f, --format <format>`,`Output format: json, text, quiet`,`json`).option(`--no-color`,`Disable colored output`).option(`-p, --port <port>`,`HTTP server port`,String(e.s))}function Bt(e){return{browserCount:e.length,browsers:e.map(e=>({browserId:e.id,profileName:e.profileName,currentPageId:e.currentPageId,pageIds:e.pageIds,createdAt:e.createdAt}))}}function Vt(){return{definition:Rt,execute:async(e,t)=>{let n=await A({port:t.port}).listBrowsers();return{content:[{type:`text`,text:JSON.stringify(Bt(n),null,2)}]}}}}function Ht(e){return[...e.map(e=>({definition:e})),Vt()]}async function Ut(t,n){let r=O(`tools`),i=Number(n?.port??process.env.PLAYWRIGHT_PORT??r.port??e.s);try{let e=Ft(Ht(await A({port:i}).listTools()));for(let n of e)t.addCommand(n)}catch(e){let t=e instanceof Error?e.message:String(e);process.stderr.write(`${N(`Failed to load tool commands: ${t}`,!0)}\n`),process.stderr.write(`Make sure the HTTP server is running: browse-tool http-serve
674
+ `)}}const Wt=`PLAYWRIGHT_SKIP_DYNAMIC_TOOL_COMMANDS`;async function Gt(){let n=ce(process.argv.slice(2)),r=process.env.PLAYWRIGHT_PORT??n.config.commands.tools?.port??n.config.commands.exec?.port??e.s,i=new t.Command;i.name(`browse-tool`).description(`MCP server for browser automation using Playwright with profile management, page registry, and multi-browser support`).option(`--config <path>`,`Path to browse-tool config file or config directory`).version(_),i.addCommand(wt),i.addCommand(Re),i.addCommand(x),i.addCommand(Et),i.addCommand(Tt),i.addCommand(ye);let a=zt();kt(process.argv.slice(2),process.env.PLAYWRIGHT_SKIP_DYNAMIC_TOOL_COMMANDS===`1`)&&await Ut(a,{port:Number(r)}),i.addCommand(a),await i.parseAsync(process.argv)}Gt().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});