@gaiventures/pilotfish-mcp 0.1.21 → 0.1.22

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 (2) hide show
  1. package/cli.js +2 -2
  2. package/package.json +1 -1
package/cli.js CHANGED
@@ -125,7 +125,7 @@ ${s.trim().split(`
125
125
  `).replace(/\n[ \t]+/g,`
126
126
  `).replace(/\n{3,}/g,`
127
127
 
128
- `).trim();if(i.length<=e)return i;let r=i.slice(0,e);return/[\uD800-\uDBFF]$/.test(r)?r.slice(0,-1):r}l(be,"pageText");var Co=new Set("a an the of in on at to for from by with into inside within under over near this that these those its it is are be and or & + - element elements area section part page panel popup modal dialog window side header footer sidebar".split(" ")),Is={button:["button","btn"],link:["link","hyperlink"],checkbox:["checkbox","check","tick"],radio:["radio"],textbox:["field","input","box","textbox","textfield"],searchbox:["search","field","input","box","searchbox"],combobox:["dropdown","select","combobox","picker","menu"],listbox:["dropdown","select","listbox","list"],tab:["tab"],option:["option","choice"],menuitem:["menu","menuitem","option"],heading:["heading","title","header"],slider:["slider","range"],switch:["switch","toggle"]},Ao=new Set(Object.values(Is).flat()),Ts=l(n=>n.toLowerCase().split(/[^\p{L}\p{N}$€£₹%]+/u).filter(Boolean),"findTokens");function As(n,e,{limit:t=20}={}){let s=e.split(/[,;|\n]+|\s+(?:or|\/)\s+/i).map(p=>p.trim()).filter(Boolean),o=n.nodes.filter(p=>p.text===void 0&&p.visible&&(p.ref||p.role==="heading")),i=new Map,r=l(p=>{let f=i.get(p);if(!f){let y=`${p.tag} ${p.role} ${p.name} ${ie(p,200)} ${Object.values(p.attrs).join(" ")}`.toLowerCase();f={tokens:Ts(y),flat:` ${Ts(y).join(" ")} `,name:p.name.trim().toLowerCase()},i.set(p,f)}return f},"hayOf"),a=new Map,c=new Map(n.nodes.map((p,f)=>[p,f])),d=l((p,f,y)=>{let b=r(f);return b.tokens.includes(p)?1:b.tokens.some(m=>p.length>=4&&m.startsWith(p)||m.length>=4&&p.startsWith(m))?.75:p.length>=3&&b.flat.includes(p)?.6:y&&(Is[f.role]??[]).includes(p)?1:0},"wordIn"),u=new Map,h=l((p,f)=>{let y=`${f?"r":""}${p}`,b=u.get(y);return b===void 0&&(b=o.reduce((m,w)=>m+(d(p,w,f)>0?1:0),0),u.set(y,b)),b},"docFreq");for(let p of s){let f=Ts(p),y=f.filter(M=>!Co.has(M)&&!Ao.has(M)),b=!y.length;if(b&&(y=f.filter(M=>!Co.has(M))),y.length||(y=f),!y.length)continue;let m=f.filter(M=>Ao.has(M)),w=y.map(M=>{let _=h(M,b);return _?Math.log(1+o.length/_):0}),v=w.reduce((M,_)=>M+_,0);if(!v)continue;let T=[];for(let M of o){let _=r(M),x=y.map($=>d($,M,b));if(!x.some($=>$>0))continue;let g=x.every($=>$>=1),S=g?1:x.reduce(($,I,R)=>$+I*w[R],0)/v,E=0;for(let $=0;$<y.length;$++)for(let I=y.length;I>$+E;I--)if(_.flat.includes(` ${y.slice($,I).join(" ")} `)){E=I-$;break}let A=S+(y.length>1?.5*E/y.length:0);_.name&&_.name===p.trim().toLowerCase()&&(A+=1),m.length&&(Is[M.role]??[]).some($=>m.includes($))&&(A+=.25),A-=Math.min(.2,_.tokens.length/500);let k=x.filter($=>$>0).length/y.length;T.push({n:M,cover:g?1:Math.min(S,.99),score:A,run:E,raw:k})}let C=T.filter(M=>M.cover>=1),D=C.length?C:T.filter(M=>M.raw>=.5&&(M.cover>=.6||M.run>=2&&M.cover>=.4)).sort((M,_)=>_.score-M.score).slice(0,8);for(let M of D){let _=a.get(M.n),x=M.cover>=1;(!_||M.score>_.score)&&a.set(M.n,{score:M.score,exact:x||!!_?.exact,order:c.get(M.n)??0})}}return[...a.entries()].sort((p,f)=>Number(f[1].exact)-Number(p[1].exact)||f[1].score-p[1].score||p[1].order-f[1].order).slice(0,t).map(([p,f])=>({node:p,exact:f.exact}))}l(As,"findScored");function de(n){let e=n.ref?`[${n.ref}]`:"",t=Mt(n,80),s=Po(n,t);return`${e}<${n.tag}${s}${t?`>${t}</${n.tag}>`:" />"}`}l(de,"describeNode");function Rt(n){return{ref:n.ref??"",backendNodeId:n.backendNodeId,frame:n.frame,frameId:n.frameId,tag:n.tag,role:n.role,name:n.name,nth:n.nth,key:se(n),groupSize:n.groupSize,identity:n.identity,description:de(n)}}l(Rt,"handleFor");async function Pt(n,e,{allowReground:t=!0}={}){if(e.frame.session.closed)throw new B("frame_detached",`The frame containing ${e.ref} was detached; take a new snapshot.`);let s=l(a=>a.replace(/\s+/g," ").trim().slice(0,80),"norm");try{let a=await e.frame.callOnNode(e.backendNodeId,"function(){ return { connected: this.isConnected === true, tag: (this.localName || '').toLowerCase() }; }");if(a.connected&&a.tag===e.tag){if(!e.name)return{handle:e,how:"verified"};let c=await e.frame.session.send("Accessibility.getPartialAXTree",{backendNodeId:e.backendNodeId,fetchRelatives:!1}).catch(()=>null);if(!c)return{handle:e,how:"verified"};let d=c.nodes?.find(h=>h.backendDOMNodeId===e.backendNodeId)??c.nodes?.[0],u=s(String(d?.name?.value??""));if(!u||u===s(e.name))return{handle:e,how:"verified"}}}catch{}if(!t)throw new B("stale",`${e.ref} (${e.description}) is no longer in the page; take a new snapshot.`);let o=await Y(n,{viewportBand:1/0}),i=o.nodes.find(a=>a.nodeType===1&&se(a)===e.key);i||(await new Promise(a=>setTimeout(a,600)),o=await Y(n,{viewportBand:1/0}),i=o.nodes.find(a=>a.nodeType===1&&se(a)===e.key));let r=!!i&&e.groupSize>1&&i.groupSize!==e.groupSize;if(!i||r)throw new B("stale",r?`${e.ref} (${e.description}) was re-rendered and similar-looking elements were added or removed, so it can't be identified safely; take a new snapshot.`:`${e.ref} (${e.description}) is no longer in the page and no element with the same role/name exists; take a new snapshot.`,{key:e.key});return{handle:{...Rt(i),ref:e.ref},how:"regrounded",freshSnapshot:o}}l(Pt,"resolveHandle");function Ms(n,e,t={}){let s=l(w=>w.nodes.filter(v=>v.nodeType===1&&(v.interactive||v.scrollable)),"interactive"),o=new Map;for(let w of s(n))o.set(se(w),w);let i=new Map;for(let w of s(e))i.set(se(w),w);let r=[],a=[],c=[],d=[];for(let[w,v]of i){let T=o.get(w);if(!T){r.push(de(v));continue}if((T.value??"")!==(v.value??"")&&v.ref&&c.push({ref:v.ref,description:de(v),from:z(T.value??"",60),to:z(v.value??"",60)}),v.ref)for(let C of["checked","expanded","selected","disabled"])(T[C]??!1)!==(v[C]??!1)&&d.push(`${v.ref} ${C}: ${T[C]?"true":"false"} \u2192 ${v[C]?"true":"false"}`)}for(let[w,v]of o)i.has(w)||a.push(de(v));let u=new Set;for(let w of n.nodes)w.text&&w.text.length>3&&u.add(w.text);let h=[],p=new Set;for(let w of e.nodes)if(!(!w.text||w.text.length<=3||u.has(w.text)||p.has(w.text))&&!(w.parent&&!w.parent.visible&&!w.parent.boxless)&&(p.add(w.text),h.push(z(w.text,120)),h.length>=8))break;let f=n.url!==e.url,y={x:Math.round(e.scroll.x-n.scroll.x),y:Math.round(e.scroll.y-n.scroll.y)},b=t.dialogs??[],m=f||r.length>0||a.length>0||c.length>0||d.length>0||h.length>0||b.length>0||n.title!==e.title||y.y!==0||y.x!==0||n.focusedRef!==e.focusedRef||(t.writes?.length??0)>0;return{urlBefore:n.url,urlAfter:e.url,navigated:f,titleBefore:n.title,titleAfter:e.title,added:r.slice(0,10),removed:a.slice(0,10),addedCount:r.length,removedCount:a.length,valueChanges:c,stateChanges:d,focusedBefore:n.focusedRef,focusedAfter:e.focusedRef,scrollDelta:y,dialogs:b,network:t.network??{requests:0,failed:0},settle:t.settle??null,writes:t.writes,newText:h,changed:m}}l(Ms,"diffSnapshots");function Os(n,{shown:e,lists:t=!0}={}){let s=l(u=>/^\[((?:f\d+)?e\d+)\]/.exec(u)?.[1],"refIn"),o=t?n.added.slice(0,5).filter(u=>!(e&&s(u)&&e.includes(`[${s(u)}]`))):[],i=t?n.newText.slice(0,5).filter(u=>!(e&&e.includes(u.replace(/\s+/g," ").trim()))):[],r=t?n.removed:[],a=[];if(!n.changed)a.push("EVIDENCE: no observable change (same URL, no new/removed elements, no value/state changes, no new text).");else{if(a.push("EVIDENCE:"),n.navigated&&a.push(`- navigated: ${n.urlBefore} \u2192 ${n.urlAfter}`),n.titleBefore!==n.titleAfter&&a.push(`- title: "${z(n.titleBefore,60)}" \u2192 "${z(n.titleAfter,60)}"`),n.dialogs.length)for(let u of n.dialogs)a.push(`- ${u.type} dialog "${z(u.message,100)}" was auto-${u.handledWith}ed`);if(n.valueChanges.length)for(let u of n.valueChanges.slice(0,6))a.push(`- value ${u.ref}: "${u.from}" \u2192 "${u.to}"`);n.stateChanges.length&&a.push(`- state: ${n.stateChanges.slice(0,6).join("; ")}`),n.addedCount&&a.push(`- ${n.addedCount} new interactive element(s)${o.length?": "+o.slice(0,5).join(" ; "):""}`),n.removedCount&&a.push(`- ${n.removedCount} element(s) removed${r.length?": "+r.slice(0,3).join(" ; "):""}`),i.length&&a.push(`- new text: ${i.slice(0,5).map(u=>`"${u}"`).join(", ")}`),(n.scrollDelta.y||n.scrollDelta.x)&&a.push(`- scrolled by (${n.scrollDelta.x}, ${n.scrollDelta.y})`),n.focusedBefore!==n.focusedAfter&&a.push(`- focus: ${n.focusedBefore??"none"} \u2192 ${n.focusedAfter??"none"}`);for(let u of(n.writes??[]).slice(0,4)){let h=u.url;try{h=new URL(u.url).pathname}catch{}let p=u.failed?`FAILED (${u.failed})`:u.status!==void 0?String(u.status):"no response yet";a.push(`- server: ${u.method} ${z(h,80)} \u2192 ${p}${u.ok?"":u.failed||(u.status??0)>=400?" \u2014 the server did NOT accept this":""}${u.ms!==void 0?` (${(u.ms/1e3).toFixed(1)}s)`:""}`)}}let c=n.network.requests?`${n.network.requests} request(s)${n.network.failed?`, ${n.network.failed} failed`:""}`:"no network",d=n.settle?`${n.settle.networkIdle?"network idle":"NETWORK STILL BUSY"}, ${n.settle.mutationsQuiet?"DOM quiet":"DOM still mutating"}`:"";return a.push(`- ${c}${d?`; ${d}`:""}`),a.join(`
128
+ `).trim();if(i.length<=e)return i;let r=i.slice(0,e);return/[\uD800-\uDBFF]$/.test(r)?r.slice(0,-1):r}l(be,"pageText");var Co=new Set("a an the of in on at to for from by with into inside within under over near this that these those its it is are be and or & + - element elements area section part page panel popup modal dialog window side header footer sidebar".split(" ")),Is={button:["button","btn"],link:["link","hyperlink"],checkbox:["checkbox","check","tick"],radio:["radio"],textbox:["field","input","box","textbox","textfield"],searchbox:["search","field","input","box","searchbox"],combobox:["dropdown","select","combobox","picker","menu"],listbox:["dropdown","select","listbox","list"],tab:["tab"],option:["option","choice"],menuitem:["menu","menuitem","option"],heading:["heading","title","header"],slider:["slider","range"],switch:["switch","toggle"]},Ao=new Set(Object.values(Is).flat()),Ts=l(n=>n.toLowerCase().split(/[^\p{L}\p{N}$€£₹%]+/u).filter(Boolean),"findTokens");function As(n,e,{limit:t=20}={}){let s=e.split(/[,;|\n]+|\s+(?:or|\/)\s+/i).map(p=>p.trim()).filter(Boolean),o=n.nodes.filter(p=>p.text===void 0&&p.visible&&(p.ref||p.role==="heading")),i=new Map,r=l(p=>{let f=i.get(p);if(!f){let y=`${p.tag} ${p.role} ${p.name} ${ie(p,200)} ${Object.values(p.attrs).join(" ")}`.toLowerCase();f={tokens:Ts(y),flat:` ${Ts(y).join(" ")} `,name:p.name.trim().toLowerCase()},i.set(p,f)}return f},"hayOf"),a=new Map,c=new Map(n.nodes.map((p,f)=>[p,f])),d=l((p,f,y)=>{let b=r(f);return b.tokens.includes(p)?1:b.tokens.some(m=>p.length>=4&&m.startsWith(p)||m.length>=4&&p.startsWith(m))?.75:p.length>=3&&b.flat.includes(p)?.6:y&&(Is[f.role]??[]).includes(p)?1:0},"wordIn"),u=new Map,h=l((p,f)=>{let y=`${f?"r":""}${p}`,b=u.get(y);return b===void 0&&(b=o.reduce((m,w)=>m+(d(p,w,f)>0?1:0),0),u.set(y,b)),b},"docFreq");for(let p of s){let f=Ts(p),y=f.filter(M=>!Co.has(M)&&!Ao.has(M)),b=!y.length;if(b&&(y=f.filter(M=>!Co.has(M))),y.length||(y=f),!y.length)continue;let m=f.filter(M=>Ao.has(M)),w=y.map(M=>{let _=h(M,b);return _?Math.log(1+o.length/_):0}),v=w.reduce((M,_)=>M+_,0);if(!v)continue;let T=[];for(let M of o){let _=r(M),x=y.map($=>d($,M,b));if(!x.some($=>$>0))continue;let g=x.every($=>$>=1),S=g?1:x.reduce(($,I,R)=>$+I*w[R],0)/v,E=0;for(let $=0;$<y.length;$++)for(let I=y.length;I>$+E;I--)if(_.flat.includes(` ${y.slice($,I).join(" ")} `)){E=I-$;break}let A=S+(y.length>1?.5*E/y.length:0);_.name&&_.name===p.trim().toLowerCase()&&(A+=1),m.length&&(Is[M.role]??[]).some($=>m.includes($))&&(A+=.25),A-=Math.min(.2,_.tokens.length/500);let k=x.filter($=>$>0).length/y.length;T.push({n:M,cover:g?1:Math.min(S,.99),score:A,run:E,raw:k})}let C=T.filter(M=>M.cover>=1),D=C.length?C:T.filter(M=>M.raw>=.5&&(M.cover>=.6||M.run>=2&&M.cover>=.4)).sort((M,_)=>_.score-M.score).slice(0,8);for(let M of D){let _=a.get(M.n),x=M.cover>=1;(!_||M.score>_.score)&&a.set(M.n,{score:M.score,exact:x||!!_?.exact,order:c.get(M.n)??0})}}return[...a.entries()].sort((p,f)=>Number(f[1].exact)-Number(p[1].exact)||f[1].score-p[1].score||p[1].order-f[1].order).slice(0,t).map(([p,f])=>({node:p,exact:f.exact}))}l(As,"findScored");function de(n){let e=n.ref?`[${n.ref}]`:"",t=Mt(n,80),s=Po(n,t);return`${e}<${n.tag}${s}${t?`>${t}</${n.tag}>`:" />"}`}l(de,"describeNode");function Rt(n){return{ref:n.ref??"",backendNodeId:n.backendNodeId,frame:n.frame,frameId:n.frameId,tag:n.tag,role:n.role,name:n.name,nth:n.nth,key:se(n),groupSize:n.groupSize,identity:n.identity,description:de(n)}}l(Rt,"handleFor");async function Pt(n,e,{allowReground:t=!0}={}){if(e.frame.session.closed)throw new B("frame_detached",`The frame containing ${e.ref} was detached; take a new snapshot.`);let s=l(a=>a.replace(/\s+/g," ").trim().slice(0,80),"norm");try{let a=await e.frame.callOnNode(e.backendNodeId,"function(){ return { connected: this.isConnected === true, tag: (this.localName || '').toLowerCase() }; }");if(a.connected&&a.tag===e.tag){if(!e.name)return{handle:e,how:"verified"};let c=await e.frame.session.send("Accessibility.getPartialAXTree",{backendNodeId:e.backendNodeId,fetchRelatives:!1}).catch(()=>null);if(!c)return{handle:e,how:"verified"};let d=c.nodes?.find(h=>h.backendDOMNodeId===e.backendNodeId)??c.nodes?.[0],u=s(String(d?.name?.value??""));if(!u||u===s(e.name))return{handle:e,how:"verified"}}}catch{}if(!t)throw new B("stale",`${e.ref} (${e.description}) is no longer in the page; take a new snapshot.`);let o=await Y(n,{viewportBand:1/0}),i=o.nodes.find(a=>a.nodeType===1&&se(a)===e.key);i||(await new Promise(a=>setTimeout(a,600)),o=await Y(n,{viewportBand:1/0}),i=o.nodes.find(a=>a.nodeType===1&&se(a)===e.key));let r=!!i&&e.groupSize>1&&i.groupSize!==e.groupSize;if(!i||r)throw new B("stale",r?`${e.ref} (${e.description}) was re-rendered and similar-looking elements were added or removed, so it can't be identified safely; take a new snapshot.`:`${e.ref} (${e.description}) is no longer in the page and no element with the same role/name exists; take a new snapshot.`,{key:e.key});return{handle:{...Rt(i),ref:e.ref},how:"regrounded",freshSnapshot:o}}l(Pt,"resolveHandle");function Ms(n,e,t={}){let s=l(w=>w.nodes.filter(v=>v.nodeType===1&&(v.interactive||v.scrollable)),"interactive"),o=new Map;for(let w of s(n))o.set(se(w),w);let i=new Map;for(let w of s(e))i.set(se(w),w);let r=[],a=[],c=[],d=[];for(let[w,v]of i){let T=o.get(w);if(!T){r.push(de(v));continue}if((T.value??"")!==(v.value??"")&&v.ref&&c.push({ref:v.ref,description:de(v),from:z(T.value??"",60),to:z(v.value??"",60)}),v.ref)for(let C of["checked","expanded","selected","disabled"])(T[C]??!1)!==(v[C]??!1)&&d.push(`${v.ref} ${C}: ${T[C]?"true":"false"} \u2192 ${v[C]?"true":"false"}`)}for(let[w,v]of o)i.has(w)||a.push(de(v));let u=new Set;for(let w of n.nodes)w.text&&w.text.length>3&&u.add(w.text);let h=[],p=new Set;for(let w of e.nodes)if(!(!w.text||w.text.length<=3||u.has(w.text)||p.has(w.text))&&!(w.parent&&!w.parent.visible&&!w.parent.boxless)&&(p.add(w.text),h.push(z(w.text,120)),h.length>=8))break;let f=n.url!==e.url,y={x:Math.round(e.scroll.x-n.scroll.x),y:Math.round(e.scroll.y-n.scroll.y)},b=t.dialogs??[],m=f||r.length>0||a.length>0||c.length>0||d.length>0||h.length>0||b.length>0||n.title!==e.title||y.y!==0||y.x!==0||n.focusedRef!==e.focusedRef||(t.writes?.length??0)>0;return{urlBefore:n.url,urlAfter:e.url,navigated:f,titleBefore:n.title,titleAfter:e.title,added:r.slice(0,10),removed:a.slice(0,10),addedCount:r.length,removedCount:a.length,valueChanges:c,stateChanges:d,focusedBefore:n.focusedRef,focusedAfter:e.focusedRef,scrollDelta:y,dialogs:b,network:t.network??{requests:0,failed:0},settle:t.settle??null,writes:t.writes,newText:h,changed:m}}l(Ms,"diffSnapshots");function Os(n,{shown:e,lists:t=!0}={}){let s=l(u=>/^\[((?:f\d+)?e\d+)\]/.exec(u)?.[1],"refIn"),o=t?n.added.slice(0,5).filter(u=>!(e&&s(u)&&e.includes(`[${s(u)}]`))):[],i=t?n.newText.slice(0,5).filter(u=>!(e&&e.includes(u.replace(/\s+/g," ").trim()))):[],r=t?n.removed:[],a=[];if(!n.changed)a.push("EVIDENCE: no observable change (same URL, no new/removed elements, no value/state changes, no new text).");else{if(a.push("EVIDENCE:"),n.navigated&&a.push(`- navigated: ${n.urlBefore} \u2192 ${n.urlAfter}`),n.titleBefore!==n.titleAfter&&a.push(`- title: "${z(n.titleBefore,60)}" \u2192 "${z(n.titleAfter,60)}"`),n.dialogs.length)for(let h of n.dialogs)a.push(`- ${h.type} dialog "${z(h.message,100)}" was auto-${h.handledWith}ed`);if(n.valueChanges.length)for(let h of n.valueChanges.slice(0,6))a.push(`- value ${h.ref}: "${h.from}" \u2192 "${h.to}"`);n.stateChanges.length&&a.push(`- state: ${n.stateChanges.slice(0,6).join("; ")}`),n.addedCount&&a.push(`- ${n.addedCount} new interactive element(s)${o.length?": "+o.slice(0,5).join(" ; "):""}`),n.removedCount&&a.push(`- ${n.removedCount} element(s) removed${r.length?": "+r.slice(0,3).join(" ; "):""}`),i.length&&a.push(`- new text: ${i.slice(0,5).map(h=>`"${h}"`).join(", ")}`),(n.scrollDelta.y||n.scrollDelta.x)&&a.push(`- scrolled by (${n.scrollDelta.x}, ${n.scrollDelta.y})`),n.focusedBefore!==n.focusedAfter&&a.push(`- focus: ${n.focusedBefore??"none"} \u2192 ${n.focusedAfter??"none"}`);let u=new Map;for(let h of n.writes??[]){let p=h.url;try{p=new URL(h.url).pathname}catch{}let f=h.failed?`FAILED (${h.failed})`:h.status!==void 0?String(h.status):"no response yet",y=`${h.method} ${p} ${f}`,b=u.get(y);b?b.n++:u.set(y,{line:`- server: ${h.method} ${z(p,80)} \u2192 ${f}${h.ok?"":h.failed||(h.status??0)>=400?" \u2014 the server did NOT accept this":""}${h.ms!==void 0?` (${(h.ms/1e3).toFixed(1)}s)`:""}`,n:1})}for(let{line:h,n:p}of[...u.values()].slice(0,4))a.push(p>1?`${h} \xD7${p}`:h)}let c=n.network.requests?`${n.network.requests} request(s)${n.network.failed?`, ${n.network.failed} failed`:""}`:"no network",d=n.settle?`${n.settle.networkIdle?"network idle":"NETWORK STILL BUSY"}, ${n.settle.mutationsQuiet?"DOM quiet":"DOM still mutating"}`:"";return a.push(`- ${c}${d?`; ${d}`:""}`),a.join(`
129
129
  `)}l(Os,"formatEvidence");var Nt=l(n=>n.replace(/^(\t*)\*/,"$1"),"key"),Do=l(n=>/^\t*/.exec(n)[0].length,"depth");function ht(n,e,t={}){let s=n.split(`
130
130
  `),o=e.split(`
131
131
  `),i=new Map;for(let w of s)i.set(Nt(w),(i.get(Nt(w))??0)+1);let r=o.map(w=>{let v=Nt(w),T=i.get(v)??0;return T>0?(i.set(v,T-1),!1):!0}),a=[];for(let w of s){let v=Nt(w),T=i.get(v)??0;T>0&&(a.push(w),i.set(v,T-1))}if(!r.some(Boolean)&&!a.length)return null;let c=[],d=new Set;for(let w=0;w<o.length;w++){if(!r[w])continue;let v=Do(o[w]);if(v>0){for(let T=w-1;T>=0;T--)if(Do(o[T])<v){!r[T]&&!d.has(T)&&(c.push(`~ ${o[T].trim()}`),d.add(T));break}}c.push(o[w])}let u=l(w=>/\[((?:f\d+)?e\d+)\]/.exec(w)?.[1],"refOf"),h=new Set(o.map(u).filter(Boolean)),p=l(w=>!!w&&(t.liveRefs?t.liveRefs.has(w):!1),"stillLive"),f=a.filter(w=>u(w)&&!h.has(u(w))&&!p(u(w))).map(w=>/\[((?:f\d+)?e\d+)\]<\w+[^>]*>?([^<]{0,40})/.exec(w)).filter(w=>!!w),y=o.filter((w,v)=>r[v]&&!u(w)).length,b=t.truncated?0:Math.max(0,a.filter(w=>!u(w)).length-y);if(f.length||b){let w=f.map(v=>`[${v[1]}]${v[2]?.trim()?` ${v[2].trim()}`:""}`);c.push(`GONE from the page: ${w.join("; ")}${b?`${w.length?"; ":""}${b} text line(s)`:""}`)}let m=c.join(`
@@ -411,7 +411,7 @@ return __pfClassify("Accept all") === "accept" && __pfClassify("Reject all") ===
411
411
  return click.call(this);
412
412
  };
413
413
  })();
414
- ${ns(mr(wr,"autoconsent.playwright.js"),"utf8")}`,$u=3,Tu=2500,Iu=6500,Eu=6e3,Cu=3e3,Au=1500,Mu=3e3,Ou=4e3;function Ru(n,e){if(n.doneAt)return"opted_out";if(n.optOut===!1)return"failed";if(n.optOut===!0)return e-n.optOutAt>Cu?"opted_out":"pending";if(n.popupAt)return"pending";if(n.detectedAt)return e-n.detectedAt<Iu?"pending":"no_cmp";let t=n.topLifecycle!=="nothingDetected",s=l((o,i)=>e-o>=Tu&&i!==void 0&&n.topAttempts>=i+$u,"quiet");return n.cmpRequestAt&&e-n.cmpRequestAt<Eu&&t&&!s(n.cmpRequestAt,n.roundAtCmpRequest)||!n.topInitAt&&/^https?:/.test(n.url)&&e-n.navAt<Au||n.topInitAt&&n.topAttempts<2&&e-n.topInitAt<Mu||n.patternsAt&&e-n.patternsAt<Ou&&t&&!s(n.patternsAt,n.roundAtPatterns)?"pending":"no_cmp"}l(Ru,"outcomeOf");var ss=class{static{l(this,"ConsentEngine")}opts;emitter=new wu;pages=new WeakMap;disposers=new Set;armed=new WeakSet;retried=new WeakSet;retryTimers=new Set;disposed=!1;config;constructor(e={}){if(this.opts=e,this.config=xu(e),this.config.autoAction!=="optOut"||!["off","reject"].includes(this.config.heuristicMode))throw new Error("ConsentEngine only ever opts out")}on(e,t){return this.emitter.on(e,t),()=>this.emitter.off(e,t)}consentStatus(e){let t=this.state(e),s=Date.now(),o=Ru(t,s),i=o==="opted_out"?t.doneAt??t.optOutAt:s;return{cmp:t.cmp,outcome:o,ms:Math.max(0,i-t.navAt),url:t.url,...t.cosmetic!==void 0?{cosmetic:t.cosmetic}:{},...t.selfTest!==void 0?{selfTest:t.selfTest}:{},refusedClicks:t.refused,frames:t.frames.size}}async waitForConsent(e,t=1e4){let s=Date.now()+t;for(;;){let o=this.consentStatus(e);if(o.outcome!=="pending"||Date.now()>=s||e.closed)return o;await new Promise(i=>setTimeout(i,Math.min(100,Math.max(1,s-Date.now()))))}}dispose(){this.disposed=!0;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear();for(let e of this.disposers)e();this.disposers.clear()}initSession=l(async e=>{let t=e.session,s=e.page;if(!e.isMain&&ke(e.url)||this.armed.has(t))return;this.armed.add(t);let o=new Map,i=[()=>this.armed.delete(t)],r;try{[,r]=await Promise.all([t.send("Runtime.addBinding",{name:Je,executionContextName:gn},{timeoutMs:5e3}),t.send("Page.addScriptToEvaluateOnNewDocument",{source:Su,worldName:gn,runImmediately:!0},{timeoutMs:5e3})])}catch(p){if(this.armed.delete(t),e.isMain&&!this.retried.has(t)&&!this.disposed){this.retried.add(t);let f=setTimeout(()=>{this.retryTimers.delete(f),this.disposed||this.initSession(e).catch(()=>{})},2e3);f.unref?.(),this.retryTimers.add(f)}throw p}let a=l(()=>{for(let p of i)p();t.send("Page.removeScriptToEvaluateOnNewDocument",{identifier:r.identifier}).catch(()=>{}),t.send("Runtime.removeBinding",{name:Je}).catch(()=>{})},"dispose");this.disposers.add(a),i.push(()=>this.disposers.delete(a));let c=l(async(p,f,y)=>{if(!/^https?:/.test(f)||!y&&ke(f))return;let{executionContextId:b}=await t.send("Page.createIsolatedWorld",{frameId:p,worldName:gn,grantUniveralAccess:!1},{timeoutMs:5e3});o.set(b,{frameId:p,mainFrame:y}),await t.send("Runtime.addBinding",{name:Je,executionContextId:b},{timeoutMs:5e3}),await t.send("Runtime.evaluate",{contextId:b,expression:"globalThis.__pfAcFlush && __pfAcFlush()",returnByValue:!0},{timeoutMs:5e3})},"arm"),d=l((p,f,y)=>{c(p,f,y).catch(b=>{/not found|Cannot find|No frame|detached|closed|destroyed|navigated/i.test(String(b))||this.emit("error",{page:s,frameId:p,url:f,error:`arm: ${String(b)}`})})},"armSafe");i.push(t.on("Page.frameNavigated",p=>{let f=e.isMain&&!p.frame.parentId;f&&this.reset(s,p.frame.url),d(p.frame.id,p.frame.url,f)}),t.on("Runtime.bindingCalled",p=>{if(p.name!==Je)return;let f=o.get(p.executionContextId);f&&this.onMessage(t,s,p.executionContextId,f,p.payload).catch(()=>{})}),t.on("Network.requestWillBeSent",p=>{if(!Qi(p.request.url))return;let f=this.state(s);f.cmpRequestAt===void 0&&(f.cmpRequestAt=Date.now(),f.roundAtCmpRequest=f.topAttempts)}));let{frameTree:u}=await t.send("Page.getFrameTree"),h=l((p,f)=>{d(p.frame.id,p.frame.url,f);for(let y of p.childFrames??[])h(y,!1)},"walk");h(u,e.isMain)},"initSession");async onMessage(e,t,s,o,i){let r;try{r=JSON.parse(i)}catch{return}let a=this.state(t),c=typeof r.url=="string"?r.url:"",d={page:t,frameId:o.frameId,url:c},u=typeof r.cmp=="string"?r.cmp:"";switch(r.type){case"init":{a.frames.add(o.frameId),o.mainFrame&&(a.topInitAt??=Date.now());let h={autoconsent:[],compact:ku(yr,{url:c,mainFrame:o.mainFrame})};await this.reply(e,s,{type:"initResp",config:this.config,rules:h});return}case"eval":await this.reply(e,s,{type:"evalResp",id:r.id,result:await this.runSnippet(e,t,s,o,r.snippetId)});return;case"cmpDetected":a.cmp??=u,a.detectedAt??=Date.now(),this.emit("cmpDetected",{...d,cmp:u});return;case"popupFound":a.cmp=u,a.popupAt??=Date.now(),this.emit("popupFound",{...d,cmp:u});return;case"optOutResult":a.cmp=u||a.cmp,a.optOut=r.result===!0,a.optOutAt=Date.now(),r.result===!0&&r.scheduleSelfTest===!0&&(a.selfTestTarget={s:e,contextId:s}),this.emit("optOutResult",{...d,cmp:u,result:r.result===!0});return;case"autoconsentDone":{a.cmp=u||a.cmp,a.doneAt=Date.now(),a.cosmetic=r.isCosmetic===!0,this.emit("autoconsentDone",{...d,cmp:u,cosmetic:a.cosmetic,durationMs:Number(r.duration)||0,clicks:Number(r.totalClicks)||0});let h=a.selfTestTarget;a.selfTestTarget=void 0,this.opts.selfTest!==!1&&h&&await this.reply(h.s,h.contextId,{type:"selfTest"});return}case"selfTestResult":a.selfTest=r.result===!0,this.emit("selfTestResult",{...d,cmp:u,result:a.selfTest});return;case"optInResult":this.emit("error",{...d,error:"unexpected optInResult",details:r});return;case"autoconsentError":this.emit("error",{...d,error:"autoconsent",details:r.details});return;case"pfRefusedClick":a.refused++,this.emit("error",{...d,error:`refused to click an accept button: "${String(r.text)}"`});return;case"report":{let h=r.state??{};if(!o.mainFrame||r.mainFrame!==!0)return;a.topLifecycle=h.lifecycle,a.topAttempts=Math.max(a.topAttempts,Number(h.findCmpAttempts)||0),h.heuristicPatterns?.length&&a.patternsAt===void 0&&(a.patternsAt=Date.now(),a.roundAtPatterns=a.topAttempts);return}default:return}}reply(e,t,s){return e.send("Runtime.evaluate",{contextId:t,expression:`autoconsentReceiveMessage(${JSON.stringify(s)})`,returnByValue:!0}).catch(()=>{})}async runSnippet(e,t,s,o,i){let r=typeof i=="string"?gr[i]:void 0;if(!r||vu.has(i))return this.emit("error",{page:t,frameId:o.frameId,error:`refused eval snippet ${String(i)}`}),!1;let a=await e.send("Runtime.evaluate",{contextId:s,expression:"document",returnByValue:!1});if(!a.result.objectId)return!1;try{let{node:c}=await e.send("DOM.describeNode",{objectId:a.result.objectId}),{object:d}=await e.send("DOM.resolveNode",{backendNodeId:c.backendNodeId});if(!d.objectId)return!1;try{return(await e.send("Runtime.callFunctionOn",{objectId:d.objectId,functionDeclaration:`async function () { try { return !!(await (${r.toString()}).call(window)); } catch (e) { return false; } }`,returnByValue:!0,awaitPromise:!0})).result.value===!0}finally{e.send("Runtime.releaseObject",{objectId:d.objectId}).catch(()=>{})}}catch{return!1}finally{e.send("Runtime.releaseObject",{objectId:a.result.objectId}).catch(()=>{})}}state(e){let t=this.pages.get(e);return t||(t={navAt:Date.now(),url:e.url,cmp:null,refused:0,frames:new Set,topAttempts:0},this.pages.set(e,t)),t}reset(e,t){this.pages.set(e,{navAt:Date.now(),url:t,cmp:null,refused:0,frames:new Set,topAttempts:0})}emit(e,t){e==="error"&&this.emitter.listenerCount("error")===0||this.emitter.emit(e,t)}};var Pu=["cmpDetected","popupFound","optOutResult","autoconsentDone","selfTestResult","error"],Nu=["blocked","error"];async function yn(n,e={}){let t=e.consent===!1?null:new ss(typeof e.consent=="object"?e.consent:{}),s=e.adblock===!1?null:await ts.create(typeof e.adblock=="object"?e.adblock:{}),o=[];if(e.onEvent){let r=e.onEvent;if(t)for(let a of Pu)o.push(t.on(a,(c=>r({source:"consent",type:a,data:c}))));if(s)for(let a of Nu)o.push(s.on(a,(c=>r({source:"adblock",type:a,data:c}))))}let i=l(async r=>{await Promise.all([t?.initSession(r),s?.initSession(r)])},"init");return o.push(n.addSessionInitializer(i)),{consent:t,adblock:s,detach(){for(let r of o)r();t?.dispose(),s?.dispose()}}}l(yn,"attachInterrupts");var Du="pilotfish's open MCP makes no model calls: the MCP client's own model reads the page and decides the next step",Lu=l(()=>{let n=l(async()=>{throw new Error(Du)},"refuse");return{messages:{create:n},beta:{messages:{create:n}}}},"noModelClient"),bn=class{static{l(this,"ConfirmThrough")}inner;canAsk;constructor(e,t){this.inner=e,this.canAsk=t}async check(e){let t=await this.inner.check(e);return t.kind!=="confirm"||this.canAsk()?t:{kind:"deny",reason:`${t.reason}. This needs a person's confirmation, and this MCP client cannot ask for one (no elicitation support)`}}},Xe=class{static{l(this,"BrowserSession")}config;opts;browser=null;launching=null;interrupts=null;tabs=null;agent=null;queue=Promise.resolve();policy;asker;constructor(e,t={}){this.config=e,this.opts=t,this.policy=new Pe({allowedHosts:e.allowedHosts,allowPrivateNetwork:e.allowPrivateNetwork})}get launched(){return!!this.browser&&!this.browser.closed}async page(){return await this.ensure(),this.tabs.current}get tabTable(){return this.tabs}async ensure(){return this.browser&&!this.browser.closed?this.browser:(this.launching??=this.start().finally(()=>{this.launching=null}),this.launching)}async start(){let e=await ks({...this.opts.launch,headless:this.config.headless});this.interrupts=await yn(e,{consent:!0,adblock:!0}).catch(()=>null);let t=e.allPages()[0]??await e.newPage();return this.tabs=new Ne(t),this.browser=e,e.on("disconnected",()=>{this.browser===e&&this.reset()}),e}reset(){this.agent?.dispose(),this.agent=null,this.tabs?.dispose(),this.tabs=null,this.interrupts?.detach(),this.interrupts=null,this.browser=null}executor(){return this.agent??=new wt(this.tabs.current,{tabs:this.tabs,client:Lu(),secrets:this.config.secrets,policy:new bn(this.policy,()=>!!this.asker),consent:this.interrupts?.consent??void 0,allowScreenshots:this.config.allowScreenshots,askUser:l(e=>this.asker?.(e)??Promise.resolve(null),"askUser"),fastSettle:!0,enableQuery:!0,compactSnapshots:!0,autoDismiss:!0,awaitLoading:!0,actionSnapshotBand:0,snapshotMoreHint:"browser_scroll for the next screen, browser_get_text for the page's text, or browser_snapshot (whole_page) for every element"}),this.agent}async act(e,t,s={}){let o=this.queue.then(async()=>(await this.ensure(),this.executor().act(e,t,"",s)));return this.queue=o.catch(()=>{}),o}async obstacle(e={}){if(!this.launched)return null;let t=this.queue.then(()=>this.executor().obstacle(e));return this.queue=t.catch(()=>{}),t.catch(()=>null)}async close(){let e=this.browser??(this.launching?await this.launching.catch(()=>null):null);return e?(this.reset(),await e.close().catch(()=>{}),!0):!1}};import{McpServer as Fu}from"@modelcontextprotocol/sdk/server/mcp.js";import{ListToolsRequestSchema as Hu}from"@modelcontextprotocol/sdk/types.js";import{z as q}from"zod";var os="0.1.21";var is=Oe.click.shape.ref.describe('From the latest snapshot, e.g. "e12" or "f1e3"'),br=q.enum(["down","up","left","right"]),Uu={click:["ref"],type:["ref","text","submit"],select:["ref","values"],press:["key"],scroll:["direction"],wait:["seconds"]},ju={click:1,type:2,select:2,press:1,scroll:1,wait:1},Bu=q.object({action:q.enum(["click","type","select","press","scroll","wait"]).describe("click, select, type take ref; type: text (submit: Enter after); select: values; press: key; scroll: direction; wait: seconds"),ref:is.optional(),text:q.string().max(2e4).optional(),submit:q.boolean().optional(),values:q.array(q.string()).min(1).max(50).optional(),key:q.string().min(1).max(40).optional(),direction:br.optional(),seconds:q.number().min(.5).max(10).optional()}).strict().superRefine((n,e)=>{let t=Uu[n.action];for(let s of t.slice(0,ju[n.action]))n[s]===void 0&&e.addIssue({code:"custom",path:[s],message:`${n.action} needs ${s}`});for(let s of Object.keys(n))s!=="action"&&!t.includes(s)&&e.addIssue({code:"custom",path:[s],message:`${s} is not a field of ${n.action} (it takes ${t.join(", ")})`})}),re={browser_navigate:q.object({url:q.url({protocol:/^https?$/}).describe("Absolute http(s) URL"),snapshot:q.boolean().optional().describe("Default true. false: no page snapshot, only what happened (title, counts). Only when this same reply also reads the page with browser_query and you will not act on it; keep it for a page you have not seen or whose tabs, sorts, filters or forms you may use.")}).strict(),browser_snapshot:q.object({whole_page:q.boolean().optional()}).strict(),browser_click:q.object({ref:is}).strict(),browser_type:q.object({ref:is,text:q.string().max(2e4),submit:q.boolean().optional().describe("Press Enter afterwards")}).strict(),browser_select:q.object({ref:is,values:q.array(q.string()).min(1).max(50)}).strict(),browser_press:q.object({key:q.string().min(1).max(40).describe('e.g. "Enter", "Escape", "Tab", "ArrowDown", "Control+a"')}).strict(),browser_scroll:q.object({direction:br}).strict(),browser_screenshot:q.object({}).strict(),browser_get_text:q.object({max_chars:q.number().int().min(500).max(6e4).optional().describe("Default 20000. Ask for less when the start of the page is enough."),selector:q.string().min(1).max(300).optional().describe(`CSS selector: only the first match's text, e.g. "main" or "#results"`)}).strict(),browser_query:q.object({expression:q.string().min(1).max(4e3).describe("e.g. [...document.querySelectorAll('.result')].slice(0,10).map(e => e.innerText)")}).strict(),browser_find:q.object({query:q.string().min(1).max(300).describe('Words naming the element(s), e.g. "Sort by" or "price max input, Go button"')}).strict(),browser_wait:q.object({seconds:q.number().min(.5).max(10)}).strict(),browser_resume:q.object({timeout_s:q.number().int().min(5).max(900).optional().describe("Default 300")}).strict(),browser_actions:q.object({actions:q.array(Bu).min(1).max(10)}).strict(),browser_tabs:q.object({switch_to:q.string().min(1).max(10).optional().describe('Tab id to work in from now on, e.g. "t2"')}).strict(),browser_close:q.object({}).strict()};function Te(n,e=!1){return{content:[{type:"text",text:n}],...e?{isError:!0}:{}}}l(Te,"text");function qu(n){let e=Object.keys(n.secrets),t=[e.length?`Secrets are typed as placeholders and never shown: ${e.map(s=>`{{${s}}}`).join(", ")}.`:"",n.allowedHosts.length?`Navigation is limited to: ${n.allowedHosts.join(", ")}.`:""].filter(Boolean);return t.length?t.join(`
414
+ ${ns(mr(wr,"autoconsent.playwright.js"),"utf8")}`,$u=3,Tu=2500,Iu=6500,Eu=6e3,Cu=3e3,Au=1500,Mu=3e3,Ou=4e3;function Ru(n,e){if(n.doneAt)return"opted_out";if(n.optOut===!1)return"failed";if(n.optOut===!0)return e-n.optOutAt>Cu?"opted_out":"pending";if(n.popupAt)return"pending";if(n.detectedAt)return e-n.detectedAt<Iu?"pending":"no_cmp";let t=n.topLifecycle!=="nothingDetected",s=l((o,i)=>e-o>=Tu&&i!==void 0&&n.topAttempts>=i+$u,"quiet");return n.cmpRequestAt&&e-n.cmpRequestAt<Eu&&t&&!s(n.cmpRequestAt,n.roundAtCmpRequest)||!n.topInitAt&&/^https?:/.test(n.url)&&e-n.navAt<Au||n.topInitAt&&n.topAttempts<2&&e-n.topInitAt<Mu||n.patternsAt&&e-n.patternsAt<Ou&&t&&!s(n.patternsAt,n.roundAtPatterns)?"pending":"no_cmp"}l(Ru,"outcomeOf");var ss=class{static{l(this,"ConsentEngine")}opts;emitter=new wu;pages=new WeakMap;disposers=new Set;armed=new WeakSet;retried=new WeakSet;retryTimers=new Set;disposed=!1;config;constructor(e={}){if(this.opts=e,this.config=xu(e),this.config.autoAction!=="optOut"||!["off","reject"].includes(this.config.heuristicMode))throw new Error("ConsentEngine only ever opts out")}on(e,t){return this.emitter.on(e,t),()=>this.emitter.off(e,t)}consentStatus(e){let t=this.state(e),s=Date.now(),o=Ru(t,s),i=o==="opted_out"?t.doneAt??t.optOutAt:s;return{cmp:t.cmp,outcome:o,ms:Math.max(0,i-t.navAt),url:t.url,...t.cosmetic!==void 0?{cosmetic:t.cosmetic}:{},...t.selfTest!==void 0?{selfTest:t.selfTest}:{},refusedClicks:t.refused,frames:t.frames.size}}async waitForConsent(e,t=1e4){let s=Date.now()+t;for(;;){let o=this.consentStatus(e);if(o.outcome!=="pending"||Date.now()>=s||e.closed)return o;await new Promise(i=>setTimeout(i,Math.min(100,Math.max(1,s-Date.now()))))}}dispose(){this.disposed=!0;for(let e of this.retryTimers)clearTimeout(e);this.retryTimers.clear();for(let e of this.disposers)e();this.disposers.clear()}initSession=l(async e=>{let t=e.session,s=e.page;if(!e.isMain&&ke(e.url)||this.armed.has(t))return;this.armed.add(t);let o=new Map,i=[()=>this.armed.delete(t)],r;try{[,r]=await Promise.all([t.send("Runtime.addBinding",{name:Je,executionContextName:gn},{timeoutMs:5e3}),t.send("Page.addScriptToEvaluateOnNewDocument",{source:Su,worldName:gn,runImmediately:!0},{timeoutMs:5e3})])}catch(p){if(this.armed.delete(t),e.isMain&&!this.retried.has(t)&&!this.disposed){this.retried.add(t);let f=setTimeout(()=>{this.retryTimers.delete(f),this.disposed||this.initSession(e).catch(()=>{})},2e3);f.unref?.(),this.retryTimers.add(f)}throw p}let a=l(()=>{for(let p of i)p();t.send("Page.removeScriptToEvaluateOnNewDocument",{identifier:r.identifier}).catch(()=>{}),t.send("Runtime.removeBinding",{name:Je}).catch(()=>{})},"dispose");this.disposers.add(a),i.push(()=>this.disposers.delete(a));let c=l(async(p,f,y)=>{if(!/^https?:/.test(f)||!y&&ke(f))return;let{executionContextId:b}=await t.send("Page.createIsolatedWorld",{frameId:p,worldName:gn,grantUniveralAccess:!1},{timeoutMs:5e3});o.set(b,{frameId:p,mainFrame:y}),await t.send("Runtime.addBinding",{name:Je,executionContextId:b},{timeoutMs:5e3}),await t.send("Runtime.evaluate",{contextId:b,expression:"globalThis.__pfAcFlush && __pfAcFlush()",returnByValue:!0},{timeoutMs:5e3})},"arm"),d=l((p,f,y)=>{c(p,f,y).catch(b=>{/not found|Cannot find|No frame|detached|closed|destroyed|navigated/i.test(String(b))||this.emit("error",{page:s,frameId:p,url:f,error:`arm: ${String(b)}`})})},"armSafe");i.push(t.on("Page.frameNavigated",p=>{let f=e.isMain&&!p.frame.parentId;f&&this.reset(s,p.frame.url),d(p.frame.id,p.frame.url,f)}),t.on("Runtime.bindingCalled",p=>{if(p.name!==Je)return;let f=o.get(p.executionContextId);f&&this.onMessage(t,s,p.executionContextId,f,p.payload).catch(()=>{})}),t.on("Network.requestWillBeSent",p=>{if(!Qi(p.request.url))return;let f=this.state(s);f.cmpRequestAt===void 0&&(f.cmpRequestAt=Date.now(),f.roundAtCmpRequest=f.topAttempts)}));let{frameTree:u}=await t.send("Page.getFrameTree"),h=l((p,f)=>{d(p.frame.id,p.frame.url,f);for(let y of p.childFrames??[])h(y,!1)},"walk");h(u,e.isMain)},"initSession");async onMessage(e,t,s,o,i){let r;try{r=JSON.parse(i)}catch{return}let a=this.state(t),c=typeof r.url=="string"?r.url:"",d={page:t,frameId:o.frameId,url:c},u=typeof r.cmp=="string"?r.cmp:"";switch(r.type){case"init":{a.frames.add(o.frameId),o.mainFrame&&(a.topInitAt??=Date.now());let h={autoconsent:[],compact:ku(yr,{url:c,mainFrame:o.mainFrame})};await this.reply(e,s,{type:"initResp",config:this.config,rules:h});return}case"eval":await this.reply(e,s,{type:"evalResp",id:r.id,result:await this.runSnippet(e,t,s,o,r.snippetId)});return;case"cmpDetected":a.cmp??=u,a.detectedAt??=Date.now(),this.emit("cmpDetected",{...d,cmp:u});return;case"popupFound":a.cmp=u,a.popupAt??=Date.now(),this.emit("popupFound",{...d,cmp:u});return;case"optOutResult":a.cmp=u||a.cmp,a.optOut=r.result===!0,a.optOutAt=Date.now(),r.result===!0&&r.scheduleSelfTest===!0&&(a.selfTestTarget={s:e,contextId:s}),this.emit("optOutResult",{...d,cmp:u,result:r.result===!0});return;case"autoconsentDone":{a.cmp=u||a.cmp,a.doneAt=Date.now(),a.cosmetic=r.isCosmetic===!0,this.emit("autoconsentDone",{...d,cmp:u,cosmetic:a.cosmetic,durationMs:Number(r.duration)||0,clicks:Number(r.totalClicks)||0});let h=a.selfTestTarget;a.selfTestTarget=void 0,this.opts.selfTest!==!1&&h&&await this.reply(h.s,h.contextId,{type:"selfTest"});return}case"selfTestResult":a.selfTest=r.result===!0,this.emit("selfTestResult",{...d,cmp:u,result:a.selfTest});return;case"optInResult":this.emit("error",{...d,error:"unexpected optInResult",details:r});return;case"autoconsentError":this.emit("error",{...d,error:"autoconsent",details:r.details});return;case"pfRefusedClick":a.refused++,this.emit("error",{...d,error:`refused to click an accept button: "${String(r.text)}"`});return;case"report":{let h=r.state??{};if(!o.mainFrame||r.mainFrame!==!0)return;a.topLifecycle=h.lifecycle,a.topAttempts=Math.max(a.topAttempts,Number(h.findCmpAttempts)||0),h.heuristicPatterns?.length&&a.patternsAt===void 0&&(a.patternsAt=Date.now(),a.roundAtPatterns=a.topAttempts);return}default:return}}reply(e,t,s){return e.send("Runtime.evaluate",{contextId:t,expression:`autoconsentReceiveMessage(${JSON.stringify(s)})`,returnByValue:!0}).catch(()=>{})}async runSnippet(e,t,s,o,i){let r=typeof i=="string"?gr[i]:void 0;if(!r||vu.has(i))return this.emit("error",{page:t,frameId:o.frameId,error:`refused eval snippet ${String(i)}`}),!1;let a=await e.send("Runtime.evaluate",{contextId:s,expression:"document",returnByValue:!1});if(!a.result.objectId)return!1;try{let{node:c}=await e.send("DOM.describeNode",{objectId:a.result.objectId}),{object:d}=await e.send("DOM.resolveNode",{backendNodeId:c.backendNodeId});if(!d.objectId)return!1;try{return(await e.send("Runtime.callFunctionOn",{objectId:d.objectId,functionDeclaration:`async function () { try { return !!(await (${r.toString()}).call(window)); } catch (e) { return false; } }`,returnByValue:!0,awaitPromise:!0})).result.value===!0}finally{e.send("Runtime.releaseObject",{objectId:d.objectId}).catch(()=>{})}}catch{return!1}finally{e.send("Runtime.releaseObject",{objectId:a.result.objectId}).catch(()=>{})}}state(e){let t=this.pages.get(e);return t||(t={navAt:Date.now(),url:e.url,cmp:null,refused:0,frames:new Set,topAttempts:0},this.pages.set(e,t)),t}reset(e,t){this.pages.set(e,{navAt:Date.now(),url:t,cmp:null,refused:0,frames:new Set,topAttempts:0})}emit(e,t){e==="error"&&this.emitter.listenerCount("error")===0||this.emitter.emit(e,t)}};var Pu=["cmpDetected","popupFound","optOutResult","autoconsentDone","selfTestResult","error"],Nu=["blocked","error"];async function yn(n,e={}){let t=e.consent===!1?null:new ss(typeof e.consent=="object"?e.consent:{}),s=e.adblock===!1?null:await ts.create(typeof e.adblock=="object"?e.adblock:{}),o=[];if(e.onEvent){let r=e.onEvent;if(t)for(let a of Pu)o.push(t.on(a,(c=>r({source:"consent",type:a,data:c}))));if(s)for(let a of Nu)o.push(s.on(a,(c=>r({source:"adblock",type:a,data:c}))))}let i=l(async r=>{await Promise.all([t?.initSession(r),s?.initSession(r)])},"init");return o.push(n.addSessionInitializer(i)),{consent:t,adblock:s,detach(){for(let r of o)r();t?.dispose(),s?.dispose()}}}l(yn,"attachInterrupts");var Du="pilotfish's open MCP makes no model calls: the MCP client's own model reads the page and decides the next step",Lu=l(()=>{let n=l(async()=>{throw new Error(Du)},"refuse");return{messages:{create:n},beta:{messages:{create:n}}}},"noModelClient"),bn=class{static{l(this,"ConfirmThrough")}inner;canAsk;constructor(e,t){this.inner=e,this.canAsk=t}async check(e){let t=await this.inner.check(e);return t.kind!=="confirm"||this.canAsk()?t:{kind:"deny",reason:`${t.reason}. This needs a person's confirmation, and this MCP client cannot ask for one (no elicitation support)`}}},Xe=class{static{l(this,"BrowserSession")}config;opts;browser=null;launching=null;interrupts=null;tabs=null;agent=null;queue=Promise.resolve();policy;asker;constructor(e,t={}){this.config=e,this.opts=t,this.policy=new Pe({allowedHosts:e.allowedHosts,allowPrivateNetwork:e.allowPrivateNetwork})}get launched(){return!!this.browser&&!this.browser.closed}async page(){return await this.ensure(),this.tabs.current}get tabTable(){return this.tabs}async ensure(){return this.browser&&!this.browser.closed?this.browser:(this.launching??=this.start().finally(()=>{this.launching=null}),this.launching)}async start(){let e=await ks({...this.opts.launch,headless:this.config.headless});this.interrupts=await yn(e,{consent:!0,adblock:!0}).catch(()=>null);let t=e.allPages()[0]??await e.newPage();return this.tabs=new Ne(t),this.browser=e,e.on("disconnected",()=>{this.browser===e&&this.reset()}),e}reset(){this.agent?.dispose(),this.agent=null,this.tabs?.dispose(),this.tabs=null,this.interrupts?.detach(),this.interrupts=null,this.browser=null}executor(){return this.agent??=new wt(this.tabs.current,{tabs:this.tabs,client:Lu(),secrets:this.config.secrets,policy:new bn(this.policy,()=>!!this.asker),consent:this.interrupts?.consent??void 0,allowScreenshots:this.config.allowScreenshots,askUser:l(e=>this.asker?.(e)??Promise.resolve(null),"askUser"),fastSettle:!0,enableQuery:!0,compactSnapshots:!0,autoDismiss:!0,awaitLoading:!0,actionSnapshotBand:0,snapshotMoreHint:"browser_scroll for the next screen, browser_get_text for the page's text, or browser_snapshot (whole_page) for every element"}),this.agent}async act(e,t,s={}){let o=this.queue.then(async()=>(await this.ensure(),this.executor().act(e,t,"",s)));return this.queue=o.catch(()=>{}),o}async obstacle(e={}){if(!this.launched)return null;let t=this.queue.then(()=>this.executor().obstacle(e));return this.queue=t.catch(()=>{}),t.catch(()=>null)}async close(){let e=this.browser??(this.launching?await this.launching.catch(()=>null):null);return e?(this.reset(),await e.close().catch(()=>{}),!0):!1}};import{McpServer as Fu}from"@modelcontextprotocol/sdk/server/mcp.js";import{ListToolsRequestSchema as Hu}from"@modelcontextprotocol/sdk/types.js";import{z as q}from"zod";var os="0.1.22";var is=Oe.click.shape.ref.describe('From the latest snapshot, e.g. "e12" or "f1e3"'),br=q.enum(["down","up","left","right"]),Uu={click:["ref"],type:["ref","text","submit"],select:["ref","values"],press:["key"],scroll:["direction"],wait:["seconds"]},ju={click:1,type:2,select:2,press:1,scroll:1,wait:1},Bu=q.object({action:q.enum(["click","type","select","press","scroll","wait"]).describe("click, select, type take ref; type: text (submit: Enter after); select: values; press: key; scroll: direction; wait: seconds"),ref:is.optional(),text:q.string().max(2e4).optional(),submit:q.boolean().optional(),values:q.array(q.string()).min(1).max(50).optional(),key:q.string().min(1).max(40).optional(),direction:br.optional(),seconds:q.number().min(.5).max(10).optional()}).strict().superRefine((n,e)=>{let t=Uu[n.action];for(let s of t.slice(0,ju[n.action]))n[s]===void 0&&e.addIssue({code:"custom",path:[s],message:`${n.action} needs ${s}`});for(let s of Object.keys(n))s!=="action"&&!t.includes(s)&&e.addIssue({code:"custom",path:[s],message:`${s} is not a field of ${n.action} (it takes ${t.join(", ")})`})}),re={browser_navigate:q.object({url:q.url({protocol:/^https?$/}).describe("Absolute http(s) URL"),snapshot:q.boolean().optional().describe("Default true. false: no page snapshot, only what happened (title, counts). Only when this same reply also reads the page with browser_query and you will not act on it; keep it for a page you have not seen or whose tabs, sorts, filters or forms you may use.")}).strict(),browser_snapshot:q.object({whole_page:q.boolean().optional()}).strict(),browser_click:q.object({ref:is}).strict(),browser_type:q.object({ref:is,text:q.string().max(2e4),submit:q.boolean().optional().describe("Press Enter afterwards")}).strict(),browser_select:q.object({ref:is,values:q.array(q.string()).min(1).max(50)}).strict(),browser_press:q.object({key:q.string().min(1).max(40).describe('e.g. "Enter", "Escape", "Tab", "ArrowDown", "Control+a"')}).strict(),browser_scroll:q.object({direction:br}).strict(),browser_screenshot:q.object({}).strict(),browser_get_text:q.object({max_chars:q.number().int().min(500).max(6e4).optional().describe("Default 20000. Ask for less when the start of the page is enough."),selector:q.string().min(1).max(300).optional().describe(`CSS selector: only the first match's text, e.g. "main" or "#results"`)}).strict(),browser_query:q.object({expression:q.string().min(1).max(4e3).describe("e.g. [...document.querySelectorAll('.result')].slice(0,10).map(e => e.innerText)")}).strict(),browser_find:q.object({query:q.string().min(1).max(300).describe('Words naming the element(s), e.g. "Sort by" or "price max input, Go button"')}).strict(),browser_wait:q.object({seconds:q.number().min(.5).max(10)}).strict(),browser_resume:q.object({timeout_s:q.number().int().min(5).max(900).optional().describe("Default 300")}).strict(),browser_actions:q.object({actions:q.array(Bu).min(1).max(10)}).strict(),browser_tabs:q.object({switch_to:q.string().min(1).max(10).optional().describe('Tab id to work in from now on, e.g. "t2"')}).strict(),browser_close:q.object({}).strict()};function Te(n,e=!1){return{content:[{type:"text",text:n}],...e?{isError:!0}:{}}}l(Te,"text");function qu(n){let e=Object.keys(n.secrets),t=[e.length?`Secrets are typed as placeholders and never shown: ${e.map(s=>`{{${s}}}`).join(", ")}.`:"",n.allowedHosts.length?`Navigation is limited to: ${n.allowedHosts.join(", ")}.`:""].filter(Boolean);return t.length?t.join(`
415
415
  `):void 0}l(qu,"serverInstructions");function kn(n={}){let e=n.config??n.session?.config??vt(),t=!n.session,s=n.session??new Xe(e,n),o=new Fu({name:"pilotfish",version:n.version??os},{capabilities:{logging:{}},instructions:qu(e)}),i=Object.keys(e.secrets),r=i.length?` Secrets: ${i.map(g=>`{{${g}}}`).join(", ")}.`:"",a=l(()=>!!o.server.getClientCapabilities()?.elicitation?.form,"canElicit"),c=l(g=>a()?async S=>{let E=await o.server.elicitInput({message:S,requestedSchema:{type:"object",properties:{answer:{type:"string",title:"Answer",description:'Reply "yes" to allow an action'}},required:["answer"]}},{relatedRequestId:g.requestId,timeout:e.interventionTimeoutMs}).catch(()=>null);return E?.action==="accept"&&typeof E.content?.answer=="string"?E.content.answer:null}:void 0,"askerFor"),d=l(g=>g.replace(/in the live view/g,"in the pilotfish browser window").replace(/Please send the code, or type it/,"Please type the code"),"forWindow"),u=l(g=>g.needs==="solve_in_live_view"||g.needs==="login_in_live_view"||g.needs==="code"||g.needs==="credentials","byHand"),h=l((g,S="")=>[`NEEDS A PERSON (${g.category}${g.vendor?`, ${g.vendor}`:""}): ${d(g.message)}`,S,u(g)&&e.headless?"This browser is headless, so it cannot be done by hand here: tell the user, and that the pilotfish server needs PILOTFISH_HEADLESS=0 (a visible window) for steps like this one.":`Tell the user now, in your reply: what the page needs, and that the pilotfish browser window is open on it (${g.url}). Ask them to do it there and to tell you when it is done. Then call browser_resume: it waits for the page to move on and returns it.`,"Do not try to get past it yourself: pilotfish does not type passwords or codes it was not given, and does not solve CAPTCHAs."].filter(Boolean).join(`
416
416
  `),"needsPerson"),p=l(async()=>{let g=await s.act("read_page",{}).catch(()=>null);return g?g.text||g.summary:""},"pageNow"),f=l(async(g,S=1e3)=>{let E=Date.now()+g,A=await s.obstacle({fresh:!0});for(;A&&Date.now()<E;)await new Promise(k=>setTimeout(k,S)),A=await s.obstacle({fresh:!0});return A},"untilClear"),y=l((g,S)=>({...g,content:[...g.content,{type:"text",text:S}]}),"withNote"),b=l(async(g,S)=>{let E=await s.obstacle();if(!E)return S;if(E.autoResolvable&&!E.neverAutomate&&(E=await f(12e3),!E))return y(S,`A browser check was showing and cleared by itself. The page now:
417
417
  ${await p()}`);if(E.neverAutomate)return y(S,`STOP: ${E.host} shows a bot check, and this site is never automated past one (ticket sellers: the US BOTS Act; UIDAI: the Aadhaar Act). Do not continue on it; tell the user.`);if(E.category==="hard_block"||E.needs==="none_possible")return y(S,`BLOCKED: ${d(E.message)} A person cannot fix this from the browser window: try another way (another page or site), or tell the user.`);if(a()&&!(u(E)&&e.headless)){let A=await o.server.elicitInput({message:`${d(E.message)} (${E.url})`,requestedSchema:{type:"object",properties:{done:{type:"boolean",title:"I have done it in the pilotfish browser window"}},required:["done"]}},{relatedRequestId:g.requestId,timeout:e.interventionTimeoutMs}).catch(()=>null);if(A?.action==="accept"&&A.content?.done!==!1){let k=await f(15e3);return k?y(S,h(k,"The person said it is done, but the page still shows it.")):y(S,`The person handled it. The page now:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gaiventures/pilotfish-mcp",
3
- "version": "0.1.21",
3
+ "version": "0.1.22",
4
4
  "description": "Give any MCP agent a real Chrome on your own computer. Free, no account, no API key. mcprush.com-ba6a69f5121bd8a0089bb26a",
5
5
  "license": "MIT",
6
6
  "type": "module",