@zibby/mcp-browser 0.1.11 → 0.1.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.
package/README.md CHANGED
@@ -91,6 +91,27 @@ Set the session path via environment variable:
91
91
  export ZIBBY_SESSION_INFO=/path/to/.session-info.json
92
92
  ```
93
93
 
94
+ ## Remote / sidecar browser (pluggable runtime)
95
+
96
+ By default the wrapper launches a **local** Chromium (the official `@playwright/mcp`
97
+ behavior). If you set `BROWSER_WS_ENDPOINT` to a remote Chrome's CDP/WS endpoint,
98
+ it instead **connects to that browser over CDP** (`connectOverCDP`) and launches
99
+ **no local Chromium** — so a browser agent can run on a slim image with no baked
100
+ browser binary, pointing at a HOSTED Chrome (browserless / Browserbase / any
101
+ CDP endpoint). On a Zibby self-host box the platform's own browser is the
102
+ on-demand `browser` sidecar deployed from the marketplace, reached over MCP —
103
+ this knob is only for bringing your own hosted Chrome.
104
+
105
+ ```bash
106
+ # Connect to a hosted Chrome over CDP (no local Chromium needed):
107
+ export BROWSER_WS_ENDPOINT='wss://chrome.browserless.io?token=...'
108
+ npx @zibby/mcp-browser
109
+ ```
110
+
111
+ Implemented by reusing `@playwright/mcp`'s native `--cdp-endpoint` flag (which
112
+ takes precedence over local launch). Aliases `BROWSER_CDP_ENDPOINT` and
113
+ `PLAYWRIGHT_WS_ENDPOINT` are also accepted. Unset → unchanged (launch local).
114
+
94
115
  ## Compatibility
95
116
 
96
117
  - Node.js >= 18.0.0
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- var ne=Object.create;var W=Object.defineProperty;var re=Object.getOwnPropertyDescriptor;var se=Object.getOwnPropertyNames;var ie=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty;var ae=(e,n,r,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of se(n))!oe.call(e,t)&&t!==r&&W(e,t,{get:()=>n[t],enumerable:!(s=re(n,t))||s.enumerable});return e};var le=(e,n,r)=>(r=e!=null?ne(ie(e)):{},ae(n||!e||!e.__esModule?W(r,"default",{value:e,enumerable:!0}):r,e));const{spawn:ce,execFileSync:de}=require("child_process"),S=require("fs"),f=require("path"),x=[f.join(__dirname,"..","src","stable-id-inject.js"),f.join(__dirname,"..","stable-id-inject.js")].find(e=>S.existsSync(e))||f.join(__dirname,"..","src","stable-id-inject.js"),Y=f.join(require("os").tmpdir(),"zibby-mcp-debug.log");function i(e){const n=`[${new Date().toISOString()}] ${e}
3
- `;S.appendFileSync(Y,n),console.error(`[Zibby MCP] ${e}`)}S.appendFileSync(Y,`
2
+ var se=Object.create;var J=Object.defineProperty;var ie=Object.getOwnPropertyDescriptor;var oe=Object.getOwnPropertyNames;var ae=Object.getPrototypeOf,ce=Object.prototype.hasOwnProperty;var le=(e,n,s,i)=>{if(n&&typeof n=="object"||typeof n=="function")for(let t of oe(n))!ce.call(e,t)&&t!==s&&J(e,t,{get:()=>n[t],enumerable:!(i=ie(n,t))||i.enumerable});return e};var de=(e,n,s)=>(s=e!=null?se(ae(e)):{},le(n||!e||!e.__esModule?J(s,"default",{value:e,enumerable:!0}):s,e));const{spawn:fe,execFileSync:ue}=require("child_process"),p=require("fs"),f=require("path"),A=[f.join(__dirname,"..","src","stable-id-inject.js"),f.join(__dirname,"..","stable-id-inject.js")].find(e=>p.existsSync(e))||f.join(__dirname,"..","src","stable-id-inject.js"),G=f.join(require("os").tmpdir(),"zibby-mcp-debug.log");function r(e){const n=`[${new Date().toISOString()}] ${e}
3
+ `;p.appendFileSync(G,n),console.error(`[Zibby MCP] ${e}`)}p.appendFileSync(G,`
4
4
  === Zibby MCP Started ${new Date().toISOString()} PID:${process.pid} ===
5
- `),i(`Args: ${process.argv.slice(2).join(" ")}`),i(`Env ZIBBY_NODE_SESSION_PATH=${process.env.ZIBBY_NODE_SESSION_PATH||"(not set)"}`),i(`Env ZIBBY_SESSION_PATH=${process.env.ZIBBY_SESSION_PATH||"(not set)"}`),i(`Env ZIBBY_SESSION_INFO=${process.env.ZIBBY_SESSION_INFO||"(not set)"}`);let o=null,j="none";const w=[];let q=null;function fe(){if(process.env.ZIBBY_NODE_SESSION_PATH){o=process.env.ZIBBY_NODE_SESSION_PATH,j="env:ZIBBY_NODE_SESSION_PATH",S.mkdirSync(o,{recursive:!0}),i(`\u{1F4C1} Session from env: ${o}`);return}const e=process.argv.slice(2);for(const r of e)if(r.startsWith("--output-dir=")){o=r.split("=").slice(1).join("="),j="arg:--output-dir",S.mkdirSync(o,{recursive:!0}),i(`\u{1F4C1} Session from --output-dir: ${o}`);return}if(process.env.ZIBBY_SESSION_PATH){const r=f.join(process.env.ZIBBY_SESSION_PATH,".session-info.json");if(S.existsSync(r))try{const s=JSON.parse(S.readFileSync(r,"utf-8")),t=s.currentNode||"execute_live";o=f.join(s.sessionPath||process.env.ZIBBY_SESSION_PATH,t),j="file:per-session",S.mkdirSync(o,{recursive:!0}),i(`\u{1F4C1} Session from per-session file: ${o}`);return}catch(s){i(`\u26A0\uFE0F Per-session file read error: ${s.message}`)}}const n=[process.env.ZIBBY_SESSION_INFO,f.join(process.cwd(),".zibby/output/.session-info.json"),f.join(process.cwd(),"test-results/.session-info.json")].filter(Boolean);for(const r of n)if(S.existsSync(r))try{const s=JSON.parse(S.readFileSync(r,"utf-8")),t=s.currentNode||"execute_live";if(s.sessionPath){o=f.join(s.sessionPath,t),j=`file:shared(${f.basename(r)})`,S.mkdirSync(o,{recursive:!0}),i(`\u26A0\uFE0F Session from SHARED file (race-prone): ${o}`);return}}catch(s){i(`\u26A0\uFE0F Shared file read error: ${s.message}`)}i("\u26A0\uFE0F No session path resolved \u2014 events will not be recorded")}function G(e){const n=Math.floor(e/1e3),r=Math.floor(n/3600),s=Math.floor(n%3600/60),t=n%60,a=e%1e3;return`${String(r).padStart(2,"0")}:${String(s).padStart(2,"0")}:${String(t).padStart(2,"0")}.${String(a).padStart(3,"0")}`}function y(e,n){if(!o)return;const r=Date.now();q||(q=r);const s=r-q,t={id:w.length,type:e,timestamp:new Date(r).toISOString(),videoOffsetMs:s,videoOffsetFormatted:G(s),data:n,_recordedBy:"zibby-wrapper-v2"};return w.push(t),i(`\u{1F4DD} Event #${t.id}: ${e}${n.stableId?` [${n.stableId}]`:""}`),e==="close"?pe():N(),t.id}function ue(e,n){if(!o||e<0||e>=w.length)return;const r=w[e];r&&!r.data.stableId&&n&&(r.data.stableId=n,i(`\u{1F517} Event #${e} stableId: ${n}`),N())}function me(e){function a(u,d,m){if(d>=u.length)return null;const h=u[d];let b=1,z=128;for(;b<=8&&!(h&z);)b++,z>>=1;if(b>8||d+b>u.length)return null;let C=m?h:h&z-1;for(let Z=1;Z<b;Z++)C=C<<8|u[d+Z];return{value:C,length:b}}function l(u,d){if(d>=u.length)return null;const m=a(u,d,!0);if(!m)return null;d+=m.length;const h=a(u,d,!1);return h?(d+=h.length,{id:m.value,dataStart:d,dataSize:h.value,dataEnd:d+h.value}):null}function I(u,d,m){let h=0;for(let b=0;b<m;b++)h=h<<8|u[d+b];return h}function E(u,d,m){return m===4?u.readFloatBE(d):m===8?u.readDoubleBE(d):null}let c=0,p=1e6,v=null;const M=l(e,c);if(!M)return null;c=M.dataEnd;const P=l(e,c);if(!P||P.id!==408125543)return null;c=P.dataStart;const te=Math.min(P.dataEnd,e.length);for(;c<te;){const u=l(e,c);if(!u)break;if(u.id===357149030){let d=u.dataStart;for(;d<u.dataEnd;){const m=l(e,d);if(!m)break;m.id===2807729?p=I(e,m.dataStart,m.dataSize):m.id===17545&&(v=E(e,m.dataStart,m.dataSize)),d=m.dataEnd}break}c=u.dataEnd}return v!==null?v*p/1e6:null}function Se(e){try{const n=de("ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf-8",timeout:5e3}),r=parseFloat(n.trim());if(!isNaN(r)){const s=Math.round(r*1e3);return i(`\u{1F4CF} Video duration (ffprobe): ${s}ms`),s}}catch{i("\u26A0\uFE0F ffprobe not available, using WebM parser fallback")}try{const n=S.readFileSync(e),r=me(n);if(r){const s=Math.round(r);return i(`\u{1F4CF} Video duration (WebM parser): ${s}ms`),s}}catch(n){i(`\u26A0\uFE0F WebM parsing failed: ${n.message}`)}return null}function pe(){if(!o||w.length===0)return;let e=null,n=0;const r=40;let s=0,t=0;for(;!e&&n<r;){n++;let c=null;if(S.existsSync(f.join(o,"recording.webm")))c=f.join(o,"recording.webm"),n===1&&i("Found recording.webm");else try{const p=S.readdirSync(o);n===1&&i(`Directory contains ${p.length} files: ${p.join(", ")}`);const v=p.filter(M=>M.endsWith(".webm"));n===1&&v.length>0&&i(`Found ${v.length} .webm file(s): ${v.join(", ")}`),v.length>0&&(c=f.join(o,v[0]))}catch(p){n===1&&i(`\u26A0\uFE0F Error reading directory: ${p.message}`)}if(c&&S.existsSync(c))try{const v=S.statSync(c).size;if(v>0&&v===s){if(t++,t>=2){e=c,i(`\u2705 Video file stable after ${n} attempts: ${f.basename(e)} (${v} bytes)`);break}}else t=0,s=v}catch(p){i(`\u26A0\uFE0F Error checking file: ${p.message}`)}if(!e){n%5===0&&i(`\u23F3 Waiting for stable video file... (attempt ${n}/${r}, size: ${s})`);const p=Date.now();for(;Date.now()-p<500;);}}if(!e){i(`\u26A0\uFE0F Video file not found/stable after ${n} attempts in: ${o}`),N();return}const a=Se(e);if(!a){i("\u26A0\uFE0F Could not determine video duration, using fallback"),N();return}const l=w.find(c=>c.type==="close");if(!l){i("\u26A0\uFE0F No close event found"),N();return}const I=new Date(l.timestamp).getTime(),E=I-a;i(`\u{1F4CA} Calculated video start: ${new Date(E).toISOString()}`),i(` Close timestamp: ${I}ms`),i(` Video duration: ${a}ms`),w.forEach(c=>{const p=new Date(c.timestamp).getTime();c.videoOffsetMs=p-E,c.videoOffsetFormatted=G(c.videoOffsetMs)}),i(`\u2705 Recalculated ${w.length} events using accurate video start time`),N()}function N(){if(o)try{const e=f.join(o,"events.json");S.writeFileSync(e,JSON.stringify(w,null,2))}catch{}}i(`CWD: ${process.cwd()}`),fe();const U=process.argv.slice(2);let O=null;for(const e of U){const n=e.match(/^--save-video=(\d+)x(\d+)$/);if(n){O={width:parseInt(n[1],10),height:parseInt(n[2],10)};break}}const _=U.filter(e=>!e.startsWith("--save-video"));S.existsSync(x)?(_.unshift("--init-script",x),i(`\u2705 Stable ID injection enabled: ${x}`)):i(`\u26A0\uFE0F Stable ID script not found: ${x}`);const A=_.findIndex(e=>e==="--caps");if(A>=0&&_[A+1])_[A+1].includes("devtools")||(_[A+1]+=",devtools");else{const e=_.findIndex(n=>n.startsWith("--caps="));e>=0?_[e].includes("devtools")||(_[e]+=",devtools"):_.push("--caps","devtools")}if(o){const e=_.findIndex(n=>n.startsWith("--output-dir"));e!==-1?_[e]=`--output-dir=${o}`:_.push("--output-dir",o),i(`\u{1F4F9} Video output: ${o} (source: ${j})`)}const ve=f.dirname(require.resolve("@playwright/mcp")),_e=f.join(ve,"cli.js"),g=ce(process.execPath,[_e,..._],{stdio:["pipe","pipe","inherit"]});let $=!1,H=!1,Q=8e5;const D=new Set;function he(){if(H||!o)return;H=!0;const e=Q++;D.add(e);const n=o?f.join(o,"recording.webm"):"recording.webm",r={jsonrpc:"2.0",id:e,method:"tools/call",params:{name:"browser_start_video",arguments:{filename:n,...O?{size:O}:{}}}};try{g.stdin.write(JSON.stringify(r)+`
6
- `),i(`\u{1F3AC} Auto-started video recording${O?` (${O.width}x${O.height})`:""}`)}catch(s){D.delete(e),i(`\u26A0\uFE0F browser_start_video send failed: ${s.message}`)}}function Ie(){if(!H)return;const e=Q++;D.add(e);const n={jsonrpc:"2.0",id:e,method:"tools/call",params:{name:"browser_stop_video",arguments:{}}};try{g.stdin.write(JSON.stringify(n)+`
7
- `),i("\u{1F3AC} Auto-stopped video recording")}catch(r){D.delete(e),i(`\u26A0\uFE0F browser_stop_video send failed: ${r.message}`)}}const ge=2e3,be=5e3,K="frames";let X=0,we=1e6;const R=new Set;let k=null;function L(){k&&(clearInterval(k),k=null)}function $e(){if(o)try{S.mkdirSync(f.join(o,K),{recursive:!0})}catch{}}function J(){return f.join(o,K,`live-frame-${Date.now()}.png`)}function ye(){L(),!(!$||!o)&&(k=setInterval(()=>{if(!$||!o){L();return}ee(!0,J())},be))}function ee(e,n){if(!o||!$)return;$e();const r=Date.now();if(!e&&r-X<ge)return;X=r;const s=n||J(),t=we++;R.add(t);const a={jsonrpc:"2.0",id:t,method:"tools/call",params:{name:"browser_take_screenshot",arguments:{type:"png",filename:s}}};try{g.stdin.write(JSON.stringify(a)+`
8
- `),i(`\u{1F4F8} live-frame queued: ${s}`)}catch(l){R.delete(t),i(`\u26A0\uFE0F live-frame send failed: ${l.message}`)}}function Ee(e){!e||typeof e!="string"||!e.startsWith("browser_")||e==="browser_close"||e==="browser_take_screenshot"||!o||!$||ee(!1,J())}const B=new Map;let Ne=9e5;const V=new Map;let T="";process.stdin.on("data",e=>{T+=e.toString();const n=T.split(`
9
- `);T=n.pop()||"";for(const r of n)if(r.trim()){try{const s=JSON.parse(r);if(s.method&&i(`\u{1F4E8} STDIN: ${s.method} ${s.params?.name||""}`),s.method==="tools/call"&&s.params){const t=s.params.name,a=s.params.arguments||{};B.set(s.id,{toolName:t,toolArgs:a});let l=-1;t==="browser_navigate"?($=!0,ye(),l=y("navigate",{url:a.url})):t==="browser_click"?l=y("click",{element:a.element,ref:a.ref}):t==="browser_type"?l=y("type",{element:a.element,ref:a.ref,text:a.text}):t==="browser_select_option"?l=y("select",{element:a.element,ref:a.ref,values:a.values}):t==="browser_fill_form"?l=y("fill_form",{fields:a.fields}):t==="browser_hover"?l=y("hover",{element:a.element,ref:a.ref}):t==="browser_close"?(Ie(),l=y("close",{}),$=!1,L()):t==="browser_snapshot"&&(l=y("snapshot",{})),l>=0&&(B.get(s.id).eventId=l)}}catch{}g.stdin.write(r+`
10
- `)}}),process.stdin.on("end",()=>{T.trim()&&g.stdin.write(T+`
11
- `),g.stdin.end()});let F="";g.stdout.on("data",e=>{F+=e.toString();const n=F.split(`
12
- `);F=n.pop()||"";for(const r of n){if(!r.trim())continue;let s=!0;try{const t=JSON.parse(r);if(t.id&&D.has(t.id))D.delete(t.id),t.error&&i(`\u26A0\uFE0F Video RPC error: ${t.error?.message||JSON.stringify(t.error)}`),s=!1;else if(t.id&&R.has(t.id))R.delete(t.id),t.error&&i(`\u26A0\uFE0F Screenshot RPC error: ${t.error?.message||JSON.stringify(t.error)}`),s=!1;else if(t.id&&B.has(t.id)){const a=B.get(t.id);if(B.delete(t.id),!t.error&&$&&Ee(a.toolName),!t.error&&a.toolName==="browser_navigate"&&he(),!t.error&&$&&a.eventId>=0&&["browser_click","browser_type","browser_select_option","browser_fill_form","browser_hover"].includes(a.toolName)){const I=Ne++,E={jsonrpc:"2.0",id:I,method:"tools/call",params:{name:"browser_evaluate",arguments:{function:"() => { const match = document.cookie.match(/(?:^|; )__zibbyLastStableId=([^;]*)/); const id = match ? decodeURIComponent(match[1]) : (window.__zibbyLastStableId || null); return id; }"}}};i(`\u{1F50D} Querying stable ID for event #${a.eventId}`),V.set(I,{eventId:a.eventId}),g.stdin.write(JSON.stringify(E)+`
13
- `)}}if(t.id&&V.has(t.id)){const a=V.get(t.id);if(V.delete(t.id),i(`\u{1F4E5} Stable ID response for event #${a.eventId}: ${JSON.stringify(t.result||t.error||"no result").slice(0,200)}`),t.result?.content?.[0]?.text){const l=t.result.content[0].text,I=l.match(/zibby-[a-zA-Z0-9-]+/);I?(i(`\u2705 Found stable ID: ${I[0]}`),ue(a.eventId,I[0])):i(`\u26A0\uFE0F No stable ID found in: ${l.slice(0,100)}`)}else t.error&&i(`\u274C Stable ID query error: ${t.error?.message||JSON.stringify(t.error)}`);s=!1}}catch{}s&&process.stdout.write(r+`
14
- `)}}),g.on("close",e=>{L(),$=!1,F.trim()&&process.stdout.write(F),process.exit(e||0)}),process.on("SIGINT",()=>{g.kill("SIGINT")}),process.on("SIGTERM",()=>{g.kill("SIGTERM")});
5
+ `),r(`Args: ${process.argv.slice(2).join(" ")}`),r(`Env ZIBBY_NODE_SESSION_PATH=${process.env.ZIBBY_NODE_SESSION_PATH||"(not set)"}`),r(`Env ZIBBY_SESSION_PATH=${process.env.ZIBBY_SESSION_PATH||"(not set)"}`),r(`Env ZIBBY_SESSION_INFO=${process.env.ZIBBY_SESSION_INFO||"(not set)"}`);let o=null,T="none";const w=[];let q=null;function me(){if(process.env.ZIBBY_NODE_SESSION_PATH){o=process.env.ZIBBY_NODE_SESSION_PATH,T="env:ZIBBY_NODE_SESSION_PATH",p.mkdirSync(o,{recursive:!0}),r(`\u{1F4C1} Session from env: ${o}`);return}const e=process.argv.slice(2);for(const s of e)if(s.startsWith("--output-dir=")){o=s.split("=").slice(1).join("="),T="arg:--output-dir",p.mkdirSync(o,{recursive:!0}),r(`\u{1F4C1} Session from --output-dir: ${o}`);return}if(process.env.ZIBBY_SESSION_PATH){const s=f.join(process.env.ZIBBY_SESSION_PATH,".session-info.json");if(p.existsSync(s))try{const i=JSON.parse(p.readFileSync(s,"utf-8")),t=i.currentNode||"execute_live";o=f.join(i.sessionPath||process.env.ZIBBY_SESSION_PATH,t),T="file:per-session",p.mkdirSync(o,{recursive:!0}),r(`\u{1F4C1} Session from per-session file: ${o}`);return}catch(i){r(`\u26A0\uFE0F Per-session file read error: ${i.message}`)}}const n=[process.env.ZIBBY_SESSION_INFO,f.join(process.cwd(),".zibby/output/.session-info.json"),f.join(process.cwd(),"test-results/.session-info.json")].filter(Boolean);for(const s of n)if(p.existsSync(s))try{const i=JSON.parse(p.readFileSync(s,"utf-8")),t=i.currentNode||"execute_live";if(i.sessionPath){o=f.join(i.sessionPath,t),T=`file:shared(${f.basename(s)})`,p.mkdirSync(o,{recursive:!0}),r(`\u26A0\uFE0F Session from SHARED file (race-prone): ${o}`);return}}catch(i){r(`\u26A0\uFE0F Shared file read error: ${i.message}`)}r("\u26A0\uFE0F No session path resolved \u2014 events will not be recorded")}function U(e){const n=Math.floor(e/1e3),s=Math.floor(n/3600),i=Math.floor(n%3600/60),t=n%60,a=e%1e3;return`${String(s).padStart(2,"0")}:${String(i).padStart(2,"0")}:${String(t).padStart(2,"0")}.${String(a).padStart(3,"0")}`}function E(e,n){if(!o)return;const s=Date.now();q||(q=s);const i=s-q,t={id:w.length,type:e,timestamp:new Date(s).toISOString(),videoOffsetMs:i,videoOffsetFormatted:U(i),data:n,_recordedBy:"zibby-wrapper-v2"};return w.push(t),r(`\u{1F4DD} Event #${t.id}: ${e}${n.stableId?` [${n.stableId}]`:""}`),e==="close"?_e():N(),t.id}function pe(e,n){if(!o||e<0||e>=w.length)return;const s=w[e];s&&!s.data.stableId&&n&&(s.data.stableId=n,r(`\u{1F517} Event #${e} stableId: ${n}`),N())}function Se(e){function a(u,d,m){if(d>=u.length)return null;const h=u[d];let b=1,V=128;for(;b<=8&&!(h&V);)b++,V>>=1;if(b>8||d+b>u.length)return null;let z=m?h:h&V-1;for(let Z=1;Z<b;Z++)z=z<<8|u[d+Z];return{value:z,length:b}}function c(u,d){if(d>=u.length)return null;const m=a(u,d,!0);if(!m)return null;d+=m.length;const h=a(u,d,!1);return h?(d+=h.length,{id:m.value,dataStart:d,dataSize:h.value,dataEnd:d+h.value}):null}function I(u,d,m){let h=0;for(let b=0;b<m;b++)h=h<<8|u[d+b];return h}function y(u,d,m){return m===4?u.readFloatBE(d):m===8?u.readDoubleBE(d):null}let l=0,S=1e6,_=null;const F=c(e,l);if(!F)return null;l=F.dataEnd;const M=c(e,l);if(!M||M.id!==408125543)return null;l=M.dataStart;const re=Math.min(M.dataEnd,e.length);for(;l<re;){const u=c(e,l);if(!u)break;if(u.id===357149030){let d=u.dataStart;for(;d<u.dataEnd;){const m=c(e,d);if(!m)break;m.id===2807729?S=I(e,m.dataStart,m.dataSize):m.id===17545&&(_=y(e,m.dataStart,m.dataSize)),d=m.dataEnd}break}l=u.dataEnd}return _!==null?_*S/1e6:null}function ve(e){try{const n=ue("ffprobe",["-v","error","-show_entries","format=duration","-of","default=noprint_wrappers=1:nokey=1",e],{encoding:"utf-8",timeout:5e3}),s=parseFloat(n.trim());if(!isNaN(s)){const i=Math.round(s*1e3);return r(`\u{1F4CF} Video duration (ffprobe): ${i}ms`),i}}catch{r("\u26A0\uFE0F ffprobe not available, using WebM parser fallback")}try{const n=p.readFileSync(e),s=Se(n);if(s){const i=Math.round(s);return r(`\u{1F4CF} Video duration (WebM parser): ${i}ms`),i}}catch(n){r(`\u26A0\uFE0F WebM parsing failed: ${n.message}`)}return null}function _e(){if(!o||w.length===0)return;let e=null,n=0;const s=40;let i=0,t=0;for(;!e&&n<s;){n++;let l=null;if(p.existsSync(f.join(o,"recording.webm")))l=f.join(o,"recording.webm"),n===1&&r("Found recording.webm");else try{const S=p.readdirSync(o);n===1&&r(`Directory contains ${S.length} files: ${S.join(", ")}`);const _=S.filter(F=>F.endsWith(".webm"));n===1&&_.length>0&&r(`Found ${_.length} .webm file(s): ${_.join(", ")}`),_.length>0&&(l=f.join(o,_[0]))}catch(S){n===1&&r(`\u26A0\uFE0F Error reading directory: ${S.message}`)}if(l&&p.existsSync(l))try{const _=p.statSync(l).size;if(_>0&&_===i){if(t++,t>=2){e=l,r(`\u2705 Video file stable after ${n} attempts: ${f.basename(e)} (${_} bytes)`);break}}else t=0,i=_}catch(S){r(`\u26A0\uFE0F Error checking file: ${S.message}`)}if(!e){n%5===0&&r(`\u23F3 Waiting for stable video file... (attempt ${n}/${s}, size: ${i})`);const S=Date.now();for(;Date.now()-S<500;);}}if(!e){r(`\u26A0\uFE0F Video file not found/stable after ${n} attempts in: ${o}`),N();return}const a=ve(e);if(!a){r("\u26A0\uFE0F Could not determine video duration, using fallback"),N();return}const c=w.find(l=>l.type==="close");if(!c){r("\u26A0\uFE0F No close event found"),N();return}const I=new Date(c.timestamp).getTime(),y=I-a;r(`\u{1F4CA} Calculated video start: ${new Date(y).toISOString()}`),r(` Close timestamp: ${I}ms`),r(` Video duration: ${a}ms`),w.forEach(l=>{const S=new Date(l.timestamp).getTime();l.videoOffsetMs=S-y,l.videoOffsetFormatted=U(l.videoOffsetMs)}),r(`\u2705 Recalculated ${w.length} events using accurate video start time`),N()}function N(){if(o)try{const e=f.join(o,"events.json");p.writeFileSync(e,JSON.stringify(w,null,2))}catch{}}r(`CWD: ${process.cwd()}`),me();const Q=process.argv.slice(2);let O=null;for(const e of Q){const n=e.match(/^--save-video=(\d+)x(\d+)$/);if(n){O={width:parseInt(n[1],10),height:parseInt(n[2],10)};break}}const v=Q.filter(e=>!e.startsWith("--save-video"));p.existsSync(A)?(v.unshift("--init-script",A),r(`\u2705 Stable ID injection enabled: ${A}`)):r(`\u26A0\uFE0F Stable ID script not found: ${A}`);const R=v.findIndex(e=>e==="--caps");if(R>=0&&v[R+1])v[R+1].includes("devtools")||(v[R+1]+=",devtools");else{const e=v.findIndex(n=>n.startsWith("--caps="));e>=0?v[e].includes("devtools")||(v[e]+=",devtools"):v.push("--caps","devtools")}if(o){const e=v.findIndex(n=>n.startsWith("--output-dir"));e!==-1?v[e]=`--output-dir=${o}`:v.push("--output-dir",o),r(`\u{1F4F9} Video output: ${o} (source: ${T})`)}const x=(process.env.BROWSER_WS_ENDPOINT||process.env.BROWSER_CDP_ENDPOINT||process.env.PLAYWRIGHT_WS_ENDPOINT||"").trim(),K=v.some(e=>e==="--cdp-endpoint"||e.startsWith("--cdp-endpoint="));x&&!K?(v.push(`--cdp-endpoint=${x}`),r(`\u{1F310} Remote browser mode: connecting over CDP to ${x} (no local Chromium launched)`)):x&&K&&r("\u{1F310} Remote browser endpoint set in env, but --cdp-endpoint already in args \u2014 leaving args unchanged");const he=f.dirname(require.resolve("@playwright/mcp")),Ie=f.join(he,"cli.js"),g=fe(process.execPath,[Ie,...v],{stdio:["pipe","pipe","inherit"]});let $=!1,H=!1,X=8e5;const D=new Set;function ge(){if(H||!o)return;H=!0;const e=X++;D.add(e);const n=o?f.join(o,"recording.webm"):"recording.webm",s={jsonrpc:"2.0",id:e,method:"tools/call",params:{name:"browser_start_video",arguments:{filename:n,...O?{size:O}:{}}}};try{g.stdin.write(JSON.stringify(s)+`
6
+ `),r(`\u{1F3AC} Auto-started video recording${O?` (${O.width}x${O.height})`:""}`)}catch(i){D.delete(e),r(`\u26A0\uFE0F browser_start_video send failed: ${i.message}`)}}function be(){if(!H)return;const e=X++;D.add(e);const n={jsonrpc:"2.0",id:e,method:"tools/call",params:{name:"browser_stop_video",arguments:{}}};try{g.stdin.write(JSON.stringify(n)+`
7
+ `),r("\u{1F3AC} Auto-stopped video recording")}catch(s){D.delete(e),r(`\u26A0\uFE0F browser_stop_video send failed: ${s.message}`)}}const we=2e3,$e=5e3,ee="frames";let te=0,Ee=1e6;const k=new Set;let C=null;function L(){C&&(clearInterval(C),C=null)}function ye(){if(o)try{p.mkdirSync(f.join(o,ee),{recursive:!0})}catch{}}function Y(){return f.join(o,ee,`live-frame-${Date.now()}.png`)}function Ne(){L(),!(!$||!o)&&(C=setInterval(()=>{if(!$||!o){L();return}ne(!0,Y())},$e))}function ne(e,n){if(!o||!$)return;ye();const s=Date.now();if(!e&&s-te<we)return;te=s;const i=n||Y(),t=Ee++;k.add(t);const a={jsonrpc:"2.0",id:t,method:"tools/call",params:{name:"browser_take_screenshot",arguments:{type:"png",filename:i}}};try{g.stdin.write(JSON.stringify(a)+`
8
+ `),r(`\u{1F4F8} live-frame queued: ${i}`)}catch(c){k.delete(t),r(`\u26A0\uFE0F live-frame send failed: ${c.message}`)}}function Oe(e){!e||typeof e!="string"||!e.startsWith("browser_")||e==="browser_close"||e==="browser_take_screenshot"||!o||!$||ne(!1,Y())}const B=new Map;let De=9e5;const W=new Map;let P="";process.stdin.on("data",e=>{P+=e.toString();const n=P.split(`
9
+ `);P=n.pop()||"";for(const s of n)if(s.trim()){try{const i=JSON.parse(s);if(i.method&&r(`\u{1F4E8} STDIN: ${i.method} ${i.params?.name||""}`),i.method==="tools/call"&&i.params){const t=i.params.name,a=i.params.arguments||{};B.set(i.id,{toolName:t,toolArgs:a});let c=-1;t==="browser_navigate"?($=!0,Ne(),c=E("navigate",{url:a.url})):t==="browser_click"?c=E("click",{element:a.element,ref:a.ref}):t==="browser_type"?c=E("type",{element:a.element,ref:a.ref,text:a.text}):t==="browser_select_option"?c=E("select",{element:a.element,ref:a.ref,values:a.values}):t==="browser_fill_form"?c=E("fill_form",{fields:a.fields}):t==="browser_hover"?c=E("hover",{element:a.element,ref:a.ref}):t==="browser_close"?(be(),c=E("close",{}),$=!1,L()):t==="browser_snapshot"&&(c=E("snapshot",{})),c>=0&&(B.get(i.id).eventId=c)}}catch{}g.stdin.write(s+`
10
+ `)}}),process.stdin.on("end",()=>{P.trim()&&g.stdin.write(P+`
11
+ `),g.stdin.end()});let j="";g.stdout.on("data",e=>{j+=e.toString();const n=j.split(`
12
+ `);j=n.pop()||"";for(const s of n){if(!s.trim())continue;let i=!0;try{const t=JSON.parse(s);if(t.id&&D.has(t.id))D.delete(t.id),t.error&&r(`\u26A0\uFE0F Video RPC error: ${t.error?.message||JSON.stringify(t.error)}`),i=!1;else if(t.id&&k.has(t.id))k.delete(t.id),t.error&&r(`\u26A0\uFE0F Screenshot RPC error: ${t.error?.message||JSON.stringify(t.error)}`),i=!1;else if(t.id&&B.has(t.id)){const a=B.get(t.id);if(B.delete(t.id),!t.error&&$&&Oe(a.toolName),!t.error&&a.toolName==="browser_navigate"&&ge(),!t.error&&$&&a.eventId>=0&&["browser_click","browser_type","browser_select_option","browser_fill_form","browser_hover"].includes(a.toolName)){const I=De++,y={jsonrpc:"2.0",id:I,method:"tools/call",params:{name:"browser_evaluate",arguments:{function:"() => { const match = document.cookie.match(/(?:^|; )__zibbyLastStableId=([^;]*)/); const id = match ? decodeURIComponent(match[1]) : (window.__zibbyLastStableId || null); return id; }"}}};r(`\u{1F50D} Querying stable ID for event #${a.eventId}`),W.set(I,{eventId:a.eventId}),g.stdin.write(JSON.stringify(y)+`
13
+ `)}}if(t.id&&W.has(t.id)){const a=W.get(t.id);if(W.delete(t.id),r(`\u{1F4E5} Stable ID response for event #${a.eventId}: ${JSON.stringify(t.result||t.error||"no result").slice(0,200)}`),t.result?.content?.[0]?.text){const c=t.result.content[0].text,I=c.match(/zibby-[a-zA-Z0-9-]+/);I?(r(`\u2705 Found stable ID: ${I[0]}`),pe(a.eventId,I[0])):r(`\u26A0\uFE0F No stable ID found in: ${c.slice(0,100)}`)}else t.error&&r(`\u274C Stable ID query error: ${t.error?.message||JSON.stringify(t.error)}`);i=!1}}catch{}i&&process.stdout.write(s+`
14
+ `)}}),g.on("close",e=>{L(),$=!1,j.trim()&&process.stdout.write(j),process.exit(e||0)}),process.on("SIGINT",()=>{g.kill("SIGINT")}),process.on("SIGTERM",()=>{g.kill("SIGTERM")});
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/mcp-browser",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "description": "Wrapper for @playwright/mcp with stable ID support and event recording",
5
5
  "type": "commonjs",
6
6
  "main": "dist/bin/mcp-browser-zibby.js",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zibby/mcp-browser",
3
- "version": "0.1.11",
3
+ "version": "0.1.13",
4
4
  "description": "Wrapper for @playwright/mcp with stable ID support and event recording",
5
5
  "type": "commonjs",
6
6
  "main": "dist/bin/mcp-browser-zibby.js",