agent-afk 5.185.0 → 5.186.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/telegram.mjs CHANGED
@@ -319,7 +319,7 @@ ${o}`,paths:[e,n]}:o!==null?s={content:o,paths:[n]}:r!==null?s={content:r,paths:
319
319
 
320
320
  ${e}`}var MX,uh=h(()=>{"use strict";MX=new Set(["script","style","noscript","template","svg"])});function FX(t,e){return new Promise((n,r)=>{if(e?.aborted){r(e.reason??new Error("aborted"));return}let o=()=>{clearTimeout(s),r(e?.reason??new Error("aborted"))},s=setTimeout(()=>{e?.removeEventListener("abort",o),n()},t);e?.addEventListener("abort",o,{once:!0})})}function FA(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function LX(t,e){let n=t.headers.get("retry-after");if(n===null)return null;let r=Number(n.trim());return!Number.isFinite(r)||r<0?null:Math.min(r*1e3,e)}async function LA(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??FX,c=n.signal??void 0,l;for(let d=0;d<=o;d++){if(c?.aborted)throw c.reason??new Error("aborted");try{let u=await t(e,n);if(!DX.has(u.status)||d===o)return u;let p=LX(u,i)??FA(d,s,i);D("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,c)}catch(u){if(c?.aborted||(l=u,d===o))throw u;let p=FA(d,s,i);D("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,c)}}throw l??new Error("retryFetch: exhausted without a result")}var DX,NA=h(()=>{"use strict";ie();DX=new Set([429,502,503,504])});import{BlockList as NX,isIP as fh}from"node:net";import{lookup as $X}from"node:dns/promises";import{Agent as UX}from"undici";function UA(){let t=v.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return t==="1"||t==="true"}function WX(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function ph(t){let e=fh(t);return e===0?!1:HX.check(t,e===4?"ipv4":"ipv6")}async function BA(t){return $X(t,{all:!0,verbatim:!0})}async function Rr(t,e={}){if(e.allowPrivateHosts??UA())return{allowed:!0};let n;try{n=new URL(t)}catch{return{allowed:!1,reason:`"${t}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{allowed:!1,reason:`protocol "${n.protocol}" not supported (http/https only)`};let r=WX(n.hostname),o=(a,c)=>`refusing to fetch ${c} \u2014 internal/private address ${a} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`;if(fh(r)!==0)return ph(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let s=e.lookupFn??BA,i;try{i=await s(r)}catch{return{allowed:!0}}for(let a of i)if(ph(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Bi(t,e={}){let n=await Rr(t,e);if(!n.allowed)throw new Ie(n.reason)}async function Mn(t,e,n={},r={}){let o={...r.lookupFn!==void 0?{lookupFn:r.lookupFn}:{},...r.allowPrivateHosts!==void 0?{allowPrivateHosts:r.allowPrivateHosts}:{}},s=e;for(let i=0;i<=$A;i++){await Bi(s,o);let a={...n,redirect:"manual",...t===globalThis.fetch&&!(r.allowPrivateHosts??UA())?{dispatcher:KX}:{}},c=await LA(t,s,a,r.retry??{});if(!qX.has(c.status))return c;let l=c.headers.get("location");if(l===null||l.trim()==="")return c;let d;try{d=new URL(l,c.url||s).toString()}catch{return c}await c.body?.cancel().catch(()=>{}),s=d}throw new Ie(`too many redirects (>${$A}) starting from ${e}`)}var BX,jX,HX,Ie,KX,$A,qX,Ir=h(()=>{"use strict";L();NA();BX=[["0.0.0.0",8],["10.0.0.0",8],["100.64.0.0",10],["127.0.0.0",8],["169.254.0.0",16],["172.16.0.0",12],["192.168.0.0",16]],jX=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],HX=(()=>{let t=new NX;for(let[e,n]of BX)t.addSubnet(e,n,"ipv4");for(let[e,n]of jX)t.addSubnet(e,n,"ipv6");return t})(),Ie=class extends Error{constructor(e){super(e),this.name="EgressBlockedError"}};KX=new UX({connect:{lookup(t,e,n){BA(t).then(r=>{let o=r.find(i=>ph(i.address));if(o!==void 0){n(new Ie(`refusing to connect to ${t} (resolved) \u2014 internal/private address ${o.address} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`),"",0);return}let s=r[0];if(s===void 0){n(new Error(`DNS lookup returned no addresses for ${t}`),"",0);return}n(null,s.address,fh(s.address))},r=>n(r,"",0))}}});$A=20,qX=new Set([301,302,303,307,308])});var gh={};Bs(gh,{enforceDomainPolicy:()=>Rt,loadBrowserConfig:()=>mh});import{readFileSync as GX}from"node:fs";import{join as XX}from"path";function zX(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function jA(t,e){return zX(e).test(t)}function YX(t,e){if(t!==void 0){let n=t.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(e!==void 0){if(JX.has(e))return!0;if(VX.has(e))return!1}return!1}function HA(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function QX(t){if(t===void 0||t==="")return"auto";if(t==="playwright"||t==="agent-browser"||t==="auto")return t;throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${t}`)}function WA(t){let e=t===void 0||t.trim()===""?"default":t.trim();return lm(e),e}function ZX(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function ez(t){try{return GX(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function tz(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright"||e.backend==="agent-browser"||e.backend==="auto")n.backend=e.backend;else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=WA(e.defaultProfile)),n}function mh(t){let e=t?.env??v,n=t?.readFileSync??ez,r=t?.surface??e.AGENT_SURFACE,o=YX(e.AFK_BROWSER_HEADLESS,r),s=HA(e.AFK_BROWSER_ALLOWED_DOMAINS),i=HA(e.AFK_BROWSER_BLOCKED_DOMAINS),a=ZX(e.AFK_BROWSER_DOM_SNAPSHOTS),c=QX(e.AFK_BROWSER_BACKEND),l=WA(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():XX(tn(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${p}: ${String(y)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=tz(d,m);return g.configPath=p,g}function Rt(t,e){let n;try{n=new URL(t).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${t}`}}for(let r of e.blockedDomains)if(jA(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>jA(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var JX,VX,On=h(()=>{"use strict";L();j();JX=new Set(["daemon","subagent","telegram","afk"]),VX=new Set(["repl","interactive","cli"])});import{readFileSync as nz}from"node:fs";import{join as rz}from"node:path";import{homedir as oz}from"node:os";function iz(t){let e=t??sz,n;try{n=nz(e,"utf8")}catch{return null}let r;try{r=JSON.parse(n)}catch{return null}if(typeof r!="object"||r===null||Array.isArray(r))return null;let o=r;if(typeof o.url!="string"||typeof o.token!="string"||typeof o.pid!="number")return null;let s;try{s=new URL(o.url)}catch{return null}let{hostname:i,protocol:a}=s;if(!(i==="127.0.0.1"||i==="localhost"||i==="::1")||a!=="http:")throw new Error(`Agent Browser connection file contains an untrusted URL: ${o.url}. Only http://127.0.0.1 or http://localhost is permitted.`);return{url:o.url,token:o.token,pid:o.pid,version:typeof o.version=="string"?o.version:"unknown"}}function az(t){try{return process.kill(t,0),!0}catch{return!1}}async function cz(t,e,n=2e3){try{let r=new AbortController,o=setTimeout(()=>r.abort(),n),s=await fetch(`${t}/health`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Host:"127.0.0.1:8833"},signal:r.signal});return clearTimeout(o),s.ok}catch{return!1}}async function hh(t){let e=iz(t);return e===null?{available:!1,connection:null,reason:"connection file missing or invalid"}:az(e.pid)?await cz(e.url,e.token)?{available:!0,connection:e,reason:null}:{available:!1,connection:e,reason:`health probe failed at ${e.url}`}:{available:!1,connection:e,reason:`stale connection file: PID ${e.pid} not alive`}}var sz,KA=h(()=>{"use strict";sz=rz(oz(),".config","agent-browser","connection.json")});async function qA(t){let{config:e,surface:n}=t;if(e.backend==="playwright")return{backend:"playwright",reason:"explicit config: backend=playwright",probeMs:0,availability:null};if(e.backend==="agent-browser"){let i=Date.now(),a=await hh(),c=Date.now()-i;if(!a.available)throw new Error(`AFK_BROWSER_BACKEND=agent-browser but Agent Browser is not available: ${a.reason}`);return{backend:"agent-browser",reason:"explicit config: backend=agent-browser",probeMs:c,availability:a}}if(n&&lz.has(n))return{backend:"playwright",reason:`auto: surface "${n}" excluded from Agent Browser`,probeMs:0,availability:null};if(e.headless)return{backend:"playwright",reason:"auto: headless mode requires Playwright",probeMs:0,availability:null};let r=Date.now(),o=await hh(),s=Date.now()-r;return o.available?{backend:"agent-browser",reason:"auto: Agent Browser available and preferred",probeMs:s,availability:o}:{backend:"playwright",reason:`auto: Agent Browser unavailable (${o.reason})`,probeMs:s,availability:o}}var lz,GA=h(()=>{"use strict";KA();lz=new Set(["daemon","subagent"])});import{createHash as dz}from"crypto";function XA(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&uz.test(t.label))}function zA(t){return dz("sha256").update(t,"utf8").digest("hex").slice(0,8)}function JA(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var uz,dd=h(()=>{"use strict";uz=/password|secret|token|api[_-]?key|otp|2fa/i});import{randomBytes as pz}from"crypto";import{mkdir as fz,stat as mz,writeFile as gz}from"fs/promises";import{join as yh}from"path";import{gzip as hz}from"zlib";import{promisify as yz}from"util";function bz(t){return yh(Ft(t),"browser")}function wz(t){return yh(bz(t),"screenshots")}function Sz(){return new Date().toISOString().replace(/[:.]/g,"-")}function kz(){return pz(3).toString("hex")}async function Do(t,e,n){if(e.length>VA)throw new Error(`writeScreenshotSidecar: buffer exceeds ${VA} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=wz(t);await fz(r,{recursive:!0});let o=`${Sz()}-${kz()}-${n}.png`,s=yh(r,o);await gz(s,e);let{size:i}=await mz(s);return{path:s,bytes:i}}var oge,VA,bh=h(()=>{"use strict";j();dd();oge=yz(hz);VA=5*1024*1024});var ud,YA=h(()=>{"use strict";ud=class{baseUrl;token;constructor(e){this.baseUrl=e.url,this.token=e.token}async call(e,n,r=3e4){let o={version:1,method:e,params:n},s=new AbortController,i=setTimeout(()=>s.abort(),r);try{let a=await fetch(`${this.baseUrl}/agent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,Host:new URL(this.baseUrl).host},body:JSON.stringify(o),signal:s.signal});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Agent Browser ${e} failed (HTTP ${a.status}): ${c}`)}return await a.json()}finally{clearTimeout(i)}}async listTabs(){return(await this.call("tabs.list",null)).tabs}async openTab(e){return{tabId:(await this.call("tabs.open",{url:e},6e4)).tab_id}}async closeTab(e){await this.call("tabs.close",{tab_id:e})}async read(e,n){return this.call("page.read",{tab_id:e,mode:n?.mode??"main",...n?.query?{query:n.query}:{},...n?.budget?{budget:n.budget}:{}})}async inspect(e,n){return this.call("page.inspect",{tab_id:e,mode:n?.mode??"interactive",...n?.query?{query:n.query}:{},...n?.limit?{limit:n.limit}:{}})}async click(e,n){await this.call("page.click",{tab_id:e,element_id:n})}async fill(e,n,r){await this.call("page.fill",{tab_id:e,element_id:n,value:r})}async press(e,n,r){await this.call("page.press",{tab_id:e,key:n,...r?{element_id:r}:{}})}async select(e,n,r){await this.call("page.select",{tab_id:e,element_id:n,value:r})}async waitFor(e,n,r){await this.call("page.wait",{tab_id:e,condition:n,...r?.value?{value:r.value}:{},...r?.timeout?{timeout:r.timeout}:{}},(r?.timeout??3e4)+5e3)}async evalScript(e,n){return this.call("page.eval",{tab_id:e,script:n})}async screenshot(e){return this.call("page.screenshot",{tab_id:e})}}});function wh(t){return{id:t.id,role:t.role,label:t.label,kind:t.kind,value:t.value,state:{disabled:t.disabled,...t.checked!==void 0?{checked:t.checked}:{},...t.selected!==void 0?{selected:t.selected}:{},...t.expanded!==void 0?{expanded:t.expanded}:{}},bbox:t.bbox,...t.selector?{selector:t.selector}:{}}}function QA(t,e){switch(e.kind){case"element_id":if(t.has(e.elementId))return e.elementId;throw new Error(`Element ${e.elementId} not found in current observation. Call browser_observe to refresh.`);case"selector":return null;case"semantic":return null}}async function Sh(t,e,n,r,o,s){switch(n){case"click":await t.click(e,r);break;case"fill":if(o===void 0)throw new Error("fill requires a value");await t.fill(e,r,o);break;case"press":if(o===void 0)throw new Error("press requires a value (key combo)");await t.press(e,o,r);break;case"select":if(o===void 0)throw new Error("select requires a value");await t.select(e,r,o);break;case"hover":throw new Error("hover is not supported by Agent Browser; use element_id from a prior observation to target clicks instead");case"scroll_to":{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');await t.evalScript(e,`document.querySelector('[data-element-id="${i}"]')?.scrollIntoView({behavior:'smooth',block:'center'})`);break}case"wait_for":await t.waitFor(e,"element",{value:r,timeout:s??1e4});break;default:throw new Error(`Unknown action: ${n}`)}}async function ZA(t,e){if(e.target.kind!=="semantic")throw new Error("resolveSemanticAndAct called with non-semantic target");let{elements:n}=await t.client.inspect(t.tabId,{mode:"interactive",query:e.target.text,limit:10}),r=n;if(e.target.role){let c=e.target.role.toLowerCase();r=n.filter(l=>l.role.toLowerCase()===c)}if(r.length===0)throw new Error(`No element found matching semantic target: text="${e.target.text}"`+(e.target.role?`, role="${e.target.role}"`:""));if(r.length>1)return{outcome:"ambiguous_target",query:{text:e.target.text,...e.target.role?{role:e.target.role}:{}},candidates:r.slice(0,5).map(wh)};let s=r[0].id;await Sh(t.client,t.tabId,e.action,s,e.value,e.timeoutMs);let i=await t.client.read(t.tabId,{mode:"main"}),a=Rt(i.url,t.config);return a.allowed?{elementId:s}:{outcome:"blocked_by_policy",url:i.url,reason:`action navigated to blocked domain: ${a.reason}`}}var ex=h(()=>{"use strict";On()});var tx={};Bs(tx,{AgentBrowserProvider:()=>kh});var kh,nx=h(()=>{"use strict";On();bh();YA();ex();kh=class{name="agent-browser";config;client;sessions=new Map;constructor(e,n){this.config=e,this.client=new ud(n)}async open(e){let n=Rt(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let r=this.sessions.get(e.sessionId);if(r)await this.client.evalScript(r.tabId,`window.location.href = ${JSON.stringify(e.url)}`),await this.client.waitFor(r.tabId,"load",{timeout:e.timeoutMs??3e4});else{let{tabId:i}=await this.client.openTab(e.url);await this.client.waitFor(i,"load",{timeout:e.timeoutMs??3e4}),r={tabId:i,observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null},this.sessions.set(e.sessionId,r)}let o=await this.client.read(r.tabId,{mode:"main"}),s=Rt(o.url,this.config);return s.allowed?this.buildObservation(r,e.sessionId,e.screenshot,void 0,"browser_open"):(await this.client.evalScript(r.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`redirected to blocked domain: ${s.reason}`})}async observe(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);return this.buildObservation(n,e.sessionId,e.screenshot,e.maxElements,"browser_observe")}async act(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);let r=QA(n.knownElements,e.target);if(r===null){if(e.target.kind==="semantic"){let i=await ZA({client:this.client,config:this.config,tabId:n.tabId},e);return"outcome"in i?i:(n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString(),this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"))}throw e.target.kind==="selector"?new Error("selector targets are not supported by Agent Browser; use element_id or semantic targets"):new Error(`Cannot resolve target: ${JSON.stringify(e.target)}`)}await Sh(this.client,n.tabId,e.action,r,e.value,e.timeoutMs),n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString();let o=await this.client.read(n.tabId,{mode:"main"}),s=Rt(o.url,this.config);return s.allowed?this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"):(await this.client.evalScript(n.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`action navigated to blocked domain: ${s.reason}`})}async render(e){throw new Error("AgentBrowserProvider does not support render(). Use PlaywrightProvider for one-shot content fetches.")}async screenshot(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);if(e.target!==void 0||e.fullPage)throw new Error("Agent Browser does not support element or full-page screenshots; omit target and fullPage.");let r=await this.client.screenshot(n.tabId),o=Buffer.from(r.data,"base64"),s=o.length>=24?o.readUInt32BE(16):0,i=o.length>=24?o.readUInt32BE(20):0;return{path:(await Do(e.sessionId,o,"browser_screenshot")).path,bytes:o.length,width:s,height:i,dataBase64:r.data,mediaType:"image/png"}}async extract(e){throw new Error("AgentBrowserProvider does not support extract() yet.")}async close(e){let n=this.sessions.get(e.sessionId);if(n){try{await this.client.closeTab(n.tabId)}catch{}this.sessions.delete(e.sessionId)}}describe(e){let n=this.sessions.get(e);return n?{active:!0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:1}:null}async shutdown(){let e=Array.from(this.sessions.entries()).map(async([,n])=>{try{await this.client.closeTab(n.tabId)}catch{}});await Promise.all(e),this.sessions.clear()}async buildObservation(e,n,r,o,s="browser_open"){let[i,a]=await Promise.all([this.client.read(e.tabId,{mode:"main",budget:4e3}),this.client.inspect(e.tabId,{mode:"interactive",limit:o??80})]),c=a.elements.map(wh),l=o??80,d=c.slice(0,l);e.observationCounter+=1,e.knownElements=new Map(d.map(g=>[g.id,g])),e.currentUrl=i.url,e.currentTitle=i.title;let u=[];c.length>l&&u.push(`page has ${c.length} interactive elements; showing first ${l}`);let p=null;if(r)try{let g=await this.client.screenshot(e.tabId),y=Buffer.from(g.data,"base64");p=(await Do(n,y,s)).path}catch{u.push("screenshot capture failed")}let f=`obs_${e.observationCounter.toString(36)}`,m={httpStatus:null,loadingState:"idle",hasDialog:!1,consoleErrors:0};return{observationId:f,url:i.url,title:i.title,textSummary:i.content.slice(0,4e3),interactive:d,status:m,warnings:u,screenshotPath:p,capturedAt:new Date().toISOString()}}}});import{existsSync as vz,readFileSync as Tz}from"node:fs";import{createRequire as Ez}from"node:module";import{dirname as _z,join as Az}from"node:path";function sx(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<Rz&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function ze(t){let e=sx(t);return ox.some(n=>e.includes(n))}function Iz(){try{let e=Ez(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(Tz(e,"utf8"));if(typeof n!="object"||n===null)return;let r=n.bin,o=typeof r=="string"?r:typeof r=="object"&&r!==null?r.playwright:void 0;if(typeof o!="string"||o.length===0)return;let s=Az(_z(e),o);return vz(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function ji(){return rx??=Iz()??xz,rx}function vh(t){return t.includes("install chromium")}function mt(t,e){let n=sx(t),r=e?.latched===!0?` ${Cz}`:"";if(n.includes("Executable doesn't exist")){let o="";return e?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":e?.headless===!1&&(o=" This launch was headed, which needs the full `chromium-*` build \u2014 the headless shell alone does not satisfy it."),`browser tools require the Playwright chromium binary. Install via: ${ji()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${ji()}). Or pick a different tool.${r}`}function pd(t,e,n=!1){if(!ze(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
321
321
 
322
- ${mt(t,{headless:e,latched:n})}`,{cause:t})}var ox,xz,Rz,rx,Cz,Th=h(()=>{"use strict";ox=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],xz="pnpm exec playwright install chromium",Rz=4;Cz="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Cr from"node:fs";import fd from"node:path";import{randomBytes as Pz}from"node:crypto";function Mz(){try{return"5.185.0"}catch{}try{let t=fd.resolve(import.meta.dirname,"../../../package.json"),e=Cr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Oz,md,ix=h(()=>{"use strict";Th();j();ie();Oz=Mz(),md=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=(async()=>{let e;try{({chromium:e}=await import("playwright"))}catch(n){let r=pd(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await e.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=pd(n,this.config.headless,!0);throw this.latchLaunchFailure(r),r}finally{this.launchPromise=void 0}})(),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${Oz}`}}loadStorageState(e){let n=dm(e);try{if(!Cr.existsSync(n))return;let r=JSON.parse(Cr.readFileSync(n,"utf8"));return D("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){D("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=dm(e);if(!Cr.existsSync(r))return;let o=await n.storageState(),s=fd.join(fd.dirname(r),`.${fd.basename(r)}.${process.pid}.${Pz(4).toString("hex")}.tmp`);Cr.writeFileSync(s,JSON.stringify(o),{mode:384}),Cr.chmodSync(s,384),Cr.renameSync(s,r),D("[browser/vault] saved session",{profile:e,file:r})}catch(r){D("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as Dz}from"node:crypto";function Fz(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Lz(t,e,n){return`el_${Dz("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Nz(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function ax(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function lx(t,e){let n=t.role??"",r=t.name??"";cx.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])lx(s,e)}async function $z(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},dx).catch(()=>[])}async function Uz(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},dx).catch(()=>[])}function Bz(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function gd(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=Bz(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=$z(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],lx(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await Uz(t)).filter(P=>cx.has(P.role??"")));let S=new Map;for(let C of p){let P=ax(C.name),q=S.get(P);(!q||q.bbox.w===0&&C.bbox.w>0)&&S.set(P,C)}let T=y.map(C=>({ax:C,dom:S.get(ax(C.name??""))})),_=r?T:T.filter(C=>C.dom?C.dom.bbox.w>0||C.dom.bbox.h>0:!0);_.sort((C,P)=>{let q=C.dom?.bbox.y??0,M=P.dom?.bbox.y??0;if(q!==M)return q-M;let B=C.dom?.bbox.x??0,F=P.dom?.bbox.x??0;return B-F}),_.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=_.slice(0,n).map((C,P)=>{let q=C.ax.role??"generic",M=C.ax.name??"",B=Lz(q,M,P),F=C.dom?.bbox??{x:0,y:0,w:0,h:0},N=C.dom?.type??null,U=null;C.ax.value!==void 0&&C.ax.value!==null&&(U=String(C.ax.value)),C.ax.checked!==void 0&&(U=String(C.ax.checked)),XA({role:q,kind:N})&&(U="[redacted]");let W={disabled:C.ax.disabled??!1};C.ax.checked!==void 0&&(W.checked=C.ax.checked===!0||C.ax.checked==="mixed"),C.ax.selected!==void 0&&(W.selected=C.ax.selected),C.ax.expanded!==void 0&&(W.expanded=C.ax.expanded);let Y;C.dom?.testId?Y=`[data-testid="${C.dom.testId}"]`:C.dom?.id&&(Y=`#${C.dom.id}`);let We={id:B,role:q,label:Fz(M),kind:N,value:U,state:W,bbox:F};return Y!==void 0&&(We.selector=Y),We}),R="idle";try{let C=await t.evaluate(()=>document.readyState);C==="loading"?R="loading":C==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=Nz(f),k=`obs_${e.observationCounter.toString(36)}`,x=new Date().toISOString();return{observationId:k,url:m,title:g,textSummary:I,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:x}}var cx,dx,ux=h(()=>{"use strict";dd();cx=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);dx="a[href], button, input, select, textarea, [role], [tabindex], label"});async function px(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Eh(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>px(t,s)))).filter(o=>o!==null)}async function jz(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function _h(t,e,n){switch(e.kind){case"element_id":return Hz(t,e,n);case"selector":return Wz(t,e);case"semantic":return Kz(t,e)}}async function Hz(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Eh(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Wz(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Eh(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Kz(t,e){return e.role!==void 0?qz(t,e.text,e.role):Gz(t,e.text,e)}async function qz(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Eh(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Gz(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await jz(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let y=p[g];if(y===void 0)continue;let b=await px(y.locator,y.index);if(b!==null){let S=`${b.role}:${b.label}:${g}`,T=0;for(let _=0;_<S.length;_++)T=T*31+S.charCodeAt(_)>>>0;f.push({...b,id:`el_${T.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var fx=h(()=>{"use strict"});async function Ah(t,e,n,r){let o=t.url();if(o===n)return null;let s=Rt(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var mx=h(()=>{"use strict";On()});var Rh={};Bs(Rh,{PlaywrightProvider:()=>xh});function gx(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var xh,Ih=h(()=>{"use strict";ix();ux();fx();On();mx();bh();xh=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new md(e)}async open(e){let n=Rt(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await Ah(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await gd(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await gd(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await _h(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${gx(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(y){l=y}else l=g}let u=await Ah(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await gd(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await _h(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${gx(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await Do(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Do(n,o,r);return s}catch{return null}}}});var Mr={};Bs(Mr,{__resetBrowserRegistryForTests:()=>Qz,browserProviderActive:()=>Jz,closeBrowserProvider:()=>Ph,getBrowserProvider:()=>zz,getLastRoutingDecision:()=>Yz,peekBrowserProvider:()=>Vz});function hx(){Promise.resolve(Ph()).then(()=>{process.exit(130)})}function yx(){Promise.resolve(Ph()).then(()=>{process.exit(143)})}function bx(){Gt=null}function Xz(){hd||(process.on("SIGINT",hx),process.on("SIGTERM",yx),process.on("exit",bx),hd=!0)}function wx(){hd&&(process.removeListener("SIGINT",hx),process.removeListener("SIGTERM",yx),process.removeListener("exit",bx),hd=!1)}async function zz(t){return Gt!==null?Gt:(Pr!==null||(Pr=(async()=>{let e=mh(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??v.AGENT_SURFACE,r=await qA({config:e,surface:n});Ch=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(nx(),tx)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(Ih(),Rh));o=new s(e)}return Xz(),Gt=o,Pr=null,o})()),Pr)}async function Ph(){if(Gt===null)return;let t=Gt;Gt=null,Pr=null,wx(),await t.shutdown()}function Jz(){return Gt!==null}function Vz(){return Gt}function Yz(){return Ch}function Qz(){Gt=null,Pr=null,Ch=null,wx()}var Gt,Pr,hd,Ch,Or=h(()=>{"use strict";On();GA();L();Gt=null,Pr=null,hd=!1,Ch=null});async function Sx(t,e){try{return await MA(t,e)}catch(n){return D("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function oJ(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Or(),Mr)),r=await n();try{return await r.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(Ih(),Rh)),{loadBrowserConfig:i}=await Promise.resolve().then(()=>(On(),gh)),a=i(),c=new s(a);try{return await c.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}finally{await c.shutdown()}}throw o}}async function kx(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??oJ,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await Mn(n,t,{headers:rJ,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(nJ.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(tJ.test(p)&&!eJ.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await Sx(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof Ie||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(s===null||s.textLength<200)&&s!==null){let u=dh({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Bi(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>Bi(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await Bi(u.finalUrl,o);let p=await Sx(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=dh({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(e.signal.aborted||u instanceof Ie)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=l instanceof Error?l.message:`HTTP ${c??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${c??"error"}).`)}var eJ,tJ,nJ,rJ,vx=h(()=>{"use strict";OA();uh();Ir();ie();eJ=/(text\/html|application\/xhtml\+xml)/i,tJ=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,nJ=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,rJ={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function aJ(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(sJ,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),iJ),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=Z(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function Tx(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?aJ({apiKey:t.exaApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function Ex(t,e){if(e.length===0)return`# Search results for "${t}"
322
+ ${mt(t,{headless:e,latched:n})}`,{cause:t})}var ox,xz,Rz,rx,Cz,Th=h(()=>{"use strict";ox=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],xz="pnpm exec playwright install chromium",Rz=4;Cz="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import Cr from"node:fs";import fd from"node:path";import{randomBytes as Pz}from"node:crypto";function Mz(){try{return"5.186.0"}catch{}try{let t=fd.resolve(import.meta.dirname,"../../../package.json"),e=Cr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Oz,md,ix=h(()=>{"use strict";Th();j();ie();Oz=Mz(),md=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=(async()=>{let e;try{({chromium:e}=await import("playwright"))}catch(n){let r=pd(n,this.config.headless,!0);throw this.latchLaunchFailure(r),this.launchPromise=void 0,r}try{let n=await e.launch({headless:this.config.headless});return this.browser=n,this.clearLaunchFailure(),n}catch(n){let r=pd(n,this.config.headless,!0);throw this.latchLaunchFailure(r),r}finally{this.launchPromise=void 0}})(),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(e){let n=this.sessions.get(e);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),s=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),i={context:s,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(e,i),s}async ensurePage(e){let n=this.sessions.get(e);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(e);let r=this.sessions.get(e);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${e}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",s=>{s.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",s=>{s.isNavigationRequest()&&s.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",s=>{s.frame()===o.mainFrame()&&s.request().isNavigationRequest()&&(r.lastHttpStatus=s.status())}),o.on("dialog",s=>{r.openDialog=s}),o}getPage(e){return this.sessions.get(e)?.page}async renderHtml(e,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${Oz}`}}loadStorageState(e){let n=dm(e);try{if(!Cr.existsSync(n))return;let r=JSON.parse(Cr.readFileSync(n,"utf8"));return D("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){D("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=dm(e);if(!Cr.existsSync(r))return;let o=await n.storageState(),s=fd.join(fd.dirname(r),`.${fd.basename(r)}.${process.pid}.${Pz(4).toString("hex")}.tmp`);Cr.writeFileSync(s,JSON.stringify(o),{mode:384}),Cr.chmodSync(s,384),Cr.renameSync(s,r),D("[browser/vault] saved session",{profile:e,file:r})}catch(r){D("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as Dz}from"node:crypto";function Fz(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Lz(t,e,n){return`el_${Dz("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Nz(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function ax(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function lx(t,e){let n=t.role??"",r=t.name??"";cx.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])lx(s,e)}async function $z(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},dx).catch(()=>[])}async function Uz(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},dx).catch(()=>[])}function Bz(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function gd(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=Bz(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=$z(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],lx(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await Uz(t)).filter(P=>cx.has(P.role??"")));let S=new Map;for(let C of p){let P=ax(C.name),q=S.get(P);(!q||q.bbox.w===0&&C.bbox.w>0)&&S.set(P,C)}let T=y.map(C=>({ax:C,dom:S.get(ax(C.name??""))})),_=r?T:T.filter(C=>C.dom?C.dom.bbox.w>0||C.dom.bbox.h>0:!0);_.sort((C,P)=>{let q=C.dom?.bbox.y??0,M=P.dom?.bbox.y??0;if(q!==M)return q-M;let B=C.dom?.bbox.x??0,F=P.dom?.bbox.x??0;return B-F}),_.length>200&&o.push("page has 200+ interactive elements; consider scoping");let E=_.slice(0,n).map((C,P)=>{let q=C.ax.role??"generic",M=C.ax.name??"",B=Lz(q,M,P),F=C.dom?.bbox??{x:0,y:0,w:0,h:0},N=C.dom?.type??null,U=null;C.ax.value!==void 0&&C.ax.value!==null&&(U=String(C.ax.value)),C.ax.checked!==void 0&&(U=String(C.ax.checked)),XA({role:q,kind:N})&&(U="[redacted]");let W={disabled:C.ax.disabled??!1};C.ax.checked!==void 0&&(W.checked=C.ax.checked===!0||C.ax.checked==="mixed"),C.ax.selected!==void 0&&(W.selected=C.ax.selected),C.ax.expanded!==void 0&&(W.expanded=C.ax.expanded);let Y;C.dom?.testId?Y=`[data-testid="${C.dom.testId}"]`:C.dom?.id&&(Y=`#${C.dom.id}`);let We={id:B,role:q,label:Fz(M),kind:N,value:U,state:W,bbox:F};return Y!==void 0&&(We.selector=Y),We}),R="idle";try{let C=await t.evaluate(()=>document.readyState);C==="loading"?R="loading":C==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let I=Nz(f),k=`obs_${e.observationCounter.toString(36)}`,x=new Date().toISOString();return{observationId:k,url:m,title:g,textSummary:I,interactive:E,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:x}}var cx,dx,ux=h(()=>{"use strict";dd();cx=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);dx="a[href], button, input, select, textarea, [role], [tabindex], label"});async function px(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Eh(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>px(t,s)))).filter(o=>o!==null)}async function jz(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function _h(t,e,n){switch(e.kind){case"element_id":return Hz(t,e,n);case"selector":return Wz(t,e);case"semantic":return Kz(t,e)}}async function Hz(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Eh(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Wz(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Eh(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Kz(t,e){return e.role!==void 0?qz(t,e.text,e.role):Gz(t,e.text,e)}async function qz(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Eh(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Gz(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await jz(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let y=p[g];if(y===void 0)continue;let b=await px(y.locator,y.index);if(b!==null){let S=`${b.role}:${b.label}:${g}`,T=0;for(let _=0;_<S.length;_++)T=T*31+S.charCodeAt(_)>>>0;f.push({...b,id:`el_${T.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var fx=h(()=>{"use strict"});async function Ah(t,e,n,r){let o=t.url();if(o===n)return null;let s=Rt(o,e);if(s.allowed)return null;try{await t.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:s.reason}}var mx=h(()=>{"use strict";On()});var Rh={};Bs(Rh,{PlaywrightProvider:()=>xh});function gx(t){switch(t.kind){case"semantic":return t.role!==void 0?`semantic('${t.text}', role='${t.role}')`:`semantic('${t.text}')`;case"element_id":return`element_id(${t.elementId})`;case"selector":return`selector(${t.selector})`}}var xh,Ih=h(()=>{"use strict";ix();ux();fx();On();mx();bh();xh=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new md(e)}async open(e){let n=Rt(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await Ah(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await gd(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await gd(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await _h(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${gx(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(y){l=y}else l=g}let u=await Ah(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await gd(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await _h(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${gx(e.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await d.locator.screenshot()}else s=await r.screenshot({fullPage:e.fullPage??!1});let{path:i,bytes:a}=await Do(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Do(n,o,r);return s}catch{return null}}}});var Mr={};Bs(Mr,{__resetBrowserRegistryForTests:()=>Qz,browserProviderActive:()=>Jz,closeBrowserProvider:()=>Ph,getBrowserProvider:()=>zz,getLastRoutingDecision:()=>Yz,peekBrowserProvider:()=>Vz});function hx(){Promise.resolve(Ph()).then(()=>{process.exit(130)})}function yx(){Promise.resolve(Ph()).then(()=>{process.exit(143)})}function bx(){Gt=null}function Xz(){hd||(process.on("SIGINT",hx),process.on("SIGTERM",yx),process.on("exit",bx),hd=!0)}function wx(){hd&&(process.removeListener("SIGINT",hx),process.removeListener("SIGTERM",yx),process.removeListener("exit",bx),hd=!1)}async function zz(t){return Gt!==null?Gt:(Pr!==null||(Pr=(async()=>{let e=mh(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??v.AGENT_SURFACE,r=await qA({config:e,surface:n});Ch=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(nx(),tx)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(Ih(),Rh));o=new s(e)}return Xz(),Gt=o,Pr=null,o})()),Pr)}async function Ph(){if(Gt===null)return;let t=Gt;Gt=null,Pr=null,wx(),await t.shutdown()}function Jz(){return Gt!==null}function Vz(){return Gt}function Yz(){return Ch}function Qz(){Gt=null,Pr=null,Ch=null,wx()}var Gt,Pr,hd,Ch,Or=h(()=>{"use strict";On();GA();L();Gt=null,Pr=null,hd=!1,Ch=null});async function Sx(t,e){try{return await MA(t,e)}catch(n){return D("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function oJ(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Or(),Mr)),r=await n();try{return await r.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(Ih(),Rh)),{loadBrowserConfig:i}=await Promise.resolve().then(()=>(On(),gh)),a=i(),c=new s(a);try{return await c.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}finally{await c.shutdown()}}throw o}}async function kx(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??oJ,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await Mn(n,t,{headers:rJ,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(nJ.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(tJ.test(p)&&!eJ.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await Sx(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof Ie||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(s===null||s.textLength<200)&&s!==null){let u=dh({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Bi(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>Bi(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await Bi(u.finalUrl,o);let p=await Sx(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=dh({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(e.signal.aborted||u instanceof Ie)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=l instanceof Error?l.message:`HTTP ${c??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${c??"error"}).`)}var eJ,tJ,nJ,rJ,vx=h(()=>{"use strict";OA();uh();Ir();ie();eJ=/(text\/html|application\/xhtml\+xml)/i,tJ=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,nJ=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,rJ={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/web_scrape",Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"}});function aJ(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(sJ,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":t.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),iJ),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=Z(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function Tx(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?aJ({apiKey:t.exaApiKey,fetchFn:t.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function Ex(t,e){if(e.length===0)return`# Search results for "${t}"
323
323
 
324
324
  (no results)`;let n=[`# Search results for "${t}"`,""];return e.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
325
325
  `).trimEnd()}var sJ,iJ,_x=h(()=>{"use strict";it();sJ="https://api.exa.ai/search",iJ=10});function yd(t){if(t instanceof Error&&t.name==="TimeoutError")return"timeout";let e=t instanceof Error?t.message:String(t);return/Timeout\s+\d+\s*ms exceeded/i.test(e)?"timeout":void 0}var Dr=h(()=>{"use strict";Th()});function fJ(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=cJ;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(e.timeout_ms,lJ)}let a=dJ;if(e.max_bytes!==void 0){if(typeof e.max_bytes!="number"||!Number.isFinite(e.max_bytes)||e.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(e.max_bytes,uJ)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Mh(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:Et(t,e),truncated:!0}}function mJ(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env,r=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{};return async(o,s)=>{if(typeof e!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let i=fJ(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let u=s.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let a=new AbortController,c=()=>{a.abort(s.reason)},l,d=()=>{let u=a.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(s.addEventListener("abort",c,{once:!0}),l=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${i.timeoutMs}ms`))},i.timeoutMs),i.url!==void 0){let p=await Rr(i.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(!p.allowed)return{content:`web_scrape blocked: ${p.reason}`,isError:!0}}if(i.mode==="raw"){let p;try{let g={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await Mn(e,i.url,g,r)}catch(g){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:g instanceof Ie?{content:`web_scrape blocked: ${g.message}`,isError:!0}:{content:`web_scrape network error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${i.url}`,isError:!0};let f;try{f=await p.text()}catch(g){return{content:`web_scrape read error: ${g instanceof Error?g.message:String(g)}`,isError:!0}}let m=Mh(f,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let p=await kx(i.url,{fetchFn:e,renderFn:t.renderFn,timeoutMs:i.timeoutMs,signal:a.signal,...t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{}});if(p.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${i.url}.`,isError:!0};let f=Mh(DA(p.markdown,p.advisory),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(p instanceof Ie)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),m=ze(p)&&!vh(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${ji()}\`)`:"";return{content:`web_scrape markdown error: ${f}${m}`,isError:!0}}let u=Tx({exaApiKey:n.EXA_API_KEY,fetchFn:e});if("error"in u)return{content:u.error,isError:!0};try{let p=await u.search(i.query,{limit:pJ,timeoutMs:i.timeoutMs,signal:a.signal}),f=Mh(Ex(i.query,p),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${p instanceof Error?p.message:String(p)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),s.removeEventListener("abort",c)}}}var cJ,lJ,dJ,uJ,pJ,Ax,xx=h(()=>{"use strict";vx();_x();Ir();jt();uh();Dr();cJ=3e4,lJ=12e4,dJ=1e5,uJ=1e6,pJ=10;Ax=mJ()});function yJ(t){return gJ.has(t)?"low":t==="DELETE"?"high":"medium"}function bJ(t){return hJ.has(t)}function kJ(t){let e={};return t.forEach((n,r)=>{let o=r.toLowerCase();SJ.has(o)||wJ.some(s=>o.startsWith(s))||(e[r]=n)}),e}function vJ(t,e){if(t==null)return{serialized:void 0,inferredContentType:void 0};let n=Object.keys(e).some(o=>o.toLowerCase()==="content-type");return typeof t=="string"?{serialized:t,inferredContentType:n?void 0:"text/plain"}:{serialized:JSON.stringify(t),inferredContentType:n?void 0:"application/json"}}function TJ(t,e,n){let r=Buffer.byteLength(t,"utf8"),o=t,s=!1;if(r>n&&(o=Et(t,n),s=!0),!s&&/application\/json/i.test(e))try{return{body:JSON.parse(o),truncated:!1}}catch{}return{body:o,truncated:s}}async function Cx(t){let{url:e,method:n,signal:r,domainCheck:o,recordEffect:s}=t,i=Math.min(t.maxResponseBytes??Oh,Dh),a={...t.headers},c=t.fetchFn??globalThis.fetch,l=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},d=yJ(n);if(o!==void 0){let k=o(e);if(!k.allowed)throw Object.assign(new Error(`web_request blocked by domain policy: ${k.reason}`),{name:"DomainPolicyError"})}let u=await Rr(e,l);if(!u.allowed)throw new Ie(u.reason);let{serialized:p,inferredContentType:f}=vJ(t.body,a);f!==void 0&&(a["content-type"]=f);let m={method:n,headers:Object.keys(a).length>0?a:void 0,body:p,signal:r},y=bJ(n)?{retries:2,baseDelayMs:300,maxDelayMs:5e3}:{retries:0},b=Date.now(),S;try{S=await Mn(c,e,m,{...l,retry:y})}catch(k){throw k instanceof Ie,k}let T=Date.now()-b,_=S.headers.get("content-type")??"",A;try{let k=S.body?.getReader();if(!k)A="";else{let x=[],C=0,P=i*2;for(;;){let{done:q,value:M}=await k.read();if(q||!M)break;if(x.push(M),C+=M.byteLength,C>=P){await k.cancel();break}}A=new TextDecoder().decode(Buffer.concat(x,C))}}catch{A=""}let{body:E,truncated:R}=TJ(A,_,i),I=kJ(S.headers);return s!==void 0&&Promise.resolve(s({url:e,method:n,status:S.status,risk:d,timing_ms:T})).catch(()=>{}),{status:S.status,headers:I,body:E,truncated:R,timing_ms:T,risk:d}}function Px(t){if(typeof t!="string"||t.trim().length===0)return{error:"method must be a non-empty string (GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS)"};let e=t.trim().toUpperCase(),n=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"];return n.includes(e)?e:{error:`method "${t}" is not supported \u2014 must be one of: ${n.join(", ")}`}}var Rx,Ix,Oh,Dh,gJ,hJ,wJ,SJ,Mx=h(()=>{"use strict";Ir();jt();Rx=3e4,Ix=12e4,Oh=1e5,Dh=1e6,gJ=new Set(["GET","HEAD","OPTIONS"]),hJ=new Set(["GET","HEAD","OPTIONS","PUT","DELETE"]);wJ=["set-cookie","x-"],SJ=new Set(["server","via","age","vary","authorization","www-authenticate"])});function EJ(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t;if(typeof e.url!="string"||e.url.length===0)return{error:'Invalid input: "url" must be a non-empty string'};let n;try{n=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(n.protocol!=="http:"&&n.protocol!=="https:")return{error:`Invalid input: protocol "${n.protocol}" not supported (http/https only)`};n.username="",n.password="";let r=n.toString(),o=Px(e.method);if(typeof o=="object"&&"error"in o)return{error:`Invalid input: ${o.error}`};let s=o,i;if(e.body!==void 0&&e.body!==null){if(typeof e.body!="string"&&typeof e.body!="object")return{error:'Invalid input: "body" must be a string, object, or array'};i=e.body}let a={};if(e.headers!==void 0){if(typeof e.headers!="object"||e.headers===null||Array.isArray(e.headers))return{error:'Invalid input: "headers" must be a string-keyed object'};let u=e.headers;for(let[p,f]of Object.entries(u)){if(typeof f!="string")return{error:`Invalid input: header value for "${p}" must be a string`};a[p]=f}}let c=Rx;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'Invalid input: "timeout_ms" must be a positive finite number'};c=Math.min(e.timeout_ms,Ix)}let l=Oh;if(e.max_response_bytes!==void 0){if(typeof e.max_response_bytes!="number"||!Number.isFinite(e.max_response_bytes)||e.max_response_bytes<=0)return{error:'Invalid input: "max_response_bytes" must be a positive finite number'};l=Math.min(e.max_response_bytes,Dh)}let d;if(e.credential!==void 0){if(typeof e.credential!="string"||e.credential.length===0)return{error:'Invalid input: "credential" must be a non-empty string (an env var name)'};d=e.credential}return{url:r,method:s,body:i,headers:a,timeoutMs:c,maxResponseBytes:l,credential:d}}function _J(t={}){let e=t.fetchFn??globalThis.fetch,n=t.env??process.env;async function r(){if(t.domainCheck!==void 0)return t.domainCheck;try{let{loadBrowserConfig:o,enforceDomainPolicy:s}=await Promise.resolve().then(()=>(On(),gh)),i=o();return a=>s(a,i)}catch{return}}return async(o,s)=>{if(typeof e!="function")return{content:"web_request unavailable: global fetch() is not present (agent-afk requires Node 20+).",isError:!0};let i=EJ(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let p=s.reason;return{content:`web_request aborted: ${p instanceof Error?p.message:String(p??"aborted")}`,isError:!0}}let a={...i.headers};if(i.credential!==void 0){let p=n[i.credential];if(p===void 0||p.trim().length===0)return{content:`web_request credential error: environment variable "${i.credential}" is not set. Set it in afk.env or export it in the shell before starting AFK.`,isError:!0};if(Object.keys(a).some(m=>m.toLowerCase()==="authorization"))return{content:'web_request credential error: both "credential" and an explicit Authorization header were provided. Use one or the other.',isError:!0};a.Authorization=`Bearer ${p}`}let c=new AbortController,l=()=>c.abort(s.reason),d,u=()=>{let p=c.signal.reason;return p instanceof Error?p.message:String(p??"aborted")};try{s.addEventListener("abort",l,{once:!0}),d=setTimeout(()=>{c.abort(new Error(`web_request timeout after ${i.timeoutMs}ms`))},i.timeoutMs);let p=await r(),f={url:i.url,method:i.method,body:i.body,headers:a,maxResponseBytes:i.maxResponseBytes,signal:c.signal,fetchFn:e,lookupFn:t.lookupFn,domainCheck:p,recordEffect:t.recordEffect},m;try{m=await Cx(f)}catch(S){if(c.signal.aborted)return{content:`web_request aborted: ${u()}`,isError:!0};if(S instanceof Ie)return{content:`web_request blocked: ${S.message}`,isError:!0};let T=S instanceof Error&&S.name==="DomainPolicyError"?"blocked":"network error",_=S instanceof Error?S.message:String(S);return{content:`web_request ${T}: ${_}`,isError:!0}}if(c.signal.aborted)return{content:`web_request aborted: ${u()}`,isError:!0};let g=m.body;if(typeof g=="string")g=qe(g);else if(typeof g=="object"&&g!==null){let S=qe(JSON.stringify(g));try{g=JSON.parse(S)}catch{g=S}}let y={status:m.status,headers:m.headers,body:g,timing_ms:m.timing_ms,...m.truncated?{truncated:!0}:{}};return{content:JSON.stringify(y,null,2),...m.truncated?{truncated:!0}:{}}}finally{d!==void 0&&clearTimeout(d),s.removeEventListener("abort",l)}}}var Ox,Dx=h(()=>{"use strict";Mx();Ir();kn();Ox=_J()});import{existsSync as Lx,mkdirSync as AJ,readFileSync as xJ,renameSync as RJ,unlinkSync as IJ,writeFileSync as CJ}from"node:fs";import{dirname as Fx,join as PJ}from"node:path";import{randomBytes as MJ}from"node:crypto";function Fr(t){let e=t??rm();if(!Lx(e))return[];try{let n=xJ(e,"utf-8");return JSON.parse(n)}catch(n){let r=n instanceof Error?n.message:String(n);return console.error(`[schedule-store] failed to parse ${e}: ${r}`),[]}}function Hi(t,e){let n=e??rm();AJ(Fx(n),{recursive:!0});let r=PJ(Fx(n),`.schedules.json.${process.pid}.${MJ(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{CJ(r,o,"utf-8"),RJ(r,n)}catch(s){try{Lx(r)&&IJ(r)}catch{}throw s}}function Nx(t,e){let n=Fr(e),r=n.map(c=>c.id),o=OJ(t.name),s=DJ(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),Hi(n,e),a}function $x(t,e){let n=Fr(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(Hi(o,e),!0)}function Ux(t,e){return Fr(e).find(n=>n.id===t)}function OJ(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function DJ(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}function Bx(t){return{taskId:t.id,command:t.command,trigger:t.trigger??"cron",...t.cron!==void 0?{cronExpression:t.cron}:{},...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{},...t.notifyChat!==void 0?{notifyChat:t.notifyChat}:{}}}var jx=h(()=>{"use strict";j()});import{existsSync as FJ,readFileSync as LJ}from"node:fs";import{join as NJ}from"node:path";async function Fo(t,e,n){let r,o;try{let s=NJ(Mk("default"),"port");if(!FJ(s))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=LJ(s,"utf-8").trim(),a=$J(i);if(!a)return{synced:!1,detail:"daemon-not-detected (invalid port file)"};({host:r,port:o}=a)}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let s=r.includes(":")?`[${r}]`:r,i=await fetch(`http://${s}:${o}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return i.ok?{synced:!0,detail:"synced"}:t==="POST"&&i.status===409?{synced:!0,detail:"already-registered"}:t==="DELETE"&&i.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${i.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}function $J(t){let e=parseInt(t,10);if(String(e)===t&&!Number.isNaN(e))return e<1||e>65535?null:{host:"localhost",port:e};let n=t.lastIndexOf(":");if(n<1)return null;let r=t.slice(0,n),o=t.slice(n+1);if(!/^\d+$/.test(o))return null;let s=parseInt(o,10);return Number.isNaN(s)||s<1||s>65535||/^:+$/.test(r)?null:{host:r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,port:s}}var Fh,Hx=h(()=>{"use strict";j();Fh="Change saved to schedules.json, but a running daemon (if any) did not pick it up \u2014 it will apply on the next daemon (re)start."});import{existsSync as UJ}from"node:fs";import{readFile as BJ}from"node:fs/promises";var Wx,Kx,qx,Gx,Xx=h(()=>{"use strict";jx();j();Hx();Wx=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.name!="string"||!n.name)return{content:"Invalid input: name required",isError:!0};if(typeof n.command!="string"||!n.command)return{content:"Invalid input: command required",isError:!0};if(typeof n.cron!="string"||!n.cron)return{content:"Invalid input: cron required",isError:!0};let r=n.cron.trim().split(/\s+/);if(r.length!==5&&r.length!==6)return{content:"Invalid input: cron must be a 5 or 6-field expression",isError:!0};let o=n.notifyChat;if(o!==void 0&&typeof o!="number"&&typeof o!="string")return{content:"Invalid input: notifyChat must be a number (chat id) or string (chat id or alias name)",isError:!0};let s=Nx({name:n.name,command:n.command,cron:n.cron,trigger:n.trigger??"cron",notifyOn:n.notifyOn,...o!==void 0?{notifyChat:o}:{},enabled:typeof n.enabled=="boolean"?n.enabled:!0}),i=s.enabled?await Fo("POST","/tasks",{taskId:s.id,command:s.command,cron:s.cron,trigger:s.trigger,notifyOn:s.notifyOn,...s.notifyChat!==void 0?{notifyChat:s.notifyChat}:{}}):await Fo("DELETE",`/tasks/${s.id}`);return{content:JSON.stringify({id:s.id,name:s.name,cron:s.cron,enabled:s.enabled,daemonSynced:i.synced,syncDetail:i.detail,...i.synced?{}:{syncNote:Fh}})}},Kx=async(t,e)=>{let n=Fr();return{content:JSON.stringify(n.map(r=>({id:r.id,name:r.name,cron:r.cron,trigger:r.trigger,enabled:r.enabled,notifyOn:r.notifyOn})))}},qx=async(t,e)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected object",isError:!0};let n=t;if(typeof n.taskId!="string"||!n.taskId)return{content:"Invalid input: taskId required",isError:!0};let r=n.taskId,o=typeof n.limit=="number"?Math.min(Math.max(1,n.limit),50):10,s=Sc();if(!UJ(s))return{content:JSON.stringify([])};let i;try{let l=await BJ(s);i=(l.length>1048576?l.subarray(l.length-1048576):l).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
@@ -348,10 +348,10 @@ ${mt(t,{headless:e,latched:n})}`,{cause:t})}var ox,xz,Rz,rx,Cz,Th=h(()=>{"use st
348
348
  `),this.errored=!0}}async close(e){if(!this.closed)return this.record({kind:"closed",...e!==void 0?{reason:e}:{}}),this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(n=>{if(!this.stream){n();return}this.stream.end(()=>n())})}};qV=250});import{readdir as GV,stat as XV}from"node:fs/promises";import{join as zV}from"node:path";async function oy(){let t=Ks(),e;try{e=await GV(t)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of e){let o=zV(t,r,"trace.jsonl");try{let s=await XV(o);s.isFile()&&n.push({sessionId:r,tracePath:o,mtimeMs:s.mtimeMs,exists:!0})}catch{}}return n.sort((r,o)=>o.mtimeMs-r.mtimeMs),n}async function eI(){return(await oy())[0]?.sessionId??null}var tI=h(()=>{"use strict";j()});import{existsSync as JV,readdirSync as VV,readFileSync as YV}from"node:fs";import{basename as QV,join as ZV}from"node:path";function t4(t){try{let e=JSON.parse(YV(t,"utf-8"));if(typeof e!="object"||e===null)return;let n=e;return{sessionId:typeof n.sessionId=="string"?n.sessionId:void 0,name:typeof n.name=="string"?n.name:void 0,savedAt:typeof n.savedAt=="number"?n.savedAt:void 0}}catch{return}}function n4(t){if(!JV(t))return[];let e;try{e=VV(t)}catch{return[]}let n=[];for(let r of e){if(!r.endsWith(".json"))continue;let o=ZV(t,r),s=t4(o);s&&n.push({sidecarId:QV(r,".json"),filePath:o,data:s})}return n}function Fd(t,e=ce()){let n=n4(e);n.sort((r,o)=>{let s=r.data.savedAt??-1/0;return(o.data.savedAt??-1/0)-s});for(let r of n){if(r.sidecarId===t)return{sessionId:r.data.sessionId??r.sidecarId,sidecarId:r.sidecarId,reason:"exact-id"};if(r.data.sessionId===t)return{sessionId:r.data.sessionId,sidecarId:r.sidecarId,reason:"exact-session-id"};if(r.data.name===t)return{sessionId:r.data.sessionId??r.sidecarId,sidecarId:r.sidecarId,reason:"exact-name"}}if(t.length>=e4){let r=n.filter(o=>o.data.name!==void 0&&o.data.name.startsWith(t));if(r.length===1){let o=r[0];return{sessionId:o.data.sessionId??o.sidecarId,sidecarId:o.sidecarId,reason:"prefix-name"}}}}var e4,sy=h(()=>{"use strict";j();e4=3});import{existsSync as r4}from"node:fs";import{readFile as o4}from"node:fs/promises";async function iy(t){if(!r4(t))return{content:"",truncated:!1};try{let e=await o4(t);if(e.length<=nI)return{content:e.toString("utf-8"),truncated:!1};let n=e.subarray(e.length-nI),r=n.indexOf(10);return r!==-1&&(n=n.subarray(r+1)),{content:n.toString("utf-8"),truncated:!0}}catch{return{content:"",truncated:!1}}}var nI,rI=h(()=>{"use strict";nI=2097152});import{existsSync as ay}from"node:fs";import{join as oI}from"node:path";function sI(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.kind=="string"&&typeof e.seq=="number"&&typeof e.payload=="object"&&e.payload!==null}function d4(t){return nr(t,{guard:sI})}function u4(t){return typeof t!="number"?s4:Math.min(Math.max(1,Math.round(t)),i4)}function p4(t){return typeof t!="number"?c4:Math.min(Math.max(1,Math.round(t)),l4)}function f4(t,e){if(e.kinds&&!e.kinds.has(t.kind)||e.toolName&&(t.kind!=="tool_call"||t.payload.name!==e.toolName))return!1;if(e.errorsOnly)if(t.kind==="tool_call"){let n=t.payload;if(n.phase!=="completed"||!n.isError)return!1}else if(t.kind==="subagent_lifecycle"){if(t.payload.transition!=="failed")return!1}else if(t.kind==="background_agent"){if(t.payload.transition!=="failed")return!1}else return!1;return!0}async function m4(t){let e=async r=>{let o=oI(Ft(r),"trace.jsonl");if(!ay(o))try{for await(let s of QR(r))if(s.kind==="meta"){if(s.traceLabel===null)return{tracePath:o,disabledNote:r};if(typeof s.traceLabel=="string"&&s.traceLabel.length>0){let i=oI(Ft(s.traceLabel),"trace.jsonl");ay(i)&&(o=i)}break}}catch{}return{tracePath:o,disabledNote:void 0}},n=await e(t);if(n.disabledNote!==void 0||ay(n.tracePath))return n;try{let r=Fd(t);if(r&&r.sessionId!==t){let o=await e(r.sessionId);return o.disabledNote!==void 0?{tracePath:o.tracePath,disabledNote:r.sessionId}:o}}catch{}return n}async function iI(t){let e=t.session==="latest"||!t.session?await eI():t.session;if(!e)return{sessionId:"(none)",events:[],totalInTrace:0,filtered:0};let{tracePath:n,disabledNote:r}=await m4(e);if(r!==void 0)return{sessionId:e,events:[],totalInTrace:0,filtered:0,note:`Session "${r}" ran with tracing disabled (traceLabel: null).`};let{content:o}=await iy(n),s=d4(o),i={kinds:t.kinds?new Set(t.kinds):void 0,toolName:t.toolName,errorsOnly:t.errorsOnly},a=u4(t.limit),c=[];for(let l=s.length-1;l>=0;l--){let d=s[l];if(f4(d,i)&&(c.push(d),c.length>=a))break}return c.reverse(),{sessionId:e,events:c,totalInTrace:s.length,filtered:c.length}}async function aI(t){let e=p4(t.sessions),r=(await oy()).slice(0,e),o=r.length,s=r;if(t.since){let p=Date.parse(t.since);if(Number.isNaN(p))throw new Error(`Invalid "since" date: ${t.since}`);s=r.filter(f=>f.mtimeMs>=p)}let i=t.kinds?new Set(t.kinds):void 0,a=t.query.toLowerCase(),c=[],l=a4,d=[],u=0;for(let p of s){if(c.length>=l)break;let{content:f,truncated:m}=await iy(p.tracePath);u++,m&&d.push(p.sessionId);let g=f.split(`
349
349
  `).filter(y=>y.trim()!==""&&y.toLowerCase().includes(a));for(let y of g){if(c.length>=l)break;let[b]=nr(y,{guard:sI});b&&(i&&!i.has(b.kind)||t.toolName&&(b.kind!=="tool_call"||b.payload.name!==t.toolName)||c.push({sessionId:p.sessionId,event:b,matchLine:y.length>500?y.slice(0,500)+"\u2026":y}))}}return{query:t.query,sessionsAvailable:o,sessionsSearched:u,sessionsScanned:u,matches:c,...d.length>0?{truncatedSessions:d}:{}}}var s4,i4,a4,c4,l4,cI=h(()=>{"use strict";j();Xi();tI();sy();rI();Pc();s4=50,i4=200,a4=200,c4=20,l4=100});function lI(t){return!t||typeof t!="object"?null:t}function dI(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string")}var uI,pI,fI=h(()=>{"use strict";cI();uI=async t=>{let e=lI(t);if(!e)return{content:"Invalid input: expected object",isError:!0};let n=typeof e.session=="string"?e.session:void 0,r=dI(e.kinds),o=typeof e.tool_name=="string"?e.tool_name:void 0,s=typeof e.errors_only=="boolean"?e.errors_only:!1,i=typeof e.limit=="number"?e.limit:void 0;try{let a=await iI({session:n,kinds:r,toolName:o,errorsOnly:s,limit:i});return{content:JSON.stringify(a)}}catch(a){return{content:`read_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},pI=async t=>{let e=lI(t);if(!e)return{content:"Invalid input: expected object",isError:!0};if(typeof e.query!="string"||!e.query)return{content:"Invalid input: query (string) is required",isError:!0};let n=e.query,r=typeof e.sessions=="number"?e.sessions:void 0,o=dI(e.kinds),s=typeof e.since=="string"?e.since:void 0,i=typeof e.tool_name=="string"?e.tool_name:void 0;try{let a=await aI({query:n,sessions:r,kinds:o,since:s,toolName:i});return{content:JSON.stringify(a)}}catch(a){return{content:`search_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}}});function g4(t){return t.length<=mI?t:`${t.slice(0,mI)}\u2026(truncated)`}function h4(t){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${t.title??t.serverName}`,g4(t.message)];t.url!==void 0&&t.url!==""&&n.push(t.url),xr(n.join(`
350
350
  `)).catch(()=>{})}catch{}}function gI(t,e){if(!(t===void 0||t===""))try{bg(t,e).catch(()=>{})}catch{}}var Uo,mI,cy,Be,Fn=h(()=>{"use strict";Oo();wr();Uo={action:"decline"},mI=300;cy=class{handler=null;queue=Promise.resolve();queueDepth=0;install(e){this.handler=e}uninstall(){this.handler=null}hasHandler(){return this.handler!==null}pendingCount(){return this.queueDepth}route(e,n){if(n.signal.aborted)return Promise.resolve(Uo);this.queueDepth+=1;let r,o=new Promise(i=>{r=i}),s=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(Uo);return}if(!s){h4(e),r(Uo);return}let i,a=new Promise(c=>{i=()=>c(Uo),n.signal.addEventListener("abort",i,{once:!0})});try{try{n.onActive?.()}catch{}gI(n.sessionId,!0);let c=await Promise.race([s(e,n).catch(()=>Uo),a]);r(c)}finally{gI(n.sessionId,!1),n.signal.removeEventListener("abort",i)}}finally{this.queueDepth-=1,r(Uo)}}).catch(()=>{}),o}},Be=new cy});var hI,yI=h(()=>{"use strict";Fn();hI=async(t,e,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let r=t,o=r.question;if(typeof o!="string"||o.trim()==="")return{content:"Invalid input: question must be a non-empty string",isError:!0};let s=new Set(["text","confirm","choice","multi_choice","number"]),i=r.type??"text";if(typeof i!="string"||!s.has(i))return{content:"Invalid input: type must be one of: text, confirm, choice, multi_choice, number",isError:!0};if(i==="choice"||i==="multi_choice"){let m=r.choices;if(!Array.isArray(m)||m.length===0)return{content:`Invalid input: choices array is required and must be non-empty for type "${i}"`,isError:!0};if(m.length>100)return{content:`Invalid input: choices array must not exceed 100 items, got ${m.length}`,isError:!0};for(let g of m)if(typeof g!="string")return{content:"Invalid input: all choices must be strings",isError:!0}}let a=r.min,c=r.max;if(a!==void 0&&(typeof a!="number"||!Number.isFinite(a)))return{content:"Invalid input: min must be a finite number",isError:!0};if(c!==void 0&&(typeof c!="number"||!Number.isFinite(c)))return{content:"Invalid input: max must be a finite number",isError:!0};if(a!==void 0&&c!==void 0&&a>c)return{content:`Invalid input: min (${a}) must be \u2264 max (${c})`,isError:!0};let l=r.min_length,d=r.max_length;if(l!==void 0&&typeof l!="number")return{content:"Invalid input: min_length must be a number",isError:!0};if(d!==void 0&&typeof d!="number")return{content:"Invalid input: max_length must be a number",isError:!0};if((l!==void 0||d!==void 0)&&i!=="text")return{content:`Invalid input: min_length/max_length are only valid for type "text", got "${i}"`,isError:!0};if(r.allow_custom!==void 0&&i!=="choice"&&i!=="multi_choice")return{content:`Invalid input: allow_custom is only valid for type "choice" or "multi_choice", got "${i}"`,isError:!0};let u={serverName:"agent",message:o.trim(),origin:"agent",type:i,...r.choices!==void 0&&{choices:r.choices},...r.context!==void 0&&typeof r.context=="string"&&{context:r.context},...r.default!==void 0&&{questionDefault:r.default},...l!==void 0&&{minLength:l},...d!==void 0&&{maxLength:d},...a!==void 0&&{min:a},...c!==void 0&&{max:c},...r.allow_skip!==void 0&&{allowSkip:!!r.allow_skip},...r.allow_custom!==void 0&&{allowCustom:!!r.allow_custom}},p=await Be.route(u,{signal:e,...n?.sessionId!==void 0?{sessionId:n.sessionId}:{}}),f=p.action==="decline"||p.action==="cancel";return{content:JSON.stringify(p),...f&&{isError:!0,failureClass:"elicitation-declined"}}}});function y4(t){if(!t||typeof t!="object")return{error:"browser_open: input must be an object"};let e=t,n=e.url;if(typeof n!="string"||n.length===0)return{error:'browser_open: "url" is required and must be a non-empty string'};let r;try{r=new URL(n)}catch{return{error:`browser_open: "${n}" is not a valid absolute URL`}}if(r.protocol!=="http:"&&r.protocol!=="https:")return{error:`browser_open: protocol "${r.protocol}" is not supported (http/https only)`};let o;if(e.wait_for!==void 0){if(!bI.includes(e.wait_for))return{error:`browser_open: "wait_for" must be one of ${bI.map(a=>`"${a}"`).join(", ")} (got ${JSON.stringify(e.wait_for)})`};o=e.wait_for}let s;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_open: "screenshot" must be a boolean'};s=e.screenshot}let i;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'browser_open: "timeout_ms" must be a positive finite number'};i=e.timeout_ms}return{url:r.toString(),waitFor:o,screenshot:s,timeoutMs:i}}function b4(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_open aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0,failureClass:Fe(n)}}let o=y4(e);if("error"in o)return{content:o.error,isError:!0};let s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(Or(),Mr));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return ze(u)?{content:mt(u),isError:!0}:{content:`browser_open failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.open({sessionId:s,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),u=Date.now()-l;if("outcome"in d&&d.outcome==="blocked_by_policy")return he(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:u}),{content:`browser_open blocked: ${d.reason}`,isError:!0,failureClass:"policy-refusal"};let p=d;return he(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:p.url,status:"ok",durationMs:u,...p.screenshotPath!==null?{screenshotPath:p.screenshotPath}:{}}),{content:JSON.stringify(p,null,2)}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);he(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}});let f=yd(d);return{content:`browser_open failed: ${p}`,isError:!0,...f?{failureClass:f}:{}}}}}var bI,wI,SI=h(()=>{"use strict";L();Rn();J();Dr();bI=["load","domcontentloaded","networkidle"];wI=b4()});function w4(t){if(t!=null&&typeof t!="object")return{error:"browser_observe: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_observe: "screenshot" must be a boolean'};n=e.screenshot}let r;if(e.include_hidden!==void 0){if(typeof e.include_hidden!="boolean")return{error:'browser_observe: "include_hidden" must be a boolean'};r=e.include_hidden}let o;if(e.max_elements!==void 0){if(typeof e.max_elements!="number"||!Number.isFinite(e.max_elements)||e.max_elements<=0||!Number.isInteger(e.max_elements))return{error:'browser_observe: "max_elements" must be a positive integer'};o=e.max_elements}return{screenshot:n,includeHidden:r,maxElements:o}}function S4(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_observe aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let o=w4(e);if("error"in o)return{content:o.error,isError:!0};let s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(Or(),Mr));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return ze(u)?{content:mt(u),isError:!0}:{content:`browser_observe failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.observe({sessionId:s,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),u=Date.now()-l;return he(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:d.url,urlAfter:d.url,status:"ok",durationMs:u,...d.screenshotPath!==null?{screenshotPath:d.screenshotPath}:{}}),{content:JSON.stringify(d,null,2)}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);return he(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}}),{content:`browser_observe failed: ${p}`,isError:!0}}}}var kI,vI=h(()=>{"use strict";L();J();Dr();kI=S4()});function k4(t){if(!t||typeof t!="object")return{error:"browser_act: input must be an object"};let e=t;if(typeof e.action!="string")return{error:'browser_act: "action" is required and must be a string'};if(!TI.includes(e.action))return{error:`browser_act: "action" must be one of ${TI.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(e.action)})`};let n=e.action,r=e.target;if(!r||typeof r!="object")return{error:'browser_act: "target" is required and must be an object'};let o=r;if(typeof o.kind!="string"||!EI.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${EI.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(o.kind)})`};let s,i=o.kind;if(i==="semantic"){if(typeof o.text!="string"||o.text.length===0)return{error:'browser_act: target.kind=semantic requires "target.text" (non-empty string)'};s={kind:"semantic",text:o.text,...typeof o.role=="string"&&o.role.length>0?{role:o.role}:{}}}else if(i==="element_id"){if(typeof o.element_id!="string"||o.element_id.length===0)return{error:'browser_act: target.kind=element_id requires "target.element_id" (non-empty string)'};s={kind:"element_id",elementId:o.element_id}}else{if(typeof o.selector!="string"||o.selector.length===0)return{error:'browser_act: target.kind=selector requires "target.selector" (non-empty string)'};s={kind:"selector",selector:o.selector}}let a;if(e.value!==void 0){if(typeof e.value!="string")return{error:'browser_act: "value" must be a string when provided'};a=e.value}let c;if(e.timeout_ms!==void 0){if(typeof e.timeout_ms!="number"||!Number.isFinite(e.timeout_ms)||e.timeout_ms<=0)return{error:'browser_act: "timeout_ms" must be a positive finite number'};c=e.timeout_ms}let l;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};l=e.screenshot}return{action:n,target:s,value:a,timeoutMs:c,screenshot:l}}function v4(t,e){let n=t.role?`"${t.text}" (role: ${t.role})`:`"${t.text}"`;return[`browser_act: ambiguous target \u2014 ${e.length} elements matched ${n}.`,'Retry with target.kind="element_id" using one of the following:',...e.map(o=>` id=${o.id} role=${o.role} label=${o.label}`)].join(`
351
- `)}function T4(t){return t.kind==="semantic"?{kind:"semantic",text:JA(t.text),...t.role!==void 0?{role:t.role}:{}}:t.kind==="element_id"?{kind:"element_id",elementId:t.elementId}:{kind:"selector",selectorHash:zA(t.selector)}}function E4(t={}){return async(e,n,r)=>{if(n.aborted){let u=n.reason;return{content:`browser_act aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0,failureClass:Fe(n)}}let o=k4(e);if("error"in o)return{content:o.error,isError:!0};let s=T4(o.target),i=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let a,c,l;try{if(t.getBrowserProvider)a=await t.getBrowserProvider();else{let{getBrowserProvider:u,getLastRoutingDecision:p}=await Promise.resolve().then(()=>(Or(),Mr));a=await u();let f=p();f&&(c=f.backend,l=f.reason)}}catch(u){let p=u instanceof Error?u.message:String(u);return ze(p)?{content:mt(p),isError:!0}:{content:`browser_act failed to get provider: ${p}`,isError:!0}}let d=Date.now();try{let u=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),p=Date.now()-d;if("outcome"in u){if(u.outcome==="ambiguous_target")return he(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:p}),{content:v4(u.query,u.candidates),isError:!0};if(u.outcome==="blocked_by_policy")return he(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:p}),{content:`browser_act blocked: ${u.reason}`,isError:!0,failureClass:"policy-refusal"}}return he(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:u.url,urlAfter:u.url,status:"ok",durationMs:p,...u.screenshotPath!==null?{screenshotPath:u.screenshotPath}:{}}),{content:JSON.stringify(u,null,2)}}catch(u){let p=Date.now()-d,f=u instanceof Error?u.message:String(u);he(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:p,error:{reason:f,recoverable:!1}});let m=yd(u);return{content:`browser_act failed: ${f}`,isError:!0,...m?{failureClass:m}:{}}}}}var TI,EI,_I,AI=h(()=>{"use strict";dd();L();Rn();J();Dr();TI=["click","fill","press","select","hover","scroll_to","wait_for"],EI=["semantic","element_id","selector"];_I=E4()});function _4(t){if(typeof t.kind!="string"||!xI.includes(t.kind))return{error:`browser_screenshot: "target.kind" must be one of ${xI.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(t.kind)})`};let e=t.kind;return e==="semantic"?typeof t.text!="string"||t.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:t.text,...typeof t.role=="string"&&t.role.length>0?{role:t.role}:{}}:e==="element_id"?typeof t.element_id!="string"||t.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:t.element_id}:typeof t.selector!="string"||t.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:t.selector}}function A4(t){if(t!=null&&typeof t!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.target!==void 0){if(!e.target||typeof e.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=_4(e.target);if("error"in o)return o;n=o}let r;if(e.full_page!==void 0){if(typeof e.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=e.full_page}return{target:n,fullPage:r}}function x4(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_screenshot aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let o=A4(e);if("error"in o)return{content:o.error,isError:!0};let s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(Or(),Mr));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return ze(u)?{content:mt(u),isError:!0}:{content:`browser_screenshot failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),u=Date.now()-l,{dataBase64:p,mediaType:f,...m}=d;return he(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:u,screenshotPath:m.path}),m.width>ly||m.height>ly?{content:JSON.stringify({...m,imageOmitted:`dimensions ${m.width}x${m.height}px exceed the ${ly}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(m,null,2),image:{mediaType:f,data:p}}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);return he(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}}),{content:`browser_screenshot failed: ${p}`,isError:!0}}}}var xI,ly,RI,II=h(()=>{"use strict";L();J();Dr();xI=["semantic","element_id","selector"],ly=8e3;RI=x4()});function R4(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_close aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let s,i,a;try{if(t.getBrowserProvider)s=await t.getBrowserProvider();else{let{getBrowserProvider:l,getLastRoutingDecision:d}=await Promise.resolve().then(()=>(Or(),Mr));s=await l();let u=d();u&&(i=u.backend,a=u.reason)}}catch(l){let d=l instanceof Error?l.message:String(l);return ze(d)?{content:mt(d),isError:!0}:{content:`browser_close failed to get provider: ${d}`,isError:!0}}let c=Date.now();try{await s.close({sessionId:o});let l=Date.now()-c;return he(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:l}),{content:"Browser session closed."}}catch(l){let d=Date.now()-c,u=l instanceof Error?l.message:String(l);return he(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}}),{content:`browser_close failed: ${u}`,isError:!0}}}}var CI,PI=h(()=>{"use strict";L();J();Dr();CI=R4()});function Ln(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}function Ld(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":Ln(I4,t)?"read":Ln(C4,t)?"write":Ln(P4,t)?"shell":Ln(MI,t)?"subagent":Ln(OI,t)?"skill":Ln(DI,t)?"dag":Ln(M4,t)?"web":O4.has(t)?"browser":Ln(D4,t)?"planning":F4.has(t)?"schedule":"other"}var I4,C4,P4,MI,OI,DI,vbe,M4,O4,D4,F4,dy,FI,zi=h(()=>{"use strict";Fl();I4=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","workspace_query","read_witness","search_witness","get_facet","json_query","state_get","state_query"]),C4=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","patch_apply","memory_update","procedure_write","terminal_font_size","config_set","workspace_publish","state_put","state_cas","state_delete","clipboard_write"]),P4=new Set(["Bash","BashOutput","KillBash","bash","test_run","wait_for"]),MI=new Set(["Agent","Task","agent","cancel_background_job","send_message_to_agent"]),OI=new Set(["Skill","skill"]),DI=new Set(["Compose","compose"]),vbe=new Set([...MI,...DI,...OI]),M4=new Set(["WebFetch","WebSearch","send_telegram","web_scrape","web_request"]),O4=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),D4=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),F4=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);dy=["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness","workspace_publish","workspace_query","json_query","state_get","state_query",...Le],FI=[...dy,"web_scrape","agent"]});import LI from"path";function U4(t){return typeof t=="object"&&t!==null&&"command"in t?String(t.command??""):typeof t=="string"?t:""}function B4(t){if(typeof t!="object"||t===null)return"";let e=t;return typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:""}function NI(t){for(let e of L4)if(t.includes(e))return"high";for(let e of N4)if(t.includes(e))return"medium";for(let e of $4)if(t.includes(e))return"safe";return"medium"}function $I(t,e){if(!t)return"safe";let n=$e(LI.resolve(e.cwd,t)),r=Mg();for(let o of r)if(n===o||n.startsWith(o+"/"))return"high";if(n.includes("/.git/"))return"high";if(e.workspaceRoot!==void 0){let o=$e(e.workspaceRoot);if(LI.relative(o,n).startsWith(".."))return"high"}return n.includes("/node_modules/")?"medium":"safe"}function H4(t){return t.split("__").slice(1).join("__").split(/[_-]+/).filter(Boolean)}function Nd(t,e,n){let r=t.toLowerCase();if(r==="bash"){let o=U4(e);return NI(o)}if(r==="write_file"||r==="edit_file"){let o=B4(e);return $I(o,n)}if(r==="patch_apply"){let o=typeof e=="object"&&e!==null?e:{},s=Array.isArray(o.changes)?o.changes:[],i="safe";for(let a of s){if(typeof a!="object"||a===null)continue;let c=a.path,d=$I(typeof c=="string"?c:"",n);if(d==="high")return"high";d==="medium"&&(i="medium")}return i}if(Ld(t)==="read")return"safe";if(r==="send_telegram")return"medium";if(r.startsWith("mcp__"))return H4(r).some(s=>j4.has(s))?"high":"medium";if(r==="create_schedule"||r==="cancel_schedule")return"high";if(r==="worktree"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.action=="string"?o.action:"";return s==="list"?"safe":s==="remove"&&o.force===!0?"high":"medium"}if(r==="browser_act"||r==="browser_open"||r==="web_scrape")return"medium";if(r==="web_request"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.method=="string"?o.method.toUpperCase():"";return s==="DELETE"?"high":s==="GET"||s==="HEAD"||s==="OPTIONS"?"safe":"medium"}if(r==="wait_for"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.type=="string"?o.type:"";if(s==="command"){let i=typeof o.command=="string"?o.command:"";return NI(i)}return s==="file"||s==="process"?"safe":"medium"}return"safe"}var L4,N4,$4,j4,uy=h(()=>{"use strict";kr();zi();L4=["rm -rf","rm ","sudo","eval ","chmod","chown","git push --force","git push -f","git reset --hard","mkfs","fdisk","diskutil eraseDisk","dd if=","dd of=","| sh","| bash","|sh","|bash","-X POST","-X PUT","-X PATCH","-X DELETE","-XPOST","-XPUT","-XPATCH","-XDELETE","--request POST","--request PUT","--request PATCH","--request DELETE","curl --data","curl -d","curl -F","wget --post-data","wget --post-file","launchctl load","launchctl bootstrap","launchctl submit","launchctl start ","launchctl kickstart","launchctl enable ","systemctl enable ","systemctl start ","systemctl daemon-reload"],N4=["git push","git reset","git commit","git stash drop","git stash clear","npm install","pnpm install","yarn","pip install","apt ","apt-get ","brew install","tee "," > "," >> ","mv ","cp ","mkdir","touch","pnpm build","tsc ","eslint --fix"],$4=["pnpm test","vitest","jest","pytest","cargo test","go test","git status","git log","git diff","git show","ls ","cat ","head ","tail ","find ","grep ","echo ","printf "];j4=new Set(["delete","drop","remove","destroy","truncate","purge","wipe","write","create","update","insert","upsert","patch","rename","exec","execute","run","eval","send","push","publish","deploy","post","merge","rollback","reset","terminate","provision","scale","disable","charge","refund","revoke"])});import*as $d from"node:fs/promises";import{execSync as W4}from"node:child_process";async function UI(t,e){let n=t.method??"HEAD",r;try{r=await Mn(globalThis.fetch,t.url,{method:n,signal:e})}catch(a){let c=a instanceof Error?a.message:String(a);return{met:!1,detail:c.startsWith("refusing to")?`SSRF blocked: ${c}`:`fetch error: ${c}`,data:c.startsWith("refusing to")?{blocked:!0}:void 0}}let{status:o}=r,s={status:o};if(!(t.expected_status!==void 0?o===t.expected_status:o>=200&&o<300))return{met:!1,detail:`HTTP ${o} (want ${t.expected_status??"2xx"})`,data:s};if(t.body_contains!==void 0){let a=await r.text().catch(()=>"");if(s.bodyLength=a.length,!a.includes(t.body_contains))return{met:!1,detail:`body does not contain "${t.body_contains}"`,data:s}}else n==="HEAD"&&await r.body?.cancel().catch(()=>{});return{met:!0,detail:`HTTP ${o}`,data:s}}async function BI(t,e){let n;try{let o=t.workspaceRoot?{resolveBase:t.workspaceRoot,cwd:t.workspaceRoot}:void 0;n=de(t.path,o,"read")}catch(o){return{met:!1,detail:`path rejected: ${o instanceof Error?o.message:String(o)}`,data:{blocked:!0}}}let r;try{let o=await $d.stat(n);r={mtimeMs:o.mtimeMs,size:o.size}}catch{return{met:!1,detail:`file not found: ${t.path}`}}if(t.content_contains!==void 0){let o;try{o=await $d.readFile(n,{encoding:"utf8",signal:e})}catch(s){return{met:!1,detail:`read error: ${s instanceof Error?s.message:String(s)}`,data:r}}if(!o.includes(t.content_contains))return{met:!1,detail:`file exists but does not contain "${t.content_contains}"`,data:r}}return{met:!0,detail:`file exists (${r.size} bytes)`,data:r}}function jI(t,e){if(!Number.isInteger(t.pid)||t.pid<=1)return{met:!1,detail:`pid ${t.pid} is not a valid target (must be integer > 1)`,data:{pid:t.pid,blocked:!0}};if(e!==void 0&&!e.has(t.pid))return{met:!1,detail:`pid ${t.pid} is not a session-owned process (not in spawned PID registry)`,data:{pid:t.pid,blocked:!0}};try{return process.kill(t.pid,0),{met:!1,detail:`pid ${t.pid} is still alive`,data:{pid:t.pid}}}catch(n){let r=n.code;return r==="ESRCH"?{met:!0,detail:`pid ${t.pid} has exited`,data:{pid:t.pid}}:{met:!1,detail:`pid ${t.pid} is alive (${r??"unknown"})`,data:{pid:t.pid}}}}function HI(t){let e=Nd("bash",{command:t.command},{cwd:t.cwd??process.cwd()});if(e!=="safe")return{met:!1,detail:`command blocked by risk classifier (${e} risk): ${t.command}`,data:{command:t.command,blocked:!0}};try{return W4(t.command,{cwd:t.cwd,stdio:"pipe",timeout:3e4}),{met:!0,detail:"command exited 0",data:{command:t.command}}}catch(n){let r=n;if(r.killed===!0&&r.signal==="SIGTERM")return{met:!1,detail:"command timed out (30s limit)",data:{command:t.command,timedOut:!0}};let o=r.status??-1;return{met:!1,detail:`command exited ${o}`,data:{command:t.command,exitCode:o}}}}var WI=h(()=>{"use strict";Ir();uy();Te()});function je(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=()=>{clearTimeout(o),n()},o=setTimeout(()=>{e.removeEventListener("abort",r),n()},t);o.unref(),e.addEventListener("abort",r,{once:!0})})}var Nn=h(()=>{"use strict"});function K4(t,e,n){switch(n){case"linear":return t+e*1e3;case"exponential":return Math.min(t*Math.pow(2,e),6e4);default:return t}}async function zI(t,e){let{timeout_ms:n,poll_interval_ms:r,backoff:o,signal:s}=e,i=Date.now()+n,a=0,c;for(;;){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};let l=i-Date.now(),d=AbortSignal.any([s,AbortSignal.timeout(Math.max(1,Math.min(r,l)))]),u;try{u=await t(d)}catch(m){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};if(m instanceof Error&&m.name==="AbortError"){if(Date.now()>=i)return{status:"timed_out",elapsed_ms:Date.now()-(i-n),attempts:a,result:c};continue}let g=m instanceof Error?m.message:String(m);return{status:"failed",elapsed_ms:Date.now()-(i-n),attempts:a,error:g}}if(c=u,a++,u.met)return{status:"succeeded",elapsed_ms:Date.now()-(i-n),attempts:a,result:u};let p=Date.now();if(p>=i)return{status:"timed_out",elapsed_ms:p-(i-n),attempts:a,result:c};let f=Math.min(K4(r,a-1,o),i-p);await je(f,s)}}var KI,qI,GI,XI,JI=h(()=>{"use strict";Nn();KI=12e4,qI=6e5,GI=5e3,XI=1e3});import VI from"node:path";function q4(t,e){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let n=t,r=n.type;if(typeof r!="string")throw new Error('"type" is required and must be a string');let o=KI;if(n.timeout_ms!==void 0){if(typeof n.timeout_ms!="number"||!Number.isFinite(n.timeout_ms))throw new Error('"timeout_ms" must be a finite number');o=Math.min(Math.max(0,n.timeout_ms),qI)}let s=GI;if(n.poll_interval_ms!==void 0){if(typeof n.poll_interval_ms!="number"||!Number.isFinite(n.poll_interval_ms))throw new Error('"poll_interval_ms" must be a finite number');s=Math.max(XI,n.poll_interval_ms)}let i=["none","linear","exponential"],a="none";if(n.backoff!==void 0){if(!i.includes(n.backoff))throw new Error(`"backoff" must be one of: ${i.join(", ")}`);a=n.backoff}switch(r){case"url":{if(typeof n.url!="string"||n.url.trim()==="")throw new Error('"url" is required for type "url"');let c=n.body_contains!==void 0,l=n.method??(c?"GET":"HEAD");if(l!=="HEAD"&&l!=="GET")throw new Error('"method" must be "HEAD" or "GET"');return{condition:{type:"url",url:n.url,method:l,...n.expected_status!==void 0?{expected_status:Number(n.expected_status)}:{},...c?{body_contains:String(n.body_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"file":{if(typeof n.path!="string"||n.path.trim()==="")throw new Error('"path" is required for type "file"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"file",path:c!==void 0&&!VI.isAbsolute(n.path)?VI.resolve(c,n.path):n.path,workspaceRoot:c,...n.content_contains!==void 0?{content_contains:String(n.content_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"process":{if(typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=1)throw new Error('"pid" is required for type "process" and must be an integer > 1');return{condition:{type:"process",pid:n.pid},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"command":{if(typeof n.command!="string"||n.command.trim()==="")throw new Error('"command" is required for type "command"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"command",command:n.command,...c!==void 0?{cwd:c}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}default:throw new Error(`Unknown type "${r}". Must be one of: url, file, process, command`)}}var YI,QI=h(()=>{"use strict";Ir();WI();JI();YI=async(t,e,n)=>{let r;try{r=q4(t,n)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{condition:o,timeoutMs:s,pollIntervalMs:i,backoff:a}=r;if(o.type==="url"){let u=await Rr(o.url);if(!u.allowed)return{content:`SSRF guard blocked: ${u.reason}`,isError:!0}}let l=await zI(u=>{switch(o.type){case"url":return UI(o,u);case"file":return BI(o,u);case"process":return Promise.resolve(jI(o,n?.spawnedPidRegistry));case"command":return Promise.resolve(HI(o))}},{timeout_ms:s,poll_interval_ms:i,backoff:a,signal:e});return{content:`Wait ${l.status}: ${o.type} condition (${l.elapsed_ms}ms elapsed, ${l.attempts} attempt${l.attempts===1?"":"s"})`+(l.result?` \u2014 ${l.result.detail}`:"")+(l.error?` \u2014 error: ${l.error}`:""),isError:l.status==="failed"}}});import{createHash as G4}from"crypto";import{readFile as X4}from"fs/promises";function z4(t){return G4("sha256").update(t,"utf8").digest("hex")}function J4(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}async function ZI(t,e,n){let r=[],o=new Map;for(let s of t){let i=s.path,a;try{a=de(i,n,"write",e)}catch(l){r.push({path:i,error:"path_containment",detail:l instanceof Error?l.message:String(l)});continue}try{To(a,"patch_apply")}catch(l){r.push({path:i,error:"write_denied",detail:l instanceof Error?l.message:String(l)});continue}if(s.edits!==void 0&&s.content!==void 0){r.push({path:i,error:"mutually_exclusive",detail:"`edits` and `content` cannot both be provided for the same file."});continue}if(s.edits===void 0&&s.content===void 0){r.push({path:i,error:"no_change_specified",detail:"At least one of `edits` or `content` must be provided."});continue}let c;try{c=await X4(a,"utf-8")}catch(l){if(s.expected_hash!==void 0||s.edits!==void 0){r.push({path:i,error:"file_read_failed",detail:l instanceof Error?l.message:String(l)});continue}o.set(a,null),c=""}if(o.has(a)||o.set(a,c),s.expected_hash!==void 0){let l="sha256:";if(!s.expected_hash.startsWith(l)){r.push({path:i,error:"invalid_hash_format",detail:`expected_hash must start with "sha256:". Got: "${s.expected_hash}"`});continue}let d=s.expected_hash.slice(l.length),u=z4(c);if(u!==d){r.push({path:i,error:"hash_mismatch",detail:`File hash mismatch. Expected sha256:${d}, got sha256:${u}. The file may have been modified.`});continue}}if(s.edits!==void 0){let l=c;for(let d=0;d<s.edits.length;d++){let u=s.edits[d],p=J4(l,u.old);if(p===0){r.push({path:i,error:"edit_not_found",detail:`Edit #${d+1}: \`old\` string not found in file.`});break}else if(p>1)r.push({path:i,error:"edit_ambiguous",detail:`Edit #${d+1}: \`old\` string matches ${p} locations. Provide enough context to make it unique.`});else{let f=l.indexOf(u.old);l=l.slice(0,f)+u.new+l.slice(f+u.old.length)}}}}return{valid:r.length===0,errors:r,fileContents:o}}var eC=h(()=>{"use strict";kr();Te()});import{createHash as V4,randomBytes as Y4}from"crypto";import{writeFile as tC,rename as Q4,mkdir as Z4,unlink as py,chmod as e5,stat as t5}from"fs/promises";import{dirname as rC,join as n5,isAbsolute as r5,resolve as o5}from"path";function nC(t){return V4("sha256").update(t,"utf8").digest("hex")}function s5(t,e,n){let r=Cn(e,n);if(!r)return"";let o=[`--- a/${t}`,`+++ b/${t}`];for(let s of r.hunks){o.push(`@@ -${s.oldStart},${s.oldLines} +${s.newStart},${s.newLines} @@`);for(let i of s.lines)o.push(`${i.kind}${i.text}`)}return o.join(`
351
+ `)}function T4(t){return t.kind==="semantic"?{kind:"semantic",text:JA(t.text),...t.role!==void 0?{role:t.role}:{}}:t.kind==="element_id"?{kind:"element_id",elementId:t.elementId}:{kind:"selector",selectorHash:zA(t.selector)}}function E4(t={}){return async(e,n,r)=>{if(n.aborted){let u=n.reason;return{content:`browser_act aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0,failureClass:Fe(n)}}let o=k4(e);if("error"in o)return{content:o.error,isError:!0};let s=T4(o.target),i=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(i))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(i)}`,isError:!0};let a,c,l;try{if(t.getBrowserProvider)a=await t.getBrowserProvider();else{let{getBrowserProvider:u,getLastRoutingDecision:p}=await Promise.resolve().then(()=>(Or(),Mr));a=await u();let f=p();f&&(c=f.backend,l=f.reason)}}catch(u){let p=u instanceof Error?u.message:String(u);return ze(p)?{content:mt(p),isError:!0}:{content:`browser_act failed to get provider: ${p}`,isError:!0}}let d=Date.now();try{let u=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),p=Date.now()-d;if("outcome"in u){if(u.outcome==="ambiguous_target")return he(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:p}),{content:v4(u.query,u.candidates),isError:!0};if(u.outcome==="blocked_by_policy")return he(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:p}),{content:`browser_act blocked: ${u.reason}`,isError:!0,failureClass:"policy-refusal"}}return he(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:u.url,urlAfter:u.url,status:"ok",durationMs:p,...u.screenshotPath!==null?{screenshotPath:u.screenshotPath}:{}}),{content:JSON.stringify(u,null,2)}}catch(u){let p=Date.now()-d,f=u instanceof Error?u.message:String(u);he(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",...c?{backend:c}:{},...l?{backendReason:l}:{},target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:p,error:{reason:f,recoverable:!1}});let m=yd(u);return{content:`browser_act failed: ${f}`,isError:!0,...m?{failureClass:m}:{}}}}}var TI,EI,_I,AI=h(()=>{"use strict";dd();L();Rn();J();Dr();TI=["click","fill","press","select","hover","scroll_to","wait_for"],EI=["semantic","element_id","selector"];_I=E4()});function _4(t){if(typeof t.kind!="string"||!xI.includes(t.kind))return{error:`browser_screenshot: "target.kind" must be one of ${xI.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(t.kind)})`};let e=t.kind;return e==="semantic"?typeof t.text!="string"||t.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:t.text,...typeof t.role=="string"&&t.role.length>0?{role:t.role}:{}}:e==="element_id"?typeof t.element_id!="string"||t.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:t.element_id}:typeof t.selector!="string"||t.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:t.selector}}function A4(t){if(t!=null&&typeof t!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!t)return{};let e=t,n;if(e.target!==void 0){if(!e.target||typeof e.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=_4(e.target);if("error"in o)return o;n=o}let r;if(e.full_page!==void 0){if(typeof e.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=e.full_page}return{target:n,fullPage:r}}function x4(t={}){return async(e,n,r)=>{if(n.aborted){let d=n.reason;return{content:`browser_screenshot aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let o=A4(e);if("error"in o)return{content:o.error,isError:!0};let s=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(s))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(s)}`,isError:!0};let i,a,c;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:d,getLastRoutingDecision:u}=await Promise.resolve().then(()=>(Or(),Mr));i=await d();let p=u();p&&(a=p.backend,c=p.reason)}}catch(d){let u=d instanceof Error?d.message:String(d);return ze(u)?{content:mt(u),isError:!0}:{content:`browser_screenshot failed to get provider: ${u}`,isError:!0}}let l=Date.now();try{let d=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),u=Date.now()-l,{dataBase64:p,mediaType:f,...m}=d;return he(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:u,screenshotPath:m.path}),m.width>ly||m.height>ly?{content:JSON.stringify({...m,imageOmitted:`dimensions ${m.width}x${m.height}px exceed the ${ly}px model-vision limit; the PNG was saved to the sidecar path but not attached. Use full_page:false (viewport) or target a specific element for a model-visible image.`},null,2)}:{content:JSON.stringify(m,null,2),image:{mediaType:f,data:p}}}catch(d){let u=Date.now()-l,p=d instanceof Error?d.message:String(d);return he(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",...a?{backend:a}:{},...c?{backendReason:c}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:u,error:{reason:p,recoverable:!1}}),{content:`browser_screenshot failed: ${p}`,isError:!0}}}}var xI,ly,RI,II=h(()=>{"use strict";L();J();Dr();xI=["semantic","element_id","selector"],ly=8e3;RI=x4()});function R4(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_close aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=v.AFK_SESSION_ID??"default";if(!/^[a-zA-Z0-9_-]+$/.test(o))return{content:`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(o)}`,isError:!0};let s,i,a;try{if(t.getBrowserProvider)s=await t.getBrowserProvider();else{let{getBrowserProvider:l,getLastRoutingDecision:d}=await Promise.resolve().then(()=>(Or(),Mr));s=await l();let u=d();u&&(i=u.backend,a=u.reason)}}catch(l){let d=l instanceof Error?l.message:String(l);return ze(d)?{content:mt(d),isError:!0}:{content:`browser_close failed to get provider: ${d}`,isError:!0}}let c=Date.now();try{await s.close({sessionId:o});let l=Date.now()-c;return he(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"ok",durationMs:l}),{content:"Browser session closed."}}catch(l){let d=Date.now()-c,u=l instanceof Error?l.message:String(l);return he(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",...i?{backend:i}:{},...a?{backendReason:a}:{},urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}}),{content:`browser_close failed: ${u}`,isError:!0}}}}var CI,PI=h(()=>{"use strict";L();J();Dr();CI=R4()});function Ln(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}function Ld(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":Ln(I4,t)?"read":Ln(C4,t)?"write":Ln(P4,t)?"shell":Ln(MI,t)?"subagent":Ln(OI,t)?"skill":Ln(DI,t)?"dag":Ln(M4,t)?"web":O4.has(t)?"browser":Ln(D4,t)?"planning":F4.has(t)?"schedule":"other"}var I4,C4,P4,MI,OI,DI,vbe,M4,O4,D4,F4,dy,FI,zi=h(()=>{"use strict";Fl();I4=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","workspace_query","read_witness","search_witness","get_facet","json_query","state_get","state_query"]),C4=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","patch_apply","memory_update","procedure_write","terminal_font_size","config_set","workspace_publish","state_put","state_cas","state_delete","clipboard_write"]),P4=new Set(["Bash","BashOutput","KillBash","bash","test_run","wait_for"]),MI=new Set(["Agent","Task","agent","cancel_background_job","send_message_to_agent"]),OI=new Set(["Skill","skill"]),DI=new Set(["Compose","compose"]),vbe=new Set([...MI,...DI,...OI]),M4=new Set(["WebFetch","WebSearch","send_telegram","web_scrape","web_request"]),O4=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),D4=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),F4=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);dy=["Read","Glob","Grep","NotebookRead","LS","read_file","extract_document","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness","workspace_publish","workspace_query","json_query","state_get","state_query",...Le],FI=[...dy,"web_scrape","agent"]});import LI from"path";function U4(t){return typeof t=="object"&&t!==null&&"command"in t?String(t.command??""):typeof t=="string"?t:""}function B4(t){if(typeof t!="object"||t===null)return"";let e=t;return typeof e.file_path=="string"?e.file_path:typeof e.path=="string"?e.path:""}function NI(t){for(let e of L4)if(t.includes(e))return"high";for(let e of N4)if(t.includes(e))return"medium";for(let e of $4)if(t.includes(e))return"safe";return"medium"}function $I(t,e){if(!t)return"safe";let n=$e(LI.resolve(e.cwd,t)),r=Mg();for(let o of r)if(n===o||n.startsWith(o+"/"))return"high";if(n.includes("/.git/"))return"high";if(e.workspaceRoot!==void 0){let o=$e(e.workspaceRoot);if(LI.relative(o,n).startsWith(".."))return"high"}return n.includes("/node_modules/")?"medium":"safe"}function H4(t){return t.split("__").slice(1).join("__").split(/[_-]+/).filter(Boolean)}function Nd(t,e,n){let r=t.toLowerCase();if(r==="bash"){let o=U4(e);return NI(o)}if(r==="write_file"||r==="edit_file"){let o=B4(e);return $I(o,n)}if(r==="patch_apply"){let o=typeof e=="object"&&e!==null?e:{},s=Array.isArray(o.changes)?o.changes:[],i="safe";for(let a of s){if(typeof a!="object"||a===null)continue;let c=a.path,d=$I(typeof c=="string"?c:"",n);if(d==="high")return"high";d==="medium"&&(i="medium")}return i}if(Ld(t)==="read")return"safe";if(r==="send_telegram")return"medium";if(r.startsWith("mcp__"))return H4(r).some(s=>j4.has(s))?"high":"medium";if(r==="create_schedule"||r==="cancel_schedule")return"high";if(r==="worktree"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.action=="string"?o.action:"";return s==="list"?"safe":s==="remove"&&o.force===!0?"high":"medium"}if(r==="browser_act"||r==="browser_open"||r==="web_scrape")return"medium";if(r==="web_request"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.method=="string"?o.method.toUpperCase():"";return s==="DELETE"?"high":s==="GET"||s==="HEAD"||s==="OPTIONS"?"safe":"medium"}if(r==="wait_for"){let o=typeof e=="object"&&e!==null?e:{},s=typeof o.type=="string"?o.type:"";if(s==="command"){let i=typeof o.command=="string"?o.command:"";return NI(i)}return s==="file"||s==="process"?"safe":"medium"}return"safe"}var L4,N4,$4,j4,uy=h(()=>{"use strict";kr();zi();L4=["rm -rf","rm ","sudo","eval ","chmod","chown","git push --force","git push -f","git reset --hard","mkfs","fdisk","diskutil eraseDisk","dd if=","dd of=","| sh","| bash","|sh","|bash","-X POST","-X PUT","-X PATCH","-X DELETE","-XPOST","-XPUT","-XPATCH","-XDELETE","--request POST","--request PUT","--request PATCH","--request DELETE","curl --data","curl -d","curl -F","wget --post-data","wget --post-file","launchctl load","launchctl bootstrap","launchctl submit","launchctl start ","launchctl kickstart","launchctl enable ","systemctl enable ","systemctl start ","systemctl daemon-reload"],N4=["git push","git reset","git commit","git stash drop","git stash clear","npm install","pnpm install","yarn","pip install","apt ","apt-get ","brew install","tee "," > "," >> ","mv ","cp ","mkdir","touch","pnpm build","tsc ","eslint --fix"],$4=["pnpm test","vitest","jest","pytest","cargo test","go test","git status","git log","git diff","git show","ls ","cat ","head ","tail ","find ","grep ","echo ","printf "];j4=new Set(["delete","drop","remove","destroy","truncate","purge","wipe","write","create","update","insert","upsert","patch","rename","exec","execute","run","eval","send","push","publish","deploy","post","merge","rollback","reset","terminate","provision","scale","disable","charge","refund","revoke"])});import*as $d from"node:fs/promises";import{execSync as W4}from"node:child_process";async function UI(t,e){let n=t.method??"HEAD",r;try{r=await Mn(globalThis.fetch,t.url,{method:n,signal:e})}catch(a){let c=a instanceof Error?a.message:String(a);return{met:!1,detail:c.startsWith("refusing to")?`SSRF blocked: ${c}`:`fetch error: ${c}`,data:c.startsWith("refusing to")?{blocked:!0}:void 0}}let{status:o}=r,s={status:o};if(!(t.expected_status!==void 0?o===t.expected_status:o>=200&&o<300))return{met:!1,detail:`HTTP ${o} (want ${t.expected_status??"2xx"})`,data:s};if(t.body_contains!==void 0){let a=await r.text().catch(()=>"");if(s.bodyLength=a.length,!a.includes(t.body_contains))return{met:!1,detail:`body does not contain "${t.body_contains}"`,data:s}}else n==="HEAD"&&await r.body?.cancel().catch(()=>{});return{met:!0,detail:`HTTP ${o}`,data:s}}async function BI(t,e){let n;try{let o=t.workspaceRoot?{resolveBase:t.workspaceRoot,cwd:t.workspaceRoot}:void 0;n=de(t.path,o,"read")}catch(o){return{met:!1,detail:`path rejected: ${o instanceof Error?o.message:String(o)}`,data:{blocked:!0}}}let r;try{let o=await $d.stat(n);r={mtimeMs:o.mtimeMs,size:o.size}}catch{return{met:!1,detail:`file not found: ${t.path}`}}if(t.content_contains!==void 0){let o;try{o=await $d.readFile(n,{encoding:"utf8",signal:e})}catch(s){return{met:!1,detail:`read error: ${s instanceof Error?s.message:String(s)}`,data:r}}if(!o.includes(t.content_contains))return{met:!1,detail:`file exists but does not contain "${t.content_contains}"`,data:r}}return{met:!0,detail:`file exists (${r.size} bytes)`,data:r}}function jI(t,e){if(!Number.isInteger(t.pid)||t.pid<=1)return{met:!1,detail:`pid ${t.pid} is not a valid target (must be integer > 1)`,data:{pid:t.pid,blocked:!0}};if(e!==void 0&&!e.has(t.pid))return{met:!1,detail:`pid ${t.pid} is not a session-owned process (not in spawned PID registry)`,data:{pid:t.pid,blocked:!0}};try{return process.kill(t.pid,0),{met:!1,detail:`pid ${t.pid} is still alive`,data:{pid:t.pid}}}catch(n){let r=n.code;return r==="ESRCH"?{met:!0,detail:`pid ${t.pid} has exited`,data:{pid:t.pid}}:{met:!1,detail:`pid ${t.pid} is alive (${r??"unknown"})`,data:{pid:t.pid}}}}function HI(t){let e=Nd("bash",{command:t.command},{cwd:t.cwd??process.cwd()});if(e!=="safe")return{met:!1,detail:`command blocked by risk classifier (${e} risk): ${t.command}`,data:{command:t.command,blocked:!0}};try{return W4(t.command,{cwd:t.cwd,stdio:"pipe",timeout:3e4}),{met:!0,detail:"command exited 0",data:{command:t.command}}}catch(n){let r=n;if(r.killed===!0&&r.signal==="SIGTERM")return{met:!1,detail:"command timed out (30s limit)",data:{command:t.command,timedOut:!0}};let o=r.status??-1;return{met:!1,detail:`command exited ${o}`,data:{command:t.command,exitCode:o}}}}var WI=h(()=>{"use strict";Ir();uy();Te()});function je(t,e){return new Promise(n=>{if(e.aborted){n();return}let r=()=>{clearTimeout(o),n()},o=setTimeout(()=>{e.removeEventListener("abort",r),n()},t);o.unref(),e.addEventListener("abort",r,{once:!0})})}var Nn=h(()=>{"use strict"});function K4(t,e,n){switch(n){case"linear":return t+e*1e3;case"exponential":return Math.min(t*Math.pow(2,e),6e4);default:return t}}async function zI(t,e){let{timeout_ms:n,poll_interval_ms:r,backoff:o,signal:s}=e,i=Date.now()+n,a=0,c;for(;;){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};let l=i-Date.now(),d=AbortSignal.any([s,AbortSignal.timeout(Math.max(1,Math.min(r,l)))]),u;try{u=await t(d)}catch(m){if(s.aborted)return{status:"cancelled",elapsed_ms:Date.now()-(i-n),attempts:a};if(m instanceof Error&&m.name==="AbortError"){if(Date.now()>=i)return{status:"timed_out",elapsed_ms:Date.now()-(i-n),attempts:a,result:c};continue}let g=m instanceof Error?m.message:String(m);return{status:"failed",elapsed_ms:Date.now()-(i-n),attempts:a,error:g}}if(c=u,a++,u.met)return{status:"succeeded",elapsed_ms:Date.now()-(i-n),attempts:a,result:u};let p=Date.now();if(p>=i)return{status:"timed_out",elapsed_ms:p-(i-n),attempts:a,result:c};let f=Math.min(K4(r,a-1,o),i-p);await je(f,s)}}var KI,qI,GI,XI,JI=h(()=>{"use strict";Nn();KI=12e4,qI=6e5,GI=5e3,XI=1e3});import VI from"node:path";function q4(t,e){if(typeof t!="object"||t===null)throw new Error("Input must be an object");let n=t,r=n.type;if(typeof r!="string")throw new Error('"type" is required and must be a string');let o=KI;if(n.timeout_ms!==void 0){if(typeof n.timeout_ms!="number"||!Number.isFinite(n.timeout_ms))throw new Error('"timeout_ms" must be a finite number');o=Math.min(Math.max(0,n.timeout_ms),qI)}let s=GI;if(n.poll_interval_ms!==void 0){if(typeof n.poll_interval_ms!="number"||!Number.isFinite(n.poll_interval_ms))throw new Error('"poll_interval_ms" must be a finite number');s=Math.max(XI,n.poll_interval_ms)}let i=["none","linear","exponential"],a="none";if(n.backoff!==void 0){if(!i.includes(n.backoff))throw new Error(`"backoff" must be one of: ${i.join(", ")}`);a=n.backoff}switch(r){case"url":{if(typeof n.url!="string"||n.url.trim()==="")throw new Error('"url" is required for type "url"');let c=n.body_contains!==void 0,l=n.method??(c?"GET":"HEAD");if(l!=="HEAD"&&l!=="GET")throw new Error('"method" must be "HEAD" or "GET"');return{condition:{type:"url",url:n.url,method:l,...n.expected_status!==void 0?{expected_status:Number(n.expected_status)}:{},...c?{body_contains:String(n.body_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"file":{if(typeof n.path!="string"||n.path.trim()==="")throw new Error('"path" is required for type "file"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"file",path:c!==void 0&&!VI.isAbsolute(n.path)?VI.resolve(c,n.path):n.path,workspaceRoot:c,...n.content_contains!==void 0?{content_contains:String(n.content_contains)}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"process":{if(typeof n.pid!="number"||!Number.isInteger(n.pid)||n.pid<=1)throw new Error('"pid" is required for type "process" and must be an integer > 1');return{condition:{type:"process",pid:n.pid},timeoutMs:o,pollIntervalMs:s,backoff:a}}case"command":{if(typeof n.command!="string"||n.command.trim()==="")throw new Error('"command" is required for type "command"');let c=e?.resolveBase??e?.cwd;return{condition:{type:"command",command:n.command,...c!==void 0?{cwd:c}:{}},timeoutMs:o,pollIntervalMs:s,backoff:a}}default:throw new Error(`Unknown type "${r}". Must be one of: url, file, process, command`)}}var YI,QI=h(()=>{"use strict";Ir();WI();JI();YI=async(t,e,n)=>{let r;try{r=q4(t,n)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{condition:o,timeoutMs:s,pollIntervalMs:i,backoff:a}=r;if(o.type==="url"){let u=await Rr(o.url);if(!u.allowed)return{content:`SSRF guard blocked: ${u.reason}`,isError:!0}}let l=await zI(u=>{switch(o.type){case"url":return UI(o,u);case"file":return BI(o,u);case"process":return Promise.resolve(jI(o,n?.spawnedPidRegistry));case"command":return Promise.resolve(HI(o))}},{timeout_ms:s,poll_interval_ms:i,backoff:a,signal:e});return{content:`Wait ${l.status}: ${o.type} condition (${l.elapsed_ms}ms elapsed, ${l.attempts} attempt${l.attempts===1?"":"s"})`+(l.result?` \u2014 ${l.result.detail}`:"")+(l.error?` \u2014 error: ${l.error}`:""),isError:l.status==="failed"}}});import{createHash as G4}from"crypto";import{readFile as X4}from"fs/promises";function z4(t){return G4("sha256").update(t,"utf8").digest("hex")}function J4(t,e){if(e.length===0)return 0;let n=0,r=0;for(;(r=t.indexOf(e,r))!==-1;)n++,r+=e.length;return n}async function ZI(t,e,n){let r=[],o=new Map;for(let s of t){let i=s.path,a;try{a=de(i,n,"write",e)}catch(l){r.push({path:i,error:"path_containment",detail:l instanceof Error?l.message:String(l)});continue}try{To(a,"patch_apply")}catch(l){r.push({path:i,error:"write_denied",detail:l instanceof Error?l.message:String(l)});continue}if(s.edits!==void 0&&s.content!==void 0){r.push({path:i,error:"mutually_exclusive",detail:"`edits` and `content` cannot both be provided for the same file."});continue}if(s.edits===void 0&&s.content===void 0){r.push({path:i,error:"no_change_specified",detail:"At least one of `edits` or `content` must be provided."});continue}let c;try{c=await X4(a,"utf-8")}catch(l){if(s.expected_hash!==void 0||s.edits!==void 0){r.push({path:i,error:"file_read_failed",detail:l instanceof Error?l.message:String(l)});continue}o.set(a,null),c=""}if(o.has(a)||o.set(a,c),s.expected_hash!==void 0){let l="sha256:";if(!s.expected_hash.startsWith(l)){r.push({path:i,error:"invalid_hash_format",detail:`expected_hash must start with "sha256:". Got: "${s.expected_hash}"`});continue}let d=s.expected_hash.slice(l.length),u=z4(c);if(u!==d){r.push({path:i,error:"hash_mismatch",detail:`File hash mismatch. Expected sha256:${d}, got sha256:${u}. The file may have been modified.`});continue}}if(s.edits!==void 0){let l=c;for(let d=0;d<s.edits.length;d++){let u=s.edits[d],p=J4(l,u.old);if(p===0){r.push({path:i,error:"edit_not_found",detail:`Edit #${d+1}: \`old\` string not found in file.`});break}else if(p>1)r.push({path:i,error:"edit_ambiguous",detail:`Edit #${d+1}: \`old\` string matches ${p} locations. Provide enough context to make it unique.`});else{let f=l.indexOf(u.old);l=l.slice(0,f)+u.new+l.slice(f+u.old.length)}}}}return{valid:r.length===0,errors:r,fileContents:o}}var eC=h(()=>{"use strict";kr();Te()});import{createHash as V4,randomBytes as Y4}from"crypto";import{writeFile as tC,rename as Q4,mkdir as Z4,unlink as py,chmod as e5,stat as t5}from"fs/promises";import{dirname as rC,join as n5,isAbsolute as r5,resolve as o5}from"path";function nC(t){return V4("sha256").update(t,"utf8").digest("hex")}function s5(t,e,n){let r=Cn(e,n);if(!r)return{text:"",payload:null};let o=[`--- a/${t}`,`+++ b/${t}`];for(let s of r.hunks){o.push(`@@ -${s.oldStart},${s.oldLines} +${s.newStart},${s.newLines} @@`);for(let i of s.lines)o.push(`${i.kind}${i.text}`)}return{text:o.join(`
352
352
  `)+`
353
- `}function i5(t,e){let n=t;for(let r of e){let o=n.indexOf(r.old);if(o===-1)throw new Error("patch_apply engine: edit old-string not found at apply time (validation may have passed a stale snapshot).");n=n.slice(0,o)+r.new+n.slice(o+r.old.length)}return n}function a5(t){let e=Y4(8).toString("hex");return n5(rC(t),`.patch-tmp-${e}`)}async function oC(t,e,n,r){let o=[];for(let u of t){let p=r5(u.path)?u.path:o5(n,u.path),f=e.get(p),m=f===null,g=f??"",y;if(u.content!==void 0)y=u.content;else if(u.edits!==void 0)y=i5(g,u.edits);else throw new Error(`patch_apply engine: change for ${u.path} has neither content nor edits.`);let b=s5(u.path,g,y);o.push({resolvedPath:p,originalContent:g,newContent:y,diffBlock:b,isNewFile:m})}let s=o.map(u=>u.diffBlock).filter(Boolean).join(`
354
- `),i=o.map(u=>({path:u.resolvedPath,before_hash:`sha256:${nC(u.originalContent)}`,after_hash:`sha256:${nC(u.newContent)}`}));if(r)return{status:"dry_run",diff:s,files_changed:i,errors:[]};let a=[],c=[];for(let u of o){let p=a5(u.resolvedPath);try{let f;if(!u.isNewFile)try{f=(await t5(u.resolvedPath)).mode}catch{}await Z4(rC(u.resolvedPath),{recursive:!0}),await tC(p,u.newContent,"utf-8"),f!==void 0&&await e5(p,f),a.push({tempPath:p,targetPath:u.resolvedPath,originalMode:f})}catch(f){c.push({path:u.resolvedPath,error:"temp_write_failed",detail:f instanceof Error?f.message:String(f)})}}if(c.length>0){for(let u of a)try{await py(u.tempPath)}catch{}return{status:"partial_failure",diff:s,files_changed:i,errors:c}}let l=[],d=[];for(let u=0;u<a.length;u++){let p=a[u];try{await Q4(p.tempPath,p.targetPath),d.push({targetPath:p.targetPath,originalContent:o[u].originalContent,isNewFile:o[u].isNewFile})}catch(f){l.push({path:p.targetPath,error:"rename_failed",detail:f instanceof Error?f.message:String(f)})}}if(l.length>0){for(let u of d)try{u.isNewFile?await py(u.targetPath):await tC(u.targetPath,u.originalContent,"utf-8")}catch{}for(let u of a)try{await py(u.tempPath)}catch{}return{status:"partial_failure",diff:s,files_changed:i,errors:l}}return{status:"applied",diff:s,files_changed:i,errors:[]}}var sC=h(()=>{"use strict";Ci()});import{resolve as c5}from"path";function l5(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object.");let e=t;if(!Array.isArray(e.changes))throw new Error('Input must have a "changes" field of type array.');let n=[];for(let o=0;o<e.changes.length;o++){let s=e.changes[o];if(typeof s!="object"||s===null)throw new Error(`changes[${o}] must be an object.`);let i=s;if(typeof i.path!="string"||i.path.trim()==="")throw new Error(`changes[${o}].path must be a non-empty string.`);let a={path:i.path};if(i.expected_hash!==void 0){if(typeof i.expected_hash!="string")throw new Error(`changes[${o}].expected_hash must be a string.`);a.expected_hash=i.expected_hash}if(i.content!==void 0){if(typeof i.content!="string")throw new Error(`changes[${o}].content must be a string.`);a.content=i.content}if(i.edits!==void 0){if(!Array.isArray(i.edits))throw new Error(`changes[${o}].edits must be an array.`);let c=[];for(let l=0;l<i.edits.length;l++){let d=i.edits[l];if(typeof d!="object"||d===null)throw new Error(`changes[${o}].edits[${l}] must be an object.`);let u=d;if(typeof u.old!="string")throw new Error(`changes[${o}].edits[${l}].old must be a string.`);if(typeof u.new!="string")throw new Error(`changes[${o}].edits[${l}].new must be a string.`);c.push({old:u.old,new:u.new})}a.edits=c}n.push(a)}let r=!1;if(e.dry_run!==void 0){if(typeof e.dry_run!="boolean")throw new Error("dry_run must be a boolean.");r=e.dry_run}return{changes:n,dry_run:r}}function fy(t){return async(e,n,r)=>{let o=r?.resolveBase??r?.cwd??t??c5(process.cwd()),s;try{s=l5(e)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{changes:i,dry_run:a}=s;if(i.length===0)return{content:JSON.stringify({status:"applied",diff:"",files_changed:[],errors:[]},null,2),isError:!1};let c=await ZI(i,o,r);if(!c.valid){let u={status:"validation_failed",diff:"",files_changed:[],errors:c.errors};return{content:JSON.stringify(u,null,2),isError:!0}}let l=await oC(i,c.fileContents,o,a),d=l.status==="validation_failed"||l.status==="partial_failure";return{content:JSON.stringify({status:l.status,diff:l.diff,files_changed:l.files_changed,errors:l.errors},null,2),isError:d}}}var iC,aC=h(()=>{"use strict";eC();sC();iC=fy()});import my from"fs";import rt from"path";function Xt(t){try{return my.accessSync(t),!0}catch{return!1}}function gy(t){try{return my.readFileSync(t,"utf8")}catch{return null}}function d5(t){return Xt(rt.join(t,"pnpm-lock.yaml"))?"pnpm":Xt(rt.join(t,"yarn.lock"))?"yarn":Xt(rt.join(t,"bun.lockb"))?"bun":"npm"}function u5(t){return/\bvitest\b/.test(t)?"vitest":/\bjest\b/.test(t)?"jest":/\bmocha\b/.test(t)?"mocha":null}function p5(t){let e=rt.join(t,"package.json"),n=gy(e);if(!n)return null;let r;try{r=JSON.parse(n)}catch{return null}let o=r.scripts;if(!o||typeof o!="object")return null;let s=d5(t);for(let i of["test:unit","test:integration","test"]){let a=o[i];if(typeof a!="string"||!a.trim())continue;let c=u5(a)??"node-generic",l=`${s} run ${i}`;return{runner:c,command:l,args:[s,"run",i]}}return null}function f5(t){let e=rt.join(t,"pyproject.toml"),n=gy(e);return n?/\[tool\.pytest/.test(n)?{runner:"pytest",command:"pytest",args:["pytest"]}:Xt(rt.join(t,"pytest.ini"))||Xt(rt.join(t,"setup.cfg"))?{runner:"pytest",command:"pytest",args:["pytest"]}:null:null}function m5(t){return Xt(rt.join(t,"Cargo.toml"))?{runner:"cargo",command:"cargo test",args:["cargo","test"]}:null}function g5(t){let n=(()=>{try{return my.readdirSync(t)}catch{return[]}})().some(r=>r.endsWith("_test.go"));return(n||Xt(rt.join(t,"go.mod")))&&(n||Xt(rt.join(t,"go.mod")))?{runner:"go-test",command:"go test ./...",args:["go","test","./..."]}:null}function h5(t){return Xt(rt.join(t,"Gemfile"))&&Xt(rt.join(t,"spec"))?{runner:"rspec",command:"bundle exec rspec",args:["bundle","exec","rspec"]}:null}function y5(t){let e=gy(rt.join(t,"Makefile"));return e&&/^test:/m.test(e)?{runner:"node-generic",command:"make test",args:["make","test"]}:null}function cC(t){return p5(t)??f5(t)??m5(t)??g5(t)??h5(t)??y5(t)??null}var lC=h(()=>{"use strict"});function b5(t){let e=[],n=/^\s*●\s+(.+?)\s*$/gm,r=/^FAIL\s+(.+\.(?:test|spec)\.[jt]sx?)\s*$/gm,o=t.split(`
353
+ `,payload:r}}function i5(t,e){let n=t;for(let r of e){let o=n.indexOf(r.old);if(o===-1)throw new Error("patch_apply engine: edit old-string not found at apply time (validation may have passed a stale snapshot).");n=n.slice(0,o)+r.new+n.slice(o+r.old.length)}return n}function a5(t){let e=Y4(8).toString("hex");return n5(rC(t),`.patch-tmp-${e}`)}async function oC(t,e,n,r){let o=[];for(let g of t){let y=r5(g.path)?g.path:o5(n,g.path),b=e.get(y),S=b===null,T=b??"",_;if(g.content!==void 0)_=g.content;else if(g.edits!==void 0)_=i5(T,g.edits);else throw new Error(`patch_apply engine: change for ${g.path} has neither content nor edits.`);let A=s5(g.path,T,_);o.push({resolvedPath:y,originalContent:T,newContent:_,diffBlock:A.text,diffPayload:A.payload,filePath:g.path,isNewFile:S})}let s=o.map(g=>g.diffBlock).filter(Boolean).join(`
354
+ `),i=[],a=0,c=0;for(let g of o)if(g.diffPayload){for(let y of g.diffPayload.hunks)i.push({...y,filePath:g.filePath});a+=g.diffPayload.addedLines,c+=g.diffPayload.removedLines}let l=i.length>0?{hunks:i,addedLines:a,removedLines:c}:void 0,d=o.map(g=>({path:g.resolvedPath,before_hash:`sha256:${nC(g.originalContent)}`,after_hash:`sha256:${nC(g.newContent)}`}));if(r)return{status:"dry_run",diff:s,structuredDiff:l,files_changed:d,errors:[]};let u=[],p=[];for(let g of o){let y=a5(g.resolvedPath);try{let b;if(!g.isNewFile)try{b=(await t5(g.resolvedPath)).mode}catch{}await Z4(rC(g.resolvedPath),{recursive:!0}),await tC(y,g.newContent,"utf-8"),b!==void 0&&await e5(y,b),u.push({tempPath:y,targetPath:g.resolvedPath,originalMode:b})}catch(b){p.push({path:g.resolvedPath,error:"temp_write_failed",detail:b instanceof Error?b.message:String(b)})}}if(p.length>0){for(let g of u)try{await py(g.tempPath)}catch{}return{status:"partial_failure",diff:s,files_changed:d,errors:p}}let f=[],m=[];for(let g=0;g<u.length;g++){let y=u[g];try{await Q4(y.tempPath,y.targetPath),m.push({targetPath:y.targetPath,originalContent:o[g].originalContent,isNewFile:o[g].isNewFile})}catch(b){f.push({path:y.targetPath,error:"rename_failed",detail:b instanceof Error?b.message:String(b)})}}if(f.length>0){for(let g of m)try{g.isNewFile?await py(g.targetPath):await tC(g.targetPath,g.originalContent,"utf-8")}catch{}for(let g of u)try{await py(g.tempPath)}catch{}return{status:"partial_failure",diff:s,files_changed:d,errors:f}}return{status:"applied",diff:s,structuredDiff:l,files_changed:d,errors:[]}}var sC=h(()=>{"use strict";Ci()});import{resolve as c5}from"path";function l5(t){if(typeof t!="object"||t===null)throw new Error("Input must be an object.");let e=t;if(!Array.isArray(e.changes))throw new Error('Input must have a "changes" field of type array.');let n=[];for(let o=0;o<e.changes.length;o++){let s=e.changes[o];if(typeof s!="object"||s===null)throw new Error(`changes[${o}] must be an object.`);let i=s;if(typeof i.path!="string"||i.path.trim()==="")throw new Error(`changes[${o}].path must be a non-empty string.`);let a={path:i.path};if(i.expected_hash!==void 0){if(typeof i.expected_hash!="string")throw new Error(`changes[${o}].expected_hash must be a string.`);a.expected_hash=i.expected_hash}if(i.content!==void 0){if(typeof i.content!="string")throw new Error(`changes[${o}].content must be a string.`);a.content=i.content}if(i.edits!==void 0){if(!Array.isArray(i.edits))throw new Error(`changes[${o}].edits must be an array.`);let c=[];for(let l=0;l<i.edits.length;l++){let d=i.edits[l];if(typeof d!="object"||d===null)throw new Error(`changes[${o}].edits[${l}] must be an object.`);let u=d;if(typeof u.old!="string")throw new Error(`changes[${o}].edits[${l}].old must be a string.`);if(typeof u.new!="string")throw new Error(`changes[${o}].edits[${l}].new must be a string.`);c.push({old:u.old,new:u.new})}a.edits=c}n.push(a)}let r=!1;if(e.dry_run!==void 0){if(typeof e.dry_run!="boolean")throw new Error("dry_run must be a boolean.");r=e.dry_run}return{changes:n,dry_run:r}}function fy(t){return async(e,n,r)=>{let o=r?.resolveBase??r?.cwd??t??c5(process.cwd()),s;try{s=l5(e)}catch(u){return{content:u instanceof Error?u.message:String(u),isError:!0}}let{changes:i,dry_run:a}=s;if(i.length===0)return{content:JSON.stringify({status:"applied",diff:"",files_changed:[],errors:[]},null,2),isError:!1};let c=await ZI(i,o,r);if(!c.valid){let u={status:"validation_failed",diff:"",files_changed:[],errors:c.errors};return{content:JSON.stringify(u,null,2),isError:!0}}let l=await oC(i,c.fileContents,o,a),d=l.status==="validation_failed"||l.status==="partial_failure";return{content:JSON.stringify({status:l.status,diff:l.diff,files_changed:l.files_changed,errors:l.errors},null,2),isError:d,...l.structuredDiff?{render:{diff:l.structuredDiff}}:{}}}}var iC,aC=h(()=>{"use strict";eC();sC();iC=fy()});import my from"fs";import rt from"path";function Xt(t){try{return my.accessSync(t),!0}catch{return!1}}function gy(t){try{return my.readFileSync(t,"utf8")}catch{return null}}function d5(t){return Xt(rt.join(t,"pnpm-lock.yaml"))?"pnpm":Xt(rt.join(t,"yarn.lock"))?"yarn":Xt(rt.join(t,"bun.lockb"))?"bun":"npm"}function u5(t){return/\bvitest\b/.test(t)?"vitest":/\bjest\b/.test(t)?"jest":/\bmocha\b/.test(t)?"mocha":null}function p5(t){let e=rt.join(t,"package.json"),n=gy(e);if(!n)return null;let r;try{r=JSON.parse(n)}catch{return null}let o=r.scripts;if(!o||typeof o!="object")return null;let s=d5(t);for(let i of["test:unit","test:integration","test"]){let a=o[i];if(typeof a!="string"||!a.trim())continue;let c=u5(a)??"node-generic",l=`${s} run ${i}`;return{runner:c,command:l,args:[s,"run",i]}}return null}function f5(t){let e=rt.join(t,"pyproject.toml"),n=gy(e);return n?/\[tool\.pytest/.test(n)?{runner:"pytest",command:"pytest",args:["pytest"]}:Xt(rt.join(t,"pytest.ini"))||Xt(rt.join(t,"setup.cfg"))?{runner:"pytest",command:"pytest",args:["pytest"]}:null:null}function m5(t){return Xt(rt.join(t,"Cargo.toml"))?{runner:"cargo",command:"cargo test",args:["cargo","test"]}:null}function g5(t){let n=(()=>{try{return my.readdirSync(t)}catch{return[]}})().some(r=>r.endsWith("_test.go"));return(n||Xt(rt.join(t,"go.mod")))&&(n||Xt(rt.join(t,"go.mod")))?{runner:"go-test",command:"go test ./...",args:["go","test","./..."]}:null}function h5(t){return Xt(rt.join(t,"Gemfile"))&&Xt(rt.join(t,"spec"))?{runner:"rspec",command:"bundle exec rspec",args:["bundle","exec","rspec"]}:null}function y5(t){let e=gy(rt.join(t,"Makefile"));return e&&/^test:/m.test(e)?{runner:"node-generic",command:"make test",args:["make","test"]}:null}function cC(t){return p5(t)??f5(t)??m5(t)??g5(t)??h5(t)??y5(t)??null}var lC=h(()=>{"use strict"});function b5(t){let e=[],n=/^\s*●\s+(.+?)\s*$/gm,r=/^FAIL\s+(.+\.(?:test|spec)\.[jt]sx?)\s*$/gm,o=t.split(`
355
355
  `),s=0;for(;s<o.length;){let i=o[s],a=r.exec(i);if(a){let l=a[1]?.trim(),d=s+1;for(;d<o.length;){let u=o[d],p=/^\s+[×✕✗x]\s+(.+)$/.exec(u);if(p){let f=p[1]?.trim()??"unknown",m="",g=d+1;for(;g<o.length&&/^\s+/.test(o[g]);){let y=o[g].trim();y&&!y.startsWith("at ")&&(m=m||y),g++}e.push({name:f,file:l,message:m||"Test failed"})}else if(u.trim()===""&&d>s+2)break;d++}r.lastIndex=0,s++;continue}let c=n.exec(i);if(c){let l=c[1]?.trim()??"unknown",d="",u="",p,f,m=s+1;for(;m<o.length;){let g=o[m];if(/^\s*●\s+/.test(g))break;if(!d&&/^\s+(?:expect|assert|Error|AssertionError)/.test(g)&&(d=g.trim()),!p){let y=/at\s+\S+\s+\((.+?):(\d+):\d+\)/.exec(g);y&&(p=y[1]?.trim(),f=parseInt(y[2],10))}u+=g+`
356
356
  `,m++}e.push({name:l,...p?{file:p}:{},...f!==void 0?{line:f}:{},message:d||"Test failed",...u.trim()?{stack:u.trim()}:{}}),n.lastIndex=0,s=m;continue}n.lastIndex=0,r.lastIndex=0,s++}return e}function w5(t){let e=[],n=/^FAILED\s+(.+?)::([^\s-]+)\s*(?:-\s*(.+))?$/gm,r;for(;(r=n.exec(t))!==null;){let o=r[1]?.trim(),s=r[2]?.trim()??"unknown",i=r[3]?.trim()??"Test failed";e.push({name:s,...o?{file:o}:{},message:i})}return e}function S5(t){let e=[],n=/^test\s+(\S+)\s+\.\.\.\s+FAILED$/gm,r;for(;(r=n.exec(t))!==null;)e.push({name:r[1]??"unknown",message:"Test failed"});let o=/^-{4}\s+(\S+)\s+stdout\s+-{4}$([\s\S]*?)(?=^-{4}|\z)/gm;for(;(r=o.exec(t))!==null;){let s=r[1]??"unknown",i=r[2]?.trim()??"",a=e.find(c=>c.name===s);a&&i&&(a.message=i.split(`
357
357
  `)[0]?.trim()??a.message,a.stack=i)}return e}function k5(t){let e=[],n=/^---\s+FAIL:\s+(\S+)\s+\([\d.]+s\)/gm,r;for(;(r=n.exec(t))!==null;)e.push({name:r[1]??"unknown",message:"Test failed"});return e}function v5(t){let e=[],n=/^\s+\d+\)\s+(.+?)\s*$/gm,r=t.split(`
@@ -8,6 +8,7 @@ export interface DiffHunk {
8
8
  newStart: number;
9
9
  newLines: number;
10
10
  lines: DiffLine[];
11
+ filePath?: string;
11
12
  }
12
13
  export interface DiffPayload {
13
14
  hunks: DiffHunk[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-afk",
3
- "version": "5.185.0",
3
+ "version": "5.186.0",
4
4
  "description": "Open-source coding-agent harness you can actually change — own the loop (prompts, gates, routing, skills, terminal states), use any model, run long tasks while you're away.",
5
5
  "main": "dist/index.mjs",
6
6
  "types": "dist/index.d.ts",