@gaiventures/pilotfish-mcp 0.1.62 → 0.1.63

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
@@ -362,7 +362,7 @@ ${await this.observe(null)}`,`close_tab ${o}`)}case"go_back":return await this.w
362
362
  `)[0]??"",c=!d&&this.page.pendingData()===0&&!this.page.socketBusy(1e3)&&(await this.page.loadState()).readyState==="complete"}let u=c?Math.min(r*1e3,500):r*1e3,h=0;return await this.withEvidence(async()=>{let p=Date.now();if(!d)await K(u);else for(;Date.now()-p<u&&(await K(250),!!await this.page.main.evaluate(io,{timeoutMs:1e3}).catch(()=>"(unread)")););h=Date.now()-p},`wait ${r}s`,()=>c?`(waited only ${u} ms: the page is idle, no requests pending. Actions already wait for their own effects.)`:d&&h<u-100?`(The page's "${d}" finished after ${(h/1e3).toFixed(1)} s.)`:"",{settle:!1})}case"read_page":{let o=await this.observe(this.lastSnapshot,{wholePage:t.whole_page===!0,interactiveOnly:t.interactive_only===!0,rootRef:typeof t.root_ref=="string"?t.root_ref:void 0,record:this.inAct});return this.note(ot("read_page",t)),oe(o,"read_page")}case"find":{this.lastSnapshot||await this.observe(null);let o=await se(this.page,{viewportBand:1/0,previous:this.lastSnapshot});this.lastSnapshot=o;let i=yn(o,String(t.query)),r=i.map(w=>w.node),a=new Set(i.filter(w=>!w.exact).map(w=>w.node));if(this.note(ot("find",t)),!r.length){let w=this.closest(o,String(t.query));return oe(this.secrets.scrub(`No elements match "${t.query}".${w||" Try different words, scroll, or get_text to read the page."}`),"find: 0 hits")}let c=new Map(o.nodes.map((w,g)=>[w,g])),d=o.nodes.filter(w=>w.role==="heading"&&w.visible),u=l(w=>{let g=c.get(w)??0,b;for(let _ of d){if((c.get(_)??0)>=g)break;b=_}let k=b?he(b,60):"";return k?` in section "${k}"`:""},"section"),h=this.inAct&&this.opts.compactSnapshots?o.url:void 0,p=r.map(w=>{let g=w.rect?w.rect.y+o.scroll.y>o.scroll.y+o.viewport.height?" (below viewport)":w.rect.y+o.scroll.y+w.rect.height<o.scroll.y?" (above viewport)":"":"";return`${Ae(w,h,h!==void 0&&this.opts.roleTags)}${u(w)}${g}${a.has(w)?" (partial match)":""}`}),f=r.length-a.size,m=a.size?`${f?`${f} match(es)`:"No element has all the words"}${f?`, and ${a.size} with most of them (partial match: check it is the one you mean)`:`; ${a.size} with most of them (partial match: check it is the one you mean)`}`:`${r.length} match(es)`;return oe(this.secrets.scrub(`${m}, best first. Refs are valid now (whole-page snapshot):
363
363
  ${p.join(`
364
364
  `)}`),`find: ${r.length} hits${a.size?` (${a.size} partial)`:""}`)}case"get_text":{if((await this.page.loadState()).contentType==="application/pdf"){let c=new Uint8Array(await this.page.documentBytes()),d=await Jn(c.slice(),Number(t.max_chars??2e4));this.note("get_text"),this.keepRead("get_text",this.secrets.scrub(d.text));let u=this.opts.onDocumentRead?await this.opts.onDocumentRead({url:this.page.url,name:vr(this.page.url),bytes:c}).catch(()=>null):null;return oe(this.secrets.scrub(`PDF TEXT (${this.page.url}, ${d.pages} page(s)${d.truncated?", truncated":""})${u?`. ${u}`:""}:
365
- ${d.text}`),`get_text: pdf ${d.pages} pages`)}let o=Number(t.max_chars??2e4);if(typeof t.selector=="string"&&t.selector.trim()){let c=t.selector.trim(),d=await this.page.main.evaluate(`(() => { const e = document.querySelector(${JSON.stringify(c)}); return e ? (e.innerText || e.textContent || "") : null; })()`,{readOnly:!0,timeoutMs:5e3}).catch(p=>{throw new ee("not_found",`selector ${c}: ${p instanceof Error?p.message.slice(0,160):String(p)}`)});if(d===null)return ne(`No element matches the selector ${c}. Use get_text without a selector, or find to locate the part you mean.`);let u=d.replace(/[ \t]+\n/g,`
365
+ ${d.text}`),`get_text: pdf ${d.pages} pages${u?` (${u})`:""}`)}let o=Number(t.max_chars??2e4);if(typeof t.selector=="string"&&t.selector.trim()){let c=t.selector.trim(),d=await this.page.main.evaluate(`(() => { const e = document.querySelector(${JSON.stringify(c)}); return e ? (e.innerText || e.textContent || "") : null; })()`,{readOnly:!0,timeoutMs:5e3}).catch(p=>{throw new ee("not_found",`selector ${c}: ${p instanceof Error?p.message.slice(0,160):String(p)}`)});if(d===null)return ne(`No element matches the selector ${c}. Use get_text without a selector, or find to locate the part you mean.`);let u=d.replace(/[ \t]+\n/g,`
366
366
  `).replace(/\n{3,}/g,`
367
367
 
368
368
  `).trim(),h=u.length>o?`${u.slice(0,o)}\u2026(truncated)`:u;return this.note(ot("get_text",t)),this.keepRead("get_text",this.secrets.scrub(h),c),oe(this.secrets.scrub(`PAGE TEXT (${this.page.url}, ${c}):
@@ -507,7 +507,7 @@ return __pfClassify("Accept all") === "accept" && __pfClassify("Reject all") ===
507
507
  };
508
508
  })();
509
509
  ${Os(ba(ka,"autoconsent.playwright.js"),"utf8")}`,Np=3,Lp=2500,Pp=6500,Dp=6e3,Fp=3e3,jp=1500,Hp=3e3,Up=4e3;function Bp(n,e){if(n.doneAt)return"opted_out";if(n.optOut===!1)return"failed";if(n.optOut===!0)return e-n.optOutAt>Fp?"opted_out":"pending";if(n.popupAt)return"pending";if(n.detectedAt)return e-n.detectedAt<Pp?"pending":"no_cmp";let t=n.topLifecycle!=="nothingDetected",s=l((o,i)=>e-o>=Lp&&i!==void 0&&n.topAttempts>=i+Np,"quiet");return n.cmpRequestAt&&e-n.cmpRequestAt<Dp&&t&&!s(n.cmpRequestAt,n.roundAtCmpRequest)||!n.topInitAt&&/^https?:/.test(n.url)&&e-n.navAt<jp||n.topInitAt&&n.topAttempts<2&&e-n.topInitAt<Hp||n.patternsAt&&e-n.patternsAt<Up&&t&&!s(n.patternsAt,n.roundAtPatterns)?"pending":"no_cmp"}l(Bp,"outcomeOf");var Cs=class{static{l(this,"ConsentEngine")}opts;emitter=new Tp;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=Op(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=Bp(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&&Ge(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:wt,executionContextName:yo},{timeoutMs:5e3}),t.send("Page.addScriptToEvaluateOnNewDocument",{source:Mp,worldName:yo,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:wt}).catch(()=>{})},"dispose");this.disposers.add(a),i.push(()=>this.disposers.delete(a));let c=l(async(p,f,m)=>{if(!/^https?:/.test(f)||!m&&Ge(f))return;let{executionContextId:w}=await t.send("Page.createIsolatedWorld",{frameId:p,worldName:yo,grantUniveralAccess:!1},{timeoutMs:5e3});o.set(w,{frameId:p,mainFrame:m}),await t.send("Runtime.addBinding",{name:wt,executionContextId:w},{timeoutMs:5e3}),await t.send("Runtime.evaluate",{contextId:w,expression:"globalThis.__pfAcFlush && __pfAcFlush()",returnByValue:!0},{timeoutMs:5e3})},"arm"),d=l((p,f,m)=>{c(p,f,m).catch(w=>{/not found|Cannot find|No frame|detached|closed|destroyed|navigated/i.test(String(w))||this.emit("error",{page:s,frameId:p,url:f,error:`arm: ${String(w)}`})})},"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!==wt)return;let f=o.get(p.executionContextId);f&&this.onMessage(t,s,p.executionContextId,f,p.payload).catch(()=>{})}),t.on("Network.requestWillBeSent",p=>{if(!ta(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 m of p.childFrames??[])h(m,!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:Ap(va,{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"?ya[i]:void 0;if(!r||Cp.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 qp=["cmpDetected","popupFound","optOutResult","autoconsentDone","selfTestResult","error"],Wp=["blocked","error"];async function vo(n,e={}){let t=e.consent===!1?null:new Cs(typeof e.consent=="object"?e.consent:{}),s=e.adblock===!1?null:await As.create(typeof e.adblock=="object"?e.adblock:{}),o=[];if(e.onEvent){let r=e.onEvent;if(t)for(let a of qp)o.push(t.on(a,(c=>r({source:"consent",type:a,data:c}))));if(s)for(let a of Wp)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(vo,"attachInterrupts");var Gp="pilotfish's open MCP makes no model calls: the MCP client's own model reads the page and decides the next step",Vp=l(()=>{let n=l(async()=>{throw new Error(Gp)},"refuse");return{messages:{create:n},beta:{messages:{create:n}}}},"noModelClient"),xo=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)`}}},bt=class{static{l(this,"BrowserSession")}config;opts;browser=null;launching=null;interrupts=null;tabs=null;agent=null;secretOutputs=0;configSecrets=null;queue=Promise.resolve();policy;callContext=new zp;get asker(){return this.callContext.getStore()?.asker}run(e,t){return this.enqueue(()=>this.callContext.run({asker:e},t))}enqueue(e){if(this.callContext.getStore())return e();let t=this.queue.then(e);return this.queue=t.catch(()=>{}),t}constructor(e,t={}){this.config=e,this.opts=t,this.policy=new tt({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 Qs({...this.opts.launch,headless:this.config.headless});this.interrupts=await vo(e,{consent:!0,adblock:!0}).catch(()=>null);let t=e.allPages()[0]??await e.newPage();return this.tabs=new st(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}hasTypedPasswords(){return!!this.agent?.hasTypedPasswords()}holdsSecret(e){return this.agent?this.agent.holdsSecretOutput(e):(this.configSecrets??=new et(this.config.secrets),this.configSecrets.holdsSecret(e))}scrubReply(e){return this.agent?this.agent.scrubOutput(e):e}executor(){return this.agent??=new Vt(this.tabs.current,{tabs:this.tabs,client:Vp(),secrets:this.config.secrets,policy:new xo(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,roleTags:!0,actionReceipts:!0,guardSecretOutput:!0,onSecretOutput:l(()=>{this.secretOutputs++},"onSecretOutput"),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",pageToolCall:"browser_page_tool"}),this.agent}async act(e,t,s={}){return this.enqueue(async()=>(await this.ensure(),this.executor().act(e,t,"",s)))}async obstacle(e={}){return this.enqueue(async()=>this.launched?this.executor().obstacle(e):null).catch(()=>({unread:!0,changed:!1,message:"Could not verify the page for a sign-in, a code or a bot check: the look at it failed.",host:"",url:""}))}async close(){return this.enqueue(async()=>{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 Jp}from"@modelcontextprotocol/sdk/server/mcp.js";import{ListToolsRequestSchema as Xp}from"@modelcontextprotocol/sdk/types.js";import{z as X}from"zod";import{appendFileSync as Qp}from"node:fs";import{createHash as Zp}from"node:crypto";import{AjvJsonSchemaValidator as xa}from"@modelcontextprotocol/sdk/validation/ajv";var yt=class extends Error{static{l(this,"InvalidSchemaError")}},Kp=32,_o=new xa,Rs=new Map,So=null;function _a(n,e=5){return n?n.split(/, (?=data[/ ])/).slice(0,e).map(t=>{let s=/^data(\S*) ([\s\S]*)$/.exec(t);return s?`${s[1]||"(root)"}: ${s[2]}`:t}):[]}l(_a,"errorLines");function Sa(n){let{$schema:e,$id:t,...s}=n,o=JSON.stringify(s),i=Rs.get(o);if(i)return i;Rs.size>=Kp&&(_o=new xa,Rs=new Map,So=null),So??=_o.getValidator({$ref:"http://json-schema.org/draft-07/schema#"});let r=So(s);if(!r.valid)throw new yt(_a(r.errorMessage,1)[0]??"not a JSON Schema");let a;try{a=_o.getValidator(s)}catch(c){throw new yt(String(c?.message??c).split(`
510
- `)[0].slice(0,200))}return Rs.set(o,a),a}l(Sa,"schemaCheck");var Yp="...(truncated)";function $a(n,e){if(n.endsWith(Yp))return{ok:!1,lines:["(root): result over 4000 characters; return less"]};let t=/^(\[\]|""|\s*) \(nothing matched\)/.exec(n),s=[];if(t)s.push(t[1]==="[]"?[]:"");else{try{s.push(JSON.parse(n))}catch{}s.push(n)}let o=null;for(let i of s){let r=e(i);if(r.valid)return{ok:!0,value:i};o??=_a(r.errorMessage)}return{ok:!1,lines:o??[]}}l($a,"checkQueryText");var Ms="0.1.62";var ef=l(n=>{try{return new URL(n).hostname}catch{return""}},"hostOf"),tf=l(n=>Zp("sha256").update(n).digest("hex").slice(0,10),"shortHash"),kt=Ze.click.shape.ref.describe('From the latest snapshot, e.g. "e12" or "f1e3"'),Ta=X.enum(["down","up","left","right"]),Yt=X.object({text:X.string().min(1).max(120).optional(),gone:X.string().min(1).max(120).optional(),in:kt.optional(),url:X.string().min(1).max(200).optional(),within:X.number().min(0).max(10).optional()}).strict().refine(n=>!!(n.text||n.gone||n.url),{message:"give text, gone or url"}).optional().describe("What this should bring about: text shown / gone (in element `in`, else the page), url containing a part; within seconds (default 3). The reply says MATCHED, UNMET, ALREADY HELD (true before too) or AMBIGUOUS (why): a page state, not proof the task succeeded."),Jt=X.boolean().optional().describe("With snapshot:false: print the page anyway if the expectation is unmet or ambiguous, or on a dialog, new tab, unexpected page, refused write, invalid field or page still loading."),it=X.boolean().optional().describe("Default true. false: no page snapshot in the result, only the evidence (what changed, was added or removed) and notes; for a next step that reads with browser_query or browser_get_text, or more steps before one look. browser_snapshot shows the screen at any time."),sf={click:["ref"],type:["ref","text","submit"],select:["ref","values"],press:["key"],scroll:["direction"],wait:["seconds"]},nf={click:1,type:2,select:2,press:1,scroll:1,wait:1},of=X.object({action:X.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:kt.optional(),text:X.string().max(2e4).optional(),submit:X.boolean().optional(),values:X.array(X.string()).min(1).max(50).optional(),key:X.string().min(1).max(40).optional(),direction:Ta.optional(),seconds:X.number().min(.5).max(10).optional()}).strict().superRefine((n,e)=>{let t=sf[n.action];for(let s of t.slice(0,nf[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(", ")})`})}),me={browser_navigate:X.object({url:X.url({protocol:/^https?$/}).describe("Absolute http(s) URL"),expect:Yt,escalate:Jt,snapshot:X.boolean().optional().describe("Default true. Choose by your next step on this page: false when you will only read it (browser_query, browser_get_text) or go on to another URL; keep true when you will click, type or choose on it (you need its refs). false still returns the evidence (where it landed, the title, what was added or removed), loading notes and anything that needs a person; browser_snapshot shows the screen at any time.")}).strict(),browser_snapshot:X.object({whole_page:X.boolean().optional()}).strict(),browser_click:X.object({ref:kt,snapshot:it,expect:Yt,escalate:Jt}).strict(),browser_type:X.object({ref:kt,text:X.string().max(2e4),submit:X.boolean().optional().describe("Press Enter afterwards"),snapshot:it,expect:Yt,escalate:Jt}).strict(),browser_select:X.object({ref:kt,values:X.array(X.string()).min(1).max(50),snapshot:it,expect:Yt,escalate:Jt}).strict(),browser_press:X.object({key:X.string().min(1).max(40).describe('e.g. "Enter", "Escape", "Tab", "ArrowDown", "Control+a"'),snapshot:it,expect:Yt,escalate:Jt}).strict(),browser_scroll:X.object({direction:Ta,snapshot:it}).strict(),browser_screenshot:X.object({}).strict(),browser_get_text:X.object({max_chars:X.number().int().min(500).max(6e4).optional().describe("Default 20000. Ask for less when the start of the page is enough."),selector:X.string().min(1).max(300).optional().describe(`CSS selector: only the first match's text, e.g. "main" or "#results"`)}).strict(),browser_query:X.object({expression:X.string().min(1).max(4e3).describe("e.g. [...document.querySelectorAll('.result')].slice(0,10).map(e => e.innerText)"),schema:X.looseObject({}).optional().describe("JSON Schema the result must match")}).strict(),browser_find:X.object({query:X.string().min(1).max(300).describe('Words naming the element(s), e.g. "Sort by" or "price max input, Go button"')}).strict(),browser_wait:X.object({seconds:X.number().min(.5).max(10),until:X.string().max(120).optional().describe("Return once the page shows this text"),gone:X.string().max(120).optional().describe("Return once this text is gone"),in:kt.optional().describe("Only within this element; the reply says whether it already held when the wait began"),snapshot:it}).strict(),browser_resume:X.object({timeout_s:X.number().int().min(5).max(900).optional().describe("Default 300")}).strict(),browser_actions:X.object({actions:X.array(of).min(1).max(10),snapshot:it}).strict(),browser_tabs:X.object({switch_to:X.string().min(1).max(10).optional().describe('Tab id to work in from now on, e.g. "t2"')}).strict(),browser_close:X.object({}).strict(),browser_page_tool:X.object({tool:X.string().min(1).max(200).describe("A name from the PAGE TOOLS line"),arguments:X.looseObject({}).optional().describe("Its input, as the parameters listed there")}).strict()},$o="https://pilotfish.gai.ventures/docs";function De(n,e=!1){return{content:[{type:"text",text:n}],...e?{isError:!0}:{}}}l(De,"text");function rf(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(`
510
+ `)[0].slice(0,200))}return Rs.set(o,a),a}l(Sa,"schemaCheck");var Yp="...(truncated)";function $a(n,e){if(n.endsWith(Yp))return{ok:!1,lines:["(root): result over 4000 characters; return less"]};let t=/^(\[\]|""|\s*) \(nothing matched\)/.exec(n),s=[];if(t)s.push(t[1]==="[]"?[]:"");else{try{s.push(JSON.parse(n))}catch{}s.push(n)}let o=null;for(let i of s){let r=e(i);if(r.valid)return{ok:!0,value:i};o??=_a(r.errorMessage)}return{ok:!1,lines:o??[]}}l($a,"checkQueryText");var Ms="0.1.63";var ef=l(n=>{try{return new URL(n).hostname}catch{return""}},"hostOf"),tf=l(n=>Zp("sha256").update(n).digest("hex").slice(0,10),"shortHash"),kt=Ze.click.shape.ref.describe('From the latest snapshot, e.g. "e12" or "f1e3"'),Ta=X.enum(["down","up","left","right"]),Yt=X.object({text:X.string().min(1).max(120).optional(),gone:X.string().min(1).max(120).optional(),in:kt.optional(),url:X.string().min(1).max(200).optional(),within:X.number().min(0).max(10).optional()}).strict().refine(n=>!!(n.text||n.gone||n.url),{message:"give text, gone or url"}).optional().describe("What this should bring about: text shown / gone (in element `in`, else the page), url containing a part; within seconds (default 3). The reply says MATCHED, UNMET, ALREADY HELD (true before too) or AMBIGUOUS (why): a page state, not proof the task succeeded."),Jt=X.boolean().optional().describe("With snapshot:false: print the page anyway if the expectation is unmet or ambiguous, or on a dialog, new tab, unexpected page, refused write, invalid field or page still loading."),it=X.boolean().optional().describe("Default true. false: no page snapshot in the result, only the evidence (what changed, was added or removed) and notes; for a next step that reads with browser_query or browser_get_text, or more steps before one look. browser_snapshot shows the screen at any time."),sf={click:["ref"],type:["ref","text","submit"],select:["ref","values"],press:["key"],scroll:["direction"],wait:["seconds"]},nf={click:1,type:2,select:2,press:1,scroll:1,wait:1},of=X.object({action:X.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:kt.optional(),text:X.string().max(2e4).optional(),submit:X.boolean().optional(),values:X.array(X.string()).min(1).max(50).optional(),key:X.string().min(1).max(40).optional(),direction:Ta.optional(),seconds:X.number().min(.5).max(10).optional()}).strict().superRefine((n,e)=>{let t=sf[n.action];for(let s of t.slice(0,nf[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(", ")})`})}),me={browser_navigate:X.object({url:X.url({protocol:/^https?$/}).describe("Absolute http(s) URL"),expect:Yt,escalate:Jt,snapshot:X.boolean().optional().describe("Default true. Choose by your next step on this page: false when you will only read it (browser_query, browser_get_text) or go on to another URL; keep true when you will click, type or choose on it (you need its refs). false still returns the evidence (where it landed, the title, what was added or removed), loading notes and anything that needs a person; browser_snapshot shows the screen at any time.")}).strict(),browser_snapshot:X.object({whole_page:X.boolean().optional()}).strict(),browser_click:X.object({ref:kt,snapshot:it,expect:Yt,escalate:Jt}).strict(),browser_type:X.object({ref:kt,text:X.string().max(2e4),submit:X.boolean().optional().describe("Press Enter afterwards"),snapshot:it,expect:Yt,escalate:Jt}).strict(),browser_select:X.object({ref:kt,values:X.array(X.string()).min(1).max(50),snapshot:it,expect:Yt,escalate:Jt}).strict(),browser_press:X.object({key:X.string().min(1).max(40).describe('e.g. "Enter", "Escape", "Tab", "ArrowDown", "Control+a"'),snapshot:it,expect:Yt,escalate:Jt}).strict(),browser_scroll:X.object({direction:Ta,snapshot:it}).strict(),browser_screenshot:X.object({}).strict(),browser_get_text:X.object({max_chars:X.number().int().min(500).max(6e4).optional().describe("Default 20000. Ask for less when the start of the page is enough."),selector:X.string().min(1).max(300).optional().describe(`CSS selector: only the first match's text, e.g. "main" or "#results"`)}).strict(),browser_query:X.object({expression:X.string().min(1).max(4e3).describe("e.g. [...document.querySelectorAll('.result')].slice(0,10).map(e => e.innerText)"),schema:X.looseObject({}).optional().describe("JSON Schema the result must match")}).strict(),browser_find:X.object({query:X.string().min(1).max(300).describe('Words naming the element(s), e.g. "Sort by" or "price max input, Go button"')}).strict(),browser_wait:X.object({seconds:X.number().min(.5).max(10),until:X.string().max(120).optional().describe("Return once the page shows this text"),gone:X.string().max(120).optional().describe("Return once this text is gone"),in:kt.optional().describe("Only within this element; the reply says whether it already held when the wait began"),snapshot:it}).strict(),browser_resume:X.object({timeout_s:X.number().int().min(5).max(900).optional().describe("Default 300")}).strict(),browser_actions:X.object({actions:X.array(of).min(1).max(10),snapshot:it}).strict(),browser_tabs:X.object({switch_to:X.string().min(1).max(10).optional().describe('Tab id to work in from now on, e.g. "t2"')}).strict(),browser_close:X.object({}).strict(),browser_page_tool:X.object({tool:X.string().min(1).max(200).describe("A name from the PAGE TOOLS line"),arguments:X.looseObject({}).optional().describe("Its input, as the parameters listed there")}).strict()},$o="https://pilotfish.gai.ventures/docs";function De(n,e=!1){return{content:[{type:"text",text:n}],...e?{isError:!0}:{}}}l(De,"text");function rf(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(`
511
511
  `):void 0}l(rf,"serverInstructions");function To(n={}){let e=n.config??n.session?.config??Xt(),t=!n.session,s=n.session??new bt(e,n),o=new Jp({name:"pilotfish",version:n.version??Ms},{capabilities:{logging:{}},instructions:rf(e)}),i=Object.keys(e.secrets),r=i.length?` Secrets: ${i.map(S=>`{{${S}}}`).join(", ")}.`:"",a=l(()=>!!o.server.getClientCapabilities()?.elicitation?.form,"canElicit"),c=l(S=>a()?async A=>{let U=await o.server.elicitInput({message:A,requestedSchema:{type:"object",properties:{answer:{type:"string",title:"Answer",description:'Reply "yes" to allow an action'}},required:["answer"]}},{relatedRequestId:S.requestId,timeout:e.interventionTimeoutMs}).catch(()=>null);return U?.action==="accept"&&typeof U.content?.answer=="string"?U.content.answer:null}:void 0,"askerFor"),d=l(S=>S.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(S=>S.needs==="solve_in_live_view"||S.needs==="login_in_live_view"||S.needs==="code"||S.needs==="credentials","byHand"),h=l((S,A="")=>[`NEEDS A PERSON (${S.category}${S.vendor?`, ${S.vendor}`:""}): ${s.scrubReply(d(S.message))}`,A,u(S)&&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. Docs: ${$o}/open-settings`:`Tell the user now, in your reply: what the page needs, and that the pilotfish browser window is open on it (${S.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.",u(S)&&e.headless?"":`Docs: ${$o}/open`].filter(Boolean).join(`
512
512
  `),"needsPerson"),p=l((S,A="")=>[`COULD NOT VERIFY THE PAGE: ${s.scrubReply(S.message)}`,A,"Look at the page again (browser_snapshot, or browser_wait while it loads) before relying on it; if it shows a sign-in, a code or a check, tell the user."].filter(Boolean).join(`
513
513
  `),"couldNotCheck"),f=l(async()=>{let S=await s.act("read_page",{}).catch(()=>null);return S?S.text||S.summary:""},"pageNow"),m=l(async(S,A=1e3)=>{let U=Date.now()+S,V=await s.obstacle({fresh:!0});for(;V&&Date.now()<U;)await new Promise(z=>setTimeout(z,A)),V=await s.obstacle({fresh:!0});return V},"untilClear"),w=l((S,A)=>({...S,content:[...S.content,{type:"text",text:A}]}),"withNote"),g=l(async(S,A)=>{let U=await s.obstacle();if(!U)return A;if("unread"in U)return w(A,p(U));let V=U;if(V.autoResolvable&&!V.neverAutomate){let z=await m(12e3);if(!z)return w(A,`A browser check was showing and cleared by itself. The page now:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gaiventures/pilotfish-mcp",
3
- "version": "0.1.62",
3
+ "version": "0.1.63",
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",