agent-afk 5.114.0 → 5.114.1
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/cli.mjs
CHANGED
|
@@ -314,7 +314,7 @@ ${o}`,paths:[t,n]}:o!==null?i={content:o,paths:[n]}:r!==null?i={content:r,paths:
|
|
|
314
314
|
|
|
315
315
|
${t}`}var Mae,nR=y(()=>{"use strict";Mae=new Set(["script","style","noscript","template","svg"])});function Dae(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason??new Error("aborted"));return}let o=()=>{clearTimeout(i),r(t?.reason??new Error("aborted"))},i=setTimeout(()=>{t?.removeEventListener("abort",o),n()},e);t?.addEventListener("abort",o,{once:!0})})}function uL(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function Fae(e,t){let n=e.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,t)}async function pL(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??Dae,l=n.signal??void 0,c;for(let d=0;d<=o;d++){if(l?.aborted)throw l.reason??new Error("aborted");try{let u=await e(t,n);if(!$ae.has(u.status)||d===o)return u;let p=Fae(u,s)??uL(d,i,s);B("[web/retryFetch] retrying",{url:t,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let p=uL(d,i,s);B("[web/retryFetch] retrying after error",{url:t,attempt:d,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var $ae,mL=y(()=>{"use strict";me();$ae=new Set([429,502,503,504])});import{BlockList as Lae,isIP as oR}from"node:net";import{lookup as Nae}from"node:dns/promises";import{Agent as Bae}from"undici";function gL(){let e=k.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return e==="1"||e==="true"}function Hae(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function rR(e){let t=oR(e);return t===0?!1:Wae.check(e,t===4?"ipv4":"ipv6")}async function hL(e){return Nae(e,{all:!0,verbatim:!0})}async function iR(e,t={}){if(t.allowPrivateHosts??gL())return{allowed:!0};let n;try{n=new URL(e)}catch{return{allowed:!1,reason:`"${e}" 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=Hae(n.hostname),o=(a,l)=>`refusing to fetch ${l} \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(oR(r)!==0)return rR(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let i=t.lookupFn??hL,s;try{s=await i(r)}catch{return{allowed:!0}}for(let a of s)if(rR(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Du(e,t={}){let n=await iR(e,t);if(!n.allowed)throw new Vn(n.reason)}async function ch(e,t,n={},r={}){let o={...r.lookupFn!==void 0?{lookupFn:r.lookupFn}:{},...r.allowPrivateHosts!==void 0?{allowPrivateHosts:r.allowPrivateHosts}:{}},i=t;for(let s=0;s<=fL;s++){await Du(i,o);let a={...n,redirect:"manual",...e===globalThis.fetch&&!(r.allowPrivateHosts??gL())?{dispatcher:Kae}:{}},l=await pL(e,i,a,r.retry??{});if(!Gae.has(l.status))return l;let c=l.headers.get("location");if(c===null||c.trim()==="")return l;let d;try{d=new URL(c,l.url||i).toString()}catch{return l}await l.body?.cancel().catch(()=>{}),i=d}throw new Vn(`too many redirects (>${fL}) starting from ${t}`)}var Uae,jae,Wae,Vn,Kae,fL,Gae,sR=y(()=>{"use strict";j();mL();Uae=[["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]],jae=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],Wae=(()=>{let e=new Lae;for(let[t,n]of Uae)e.addSubnet(t,n,"ipv4");for(let[t,n]of jae)e.addSubnet(t,n,"ipv6");return e})(),Vn=class extends Error{constructor(t){super(t),this.name="EgressBlockedError"}};Kae=new Bae({connect:{lookup(e,t,n){hL(e).then(r=>{let o=r.find(s=>rR(s.address));if(o!==void 0){n(new Vn(`refusing to connect to ${e} (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 i=r[0];if(i===void 0){n(new Error(`DNS lookup returned no addresses for ${e}`),"",0);return}n(null,i.address,oR(i.address))},r=>n(r,"",0))}}});fL=20,Gae=new Set([301,302,303,307,308])});import{readFileSync as qae}from"node:fs";import{join as zae}from"path";function Jae(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function yL(e,t){return Jae(t).test(e)}function Xae(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(Vae.has(t))return!0;if(Yae.has(t))return!1}return!1}function bL(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function Qae(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function wL(e){let t=e===void 0||e.trim()===""?"default":e.trim();return jd(t),t}function Zae(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function ele(e){try{return qae(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function tle(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return typeof t.defaultProfile=="string"&&(n.defaultProfile=wL(t.defaultProfile)),n}function SL(e){let t=e?.env??k,n=e?.readFileSync??ele,r=e?.surface??t.AGENT_SURFACE,o=Xae(t.AFK_BROWSER_HEADLESS,r),i=bL(t.AFK_BROWSER_ALLOWED_DOMAINS),s=bL(t.AFK_BROWSER_BLOCKED_DOMAINS),a=Zae(t.AFK_BROWSER_DOM_SNAPSHOTS),l=Qae(t.AFK_BROWSER_BACKEND),c=wL(t.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:i,blockedDomains:s,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=t.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():zae(Wn(),"browser.json"),f=n(p);if(f===void 0)return d;let g;try{g=JSON.parse(f)}catch(b){throw new Error(`Failed to parse browser config at ${p}: ${String(b)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=tle(d,g);return h.configPath=p,h}function dh(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(yL(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>yL(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Vae,Yae,uh=y(()=>{"use strict";j();K();Vae=new Set(["daemon","subagent","telegram","afk"]),Yae=new Set(["repl","interactive","cli"])});import{existsSync as nle,readFileSync as rle}from"node:fs";import{createRequire as ole}from"node:module";import{dirname as ile,join as sle}from"node:path";function TL(e){if(typeof e=="string")return e;let t=[],n=e;for(let r=0;r<lle&&n instanceof Error;r++)t.push(n.message),n=n.cause;return t.length>0?t.join(" | "):String(e)}function Yt(e){let t=TL(e);return kL.some(n=>t.includes(n))}function cle(){try{let t=ole(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(rle(t,"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 i=sle(ile(t),o);return nle(i)?`node ${/\s/.test(i)?`"${i}"`:i} install chromium`:void 0}catch{return}}function Fu(){return vL??=cle()??ale,vL}function aR(e){return e.includes("install chromium")}function An(e,t){let n=TL(e),r=t?.latched===!0?` ${dle}`:"";if(n.includes("Executable doesn't exist")){let o="";return t?.headless===!0?o=" This launch was headless, which needs the `chromium_headless_shell-*` build.":t?.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: ${Fu()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Fu()}). Or pick a different tool.${r}`}function Lu(e,t,n=!1){if(!Yt(e))return e;let r=e instanceof Error?e.message:String(e);return new Error(`${r}
|
|
316
316
|
|
|
317
|
-
${An(e,{headless:t,latched:n})}`,{cause:e})}var kL,ale,lle,vL,dle,ph=y(()=>{"use strict";kL=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],ale="pnpm exec playwright install chromium",lle=4;dle="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 Ts from"node:fs";import mh from"node:path";import{randomBytes as ule}from"node:crypto";import{chromium as ple}from"playwright";function mle(){try{return"5.114.0"}catch{}try{let e=mh.resolve(import.meta.dirname,"../../../package.json"),t=Ts.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var fle,fh,EL=y(()=>{"use strict";ph();K();me();fle=mle(),fh=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(t){this.config=t}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(t){this.launchFailure={error:t}}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=ple.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,this.clearLaunchFailure(),t)).catch(t=>{this.launchPromise=void 0;let n=Lu(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){i=l,await a.abort("blockedbyclient")}});let s=()=>{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",s,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw i??p}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;let d=a.url(),u=l!==null?l.status():null;return{html:c,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);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(t){this.clearLaunchFailure();let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),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 t=[...this.sessions.keys()];if(await Promise.all(t.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/${fle}`}}loadStorageState(t){let n=Wd(t);try{if(!Ts.existsSync(n))return;let r=JSON.parse(Ts.readFileSync(n,"utf8"));return B("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){B("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Wd(t);if(!Ts.existsSync(r))return;let o=await n.storageState(),i=mh.join(mh.dirname(r),`.${mh.basename(r)}.${process.pid}.${ule(4).toString("hex")}.tmp`);Ts.writeFileSync(i,JSON.stringify(o),{mode:384}),Ts.chmodSync(i,384),Ts.renameSync(i,r),B("[browser/vault] saved session",{profile:t,file:r})}catch(r){B("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as gle}from"crypto";function RL(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&hle.test(e.label))}function xL(e){return gle("sha256").update(e,"utf8").digest("hex").slice(0,8)}function AL(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var hle,gh=y(()=>{"use strict";hle=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as yle}from"node:crypto";function ble(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function wle(e,t,n){return`el_${yle("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function Sle(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function CL(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function IL(e,t){let n=e.role??"",r=e.name??"";_L.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])IL(i,t)}async function vle(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let d=window.getComputedStyle(s);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},PL).catch(()=>[])}async function kle(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in i?i.value:void 0,u=d!==void 0?String(d):void 0,p=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},PL).catch(()=>[])}function Tle(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function hh(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=Tle(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=vle(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,p,f,g,h]=await Promise.all([s,a,l,c,d]),b,w=!1;u!==null?(b=[],IL(u,b)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,b=(await kle(e)).filter($=>_L.has($.role??"")));let S=new Map;for(let P of p){let $=CL(P.name),q=S.get($);(!q||q.bbox.w===0&&P.bbox.w>0)&&S.set($,P)}let v=b.map(P=>({ax:P,dom:S.get(CL(P.name??""))})),E=r?v:v.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);E.sort((P,$)=>{let q=P.dom?.bbox.y??0,F=$.dom?.bbox.y??0;if(q!==F)return q-F;let W=P.dom?.bbox.x??0,G=$.dom?.bbox.x??0;return W-G}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=E.slice(0,n).map((P,$)=>{let q=P.ax.role??"generic",F=P.ax.name??"",W=wle(q,F,$),G=P.dom?.bbox??{x:0,y:0,w:0,h:0},I=P.dom?.type??null,L=null;P.ax.value!==void 0&&P.ax.value!==null&&(L=String(P.ax.value)),P.ax.checked!==void 0&&(L=String(P.ax.checked)),RL({role:q,kind:I})&&(L="[redacted]");let O={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(O.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(O.selected=P.ax.selected),P.ax.expanded!==void 0&&(O.expanded=P.ax.expanded);let D;P.dom?.testId?D=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(D=`#${P.dom.id}`);let H={id:W,role:q,label:ble(F),kind:I,value:L,state:O,bbox:G};return D!==void 0&&(H.selector=D),H}),M="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?M="loading":P==="interactive"?M="navigating":M="idle"}catch{M="navigating"}M!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let _=Sle(f),x=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:x,url:g,title:h,textSummary:_,interactive:A,status:{httpStatus:t.httpStatus??null,loadingState:M,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var _L,PL,ML=y(()=>{"use strict";gh();_L=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);PL="a[href], button, input, select, textarea, [role], [tabindex], label"});async function OL(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>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 lR(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>OL(e,i)))).filter(o=>o!==null)}async function Ele(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function cR(e,t,n){switch(t.kind){case"element_id":return Rle(e,t,n);case"selector":return xle(e,t);case"semantic":return Ale(e,t)}}async function Rle(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await lR(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function xle(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await lR(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function Ale(e,t){return t.role!==void 0?Cle(e,t.text,t.role):_le(e,t.text,t)}async function Cle(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await lR(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function _le(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let d=[];s>0&&d.push({loc:r,count:s}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:i,count:l});let u=await Ele(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=u.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let w=await OL(b.locator,b.index);if(w!==null){let S=`${w.role}:${w.label}:${h}`,v=0;for(let E=0;E<S.length;E++)v=v*31+S.charCodeAt(E)>>>0;f.push({...w,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var $L=y(()=>{"use strict"});async function dR(e,t,n,r){let o=e.url();if(o===n)return null;let i=dh(o,t);if(i.allowed)return null;try{await e.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:i.reason}}var DL=y(()=>{"use strict";uh()});import{randomBytes as Ile}from"crypto";import{mkdir as Ple,stat as Mle,writeFile as Ole}from"fs/promises";import{join as uR}from"path";import{gzip as $le}from"zlib";import{promisify as Dle}from"util";function Fle(e){return uR(sn(e),"browser")}function Lle(e){return uR(Fle(e),"screenshots")}function Nle(){return new Date().toISOString().replace(/[:.]/g,"-")}function Ble(){return Ile(3).toString("hex")}async function pR(e,t,n){if(t.length>FL)throw new Error(`writeScreenshotSidecar: buffer exceeds ${FL} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=Lle(e);await Ple(r,{recursive:!0});let o=`${Nle()}-${Ble()}-${n}.png`,i=uR(r,o);await Ole(i,t);let{size:s}=await Mle(i);return{path:i,bytes:s}}var R2e,FL,LL=y(()=>{"use strict";K();gh();R2e=Dle($le);FL=5*1024*1024});var BL={};Fo(BL,{PlaywrightProvider:()=>mR});function NL(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var mR,UL=y(()=>{"use strict";EL();ML();$L();uh();DL();LL();mR=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new fh(t)}async open(t){let n=dh(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await dR(o,this.config,t.url,()=>this.close({sessionId:r}));if(u!==null)return u}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let d=await hh(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(t){let{sessionId:n}=t,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),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await hh(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,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),i=r.url(),s=t.timeoutMs??3e4,a=await cR(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${NL(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":await l.fill(t.value??"");break;case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(b){c=b}else c=h}let u=await dR(r,this.config,i,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await hh(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,requestGuard:t.requestGuard})}async screenshot(t){let{sessionId:n}=t,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),i;if(t.target!==void 0){let d=await cR(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${NL(t.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await d.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await pR(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);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(t){let n=this.sessions.get(t);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(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await pR(n,o,r);return i}catch{return null}}}});var Rs={};Fo(Rs,{__resetBrowserRegistryForTests:()=>Kle,browserProviderActive:()=>Wle,closeBrowserProvider:()=>fR,getBrowserProvider:()=>jle,peekBrowserProvider:()=>Hle});function jL(){Promise.resolve(fR()).then(()=>{process.exit(130)})}function WL(){Promise.resolve(fR()).then(()=>{process.exit(143)})}function HL(){Ar=null}function Ule(){yh||(process.on("SIGINT",jL),process.on("SIGTERM",WL),process.on("exit",HL),yh=!0)}function KL(){yh&&(process.removeListener("SIGINT",jL),process.removeListener("SIGTERM",WL),process.removeListener("exit",HL),yh=!1)}async function jle(e){return Ar!==null?Ar:(Es!==null||(Es=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(UL(),BL)),n=SL(e),r=new t(n);return Ule(),Ar=r,Es=null,r})()),Es)}async function fR(){if(Ar===null)return;let e=Ar;Ar=null,Es=null,KL(),await e.shutdown()}function Wle(){return Ar!==null}function Hle(){return Ar}function Kle(){Ar=null,Es=null,KL()}var Ar,Es,yh,xs=y(()=>{"use strict";uh();Ar=null,Es=null,yh=!1});async function GL(e,t){try{return await lL(e,t)}catch(n){return B("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function Yle(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(xs(),Rs));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function qL(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??Yle,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let u=await ch(n,e,{headers:Vle,signal:t.signal},o);l=u.status,a=u.url||e;let p=u.headers.get("content-type")??"";if(u.ok){if(Jle.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(zle.test(p)&&!qle.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await GL(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(u){if(t.signal.aborted||u instanceof Vn||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;c=u}if(!(i===null||i.textLength<200)&&i!==null){let u=tR({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Du(e,o);let u=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>Du(f,o)});u.finalUrl!==e&&/^https?:\/\//i.test(u.finalUrl)&&await Du(u.finalUrl,o);let p=await GL(u.html,u.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=tR({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(t.signal.aborted||u instanceof Vn)throw u;if(i===null){let p=u instanceof Error?u.message:String(u),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,g=new Error(`web_scrape could not retrieve ${e}: fetch failed (${f}) and render failed (${p}).`);throw g.cause=u,g}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${l??"error"}).`)}var qle,zle,Jle,Vle,zL=y(()=>{"use strict";cL();nR();sR();me();qle=/(text\/html|application\/xhtml\+xml)/i,zle=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,Jle=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,Vle={"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 Zle(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(Xle,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),Qle),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Ye(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function JL(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?Zle({apiKey:e.exaApiKey,fetchFn:e.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 VL(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
317
|
+
${An(e,{headless:t,latched:n})}`,{cause:e})}var kL,ale,lle,vL,dle,ph=y(()=>{"use strict";kL=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],ale="pnpm exec playwright install chromium",lle=4;dle="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 Ts from"node:fs";import mh from"node:path";import{randomBytes as ule}from"node:crypto";import{chromium as ple}from"playwright";function mle(){try{return"5.114.1"}catch{}try{let e=mh.resolve(import.meta.dirname,"../../../package.json"),t=Ts.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var fle,fh,EL=y(()=>{"use strict";ph();K();me();fle=mle(),fh=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(t){this.config=t}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(t){this.launchFailure={error:t}}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=ple.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,this.clearLaunchFailure(),t)).catch(t=>{this.launchPromise=void 0;let n=Lu(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){i=l,await a.abort("blockedbyclient")}});let s=()=>{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",s,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw i??p}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;let d=a.url(),u=l!==null?l.status():null;return{html:c,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);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(t){this.clearLaunchFailure();let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),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 t=[...this.sessions.keys()];if(await Promise.all(t.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/${fle}`}}loadStorageState(t){let n=Wd(t);try{if(!Ts.existsSync(n))return;let r=JSON.parse(Ts.readFileSync(n,"utf8"));return B("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){B("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Wd(t);if(!Ts.existsSync(r))return;let o=await n.storageState(),i=mh.join(mh.dirname(r),`.${mh.basename(r)}.${process.pid}.${ule(4).toString("hex")}.tmp`);Ts.writeFileSync(i,JSON.stringify(o),{mode:384}),Ts.chmodSync(i,384),Ts.renameSync(i,r),B("[browser/vault] saved session",{profile:t,file:r})}catch(r){B("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as gle}from"crypto";function RL(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&hle.test(e.label))}function xL(e){return gle("sha256").update(e,"utf8").digest("hex").slice(0,8)}function AL(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var hle,gh=y(()=>{"use strict";hle=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as yle}from"node:crypto";function ble(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function wle(e,t,n){return`el_${yle("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function Sle(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function CL(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function IL(e,t){let n=e.role??"",r=e.name??"";_L.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])IL(i,t)}async function vle(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let i=o.getBoundingClientRect(),s=o;if(i.width===0&&i.height===0){let d=window.getComputedStyle(s);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(i.left),y:Math.round(i.top),w:Math.round(i.width),h:Math.round(i.height)}})}return r},PL).catch(()=>[])}async function kle(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let i of r){let s=i.tagName.toLowerCase(),a=i.getAttribute("role")??"",l=i.getAttribute("aria-label")??i.getAttribute("placeholder")??(i.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[s]??"");if(s==="input"){let h=i.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let d="value"in i?i.value:void 0,u=d!==void 0?String(d):void 0,p=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},PL).catch(()=>[])}function Tle(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function hh(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=Tle(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=vle(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,p,f,g,h]=await Promise.all([s,a,l,c,d]),b,w=!1;u!==null?(b=[],IL(u,b)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,b=(await kle(e)).filter($=>_L.has($.role??"")));let S=new Map;for(let P of p){let $=CL(P.name),q=S.get($);(!q||q.bbox.w===0&&P.bbox.w>0)&&S.set($,P)}let v=b.map(P=>({ax:P,dom:S.get(CL(P.name??""))})),E=r?v:v.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);E.sort((P,$)=>{let q=P.dom?.bbox.y??0,F=$.dom?.bbox.y??0;if(q!==F)return q-F;let W=P.dom?.bbox.x??0,G=$.dom?.bbox.x??0;return W-G}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=E.slice(0,n).map((P,$)=>{let q=P.ax.role??"generic",F=P.ax.name??"",W=wle(q,F,$),G=P.dom?.bbox??{x:0,y:0,w:0,h:0},I=P.dom?.type??null,L=null;P.ax.value!==void 0&&P.ax.value!==null&&(L=String(P.ax.value)),P.ax.checked!==void 0&&(L=String(P.ax.checked)),RL({role:q,kind:I})&&(L="[redacted]");let O={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(O.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(O.selected=P.ax.selected),P.ax.expanded!==void 0&&(O.expanded=P.ax.expanded);let D;P.dom?.testId?D=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(D=`#${P.dom.id}`);let H={id:W,role:q,label:ble(F),kind:I,value:L,state:O,bbox:G};return D!==void 0&&(H.selector=D),H}),M="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?M="loading":P==="interactive"?M="navigating":M="idle"}catch{M="navigating"}M!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let _=Sle(f),x=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:x,url:g,title:h,textSummary:_,interactive:A,status:{httpStatus:t.httpStatus??null,loadingState:M,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var _L,PL,ML=y(()=>{"use strict";gh();_L=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);PL="a[href], button, input, select, textarea, [role], [tabindex], label"});async function OL(e,t){try{let n=await e.nth(t).evaluate(s=>{let a=s,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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}:${t}`,o=0;for(let s=0;s<r.length;s++)o=o*31+r.charCodeAt(s)>>>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 lR(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>OL(e,i)))).filter(o=>o!==null)}async function Ele(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let i=0;i<o;i++){let s;try{s=await r.nth(i).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(s)||(t.add(s),n.push({key:s,locator:r,index:i}))}return n}async function cR(e,t,n){switch(t.kind){case"element_id":return Rle(e,t,n);case"selector":return xle(e,t);case"semantic":return Ale(e,t)}}async function Rle(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),i=await o.count();if(i===0)return{outcome:"not_found",query:t};if(i===1)return{outcome:"resolved",locator:o};let s=await lR(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function xle(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await lR(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function Ale(e,t){return t.role!==void 0?Cle(e,t.text,t.role):_le(e,t.text,t)}async function Cle(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let i=await lR(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function _le(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),i=e.getByLabel(t,{exact:!1}),[s,a,l]=await Promise.all([r.count(),o.count(),i.count()]);if(s+a+l===0)return{outcome:"not_found",query:n};let d=[];s>0&&d.push({loc:r,count:s}),a>0&&d.push({loc:o,count:a}),l>0&&d.push({loc:i,count:l});let u=await Ele(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=u.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let w=await OL(b.locator,b.index);if(w!==null){let S=`${w.role}:${w.label}:${h}`,v=0;for(let E=0;E<S.length;E++)v=v*31+S.charCodeAt(E)>>>0;f.push({...w,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var $L=y(()=>{"use strict"});async function dR(e,t,n,r){let o=e.url();if(o===n)return null;let i=dh(o,t);if(i.allowed)return null;try{await e.goBack()}catch{await r()}return{outcome:"blocked_by_policy",url:o,reason:i.reason}}var DL=y(()=>{"use strict";uh()});import{randomBytes as Ile}from"crypto";import{mkdir as Ple,stat as Mle,writeFile as Ole}from"fs/promises";import{join as uR}from"path";import{gzip as $le}from"zlib";import{promisify as Dle}from"util";function Fle(e){return uR(sn(e),"browser")}function Lle(e){return uR(Fle(e),"screenshots")}function Nle(){return new Date().toISOString().replace(/[:.]/g,"-")}function Ble(){return Ile(3).toString("hex")}async function pR(e,t,n){if(t.length>FL)throw new Error(`writeScreenshotSidecar: buffer exceeds ${FL} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=Lle(e);await Ple(r,{recursive:!0});let o=`${Nle()}-${Ble()}-${n}.png`,i=uR(r,o);await Ole(i,t);let{size:s}=await Mle(i);return{path:i,bytes:s}}var R2e,FL,LL=y(()=>{"use strict";K();gh();R2e=Dle($le);FL=5*1024*1024});var BL={};Fo(BL,{PlaywrightProvider:()=>mR});function NL(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var mR,UL=y(()=>{"use strict";EL();ML();$L();uh();DL();LL();mR=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new fh(t)}async open(t){let n=dh(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),i=this.ensureSessionState(r),s=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(u){a=u}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await dR(o,this.config,t.url,()=>this.close({sessionId:r}));if(u!==null)return u}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let d=await hh(o,{observationCounter:i.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(i,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(t){let{sessionId:n}=t,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),i=null;t.screenshot===!0&&(i=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let s=await hh(r,{observationCounter:o.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,s.interactive,s.url,s.title,"browser_observe"),s}async act(t){let{sessionId:n}=t,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),i=r.url(),s=t.timeoutMs??3e4,a=await cR(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${NL(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(t.action){case"click":await l.click({timeout:s});break;case"fill":await l.fill(t.value??"");break;case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:s});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:s});break;case"wait_for":await l.waitFor({timeout:s,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(b){c=b}else c=h}let u=await dR(r,this.config,i,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await hh(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,requestGuard:t.requestGuard})}async screenshot(t){let{sessionId:n}=t,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),i;if(t.target!==void 0){let d=await cR(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${NL(t.target)}`);if(d.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await d.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await pR(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:s,bytes:a,width:l,height:c,dataBase64:i.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);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(t){let n=this.sessions.get(t);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(t,r),r}updateSessionFromObservation(t,n,r,o,i){t.knownElements=new Map(n.map(s=>[s.id,s])),t.currentUrl=r,t.currentTitle=o,t.lastAction=i,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:i}=await pR(n,o,r);return i}catch{return null}}}});var Rs={};Fo(Rs,{__resetBrowserRegistryForTests:()=>Kle,browserProviderActive:()=>Wle,closeBrowserProvider:()=>fR,getBrowserProvider:()=>jle,peekBrowserProvider:()=>Hle});function jL(){Promise.resolve(fR()).then(()=>{process.exit(130)})}function WL(){Promise.resolve(fR()).then(()=>{process.exit(143)})}function HL(){Ar=null}function Ule(){yh||(process.on("SIGINT",jL),process.on("SIGTERM",WL),process.on("exit",HL),yh=!0)}function KL(){yh&&(process.removeListener("SIGINT",jL),process.removeListener("SIGTERM",WL),process.removeListener("exit",HL),yh=!1)}async function jle(e){return Ar!==null?Ar:(Es!==null||(Es=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(UL(),BL)),n=SL(e),r=new t(n);return Ule(),Ar=r,Es=null,r})()),Es)}async function fR(){if(Ar===null)return;let e=Ar;Ar=null,Es=null,KL(),await e.shutdown()}function Wle(){return Ar!==null}function Hle(){return Ar}function Kle(){Ar=null,Es=null,KL()}var Ar,Es,yh,xs=y(()=>{"use strict";uh();Ar=null,Es=null,yh=!1});async function GL(e,t){try{return await lL(e,t)}catch(n){return B("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function Yle(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(xs(),Rs));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function qL(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??Yle,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let u=await ch(n,e,{headers:Vle,signal:t.signal},o);l=u.status,a=u.url||e;let p=u.headers.get("content-type")??"";if(u.ok){if(Jle.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(zle.test(p)&&!qle.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await GL(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(u){if(t.signal.aborted||u instanceof Vn||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;c=u}if(!(i===null||i.textLength<200)&&i!==null){let u=tR({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Du(e,o);let u=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>Du(f,o)});u.finalUrl!==e&&/^https?:\/\//i.test(u.finalUrl)&&await Du(u.finalUrl,o);let p=await GL(u.html,u.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=tR({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(t.signal.aborted||u instanceof Vn)throw u;if(i===null){let p=u instanceof Error?u.message:String(u),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,g=new Error(`web_scrape could not retrieve ${e}: fetch failed (${f}) and render failed (${p}).`);throw g.cause=u,g}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${l??"error"}).`)}var qle,zle,Jle,Vle,zL=y(()=>{"use strict";cL();nR();sR();me();qle=/(text\/html|application\/xhtml\+xml)/i,zle=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,Jle=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,Vle={"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 Zle(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(Xle,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),Qle),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Ye(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=i.statusText?` ${i.statusText}`:"";throw new Error(`Exa Search HTTP ${i.status}${c}${l}`)}let s;try{s=await i.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(s.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function JL(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?Zle({apiKey:e.exaApiKey,fetchFn:e.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 VL(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
318
318
|
|
|
319
319
|
(no results)`;let n=[`# Search results for "${e}"`,""];return t.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(`
|
|
320
320
|
`).trimEnd()}var Xle,Qle,YL=y(()=>{"use strict";Tr();Xle="https://api.exa.ai/search",Qle=10});function bh(e){if(e instanceof Error&&e.name==="TimeoutError")return"timeout";let t=e instanceof Error?e.message:String(e);return/Timeout\s+\d+\s*ms exceeded/i.test(t)?"timeout":void 0}var As=y(()=>{"use strict";ph()});function ice(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e,n=t.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,i;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};i=t.query}else{if(typeof t.url!="string"||t.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let s=ece;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};s=Math.min(t.timeout_ms,tce)}let a=nce;if(t.max_bytes!==void 0){if(typeof t.max_bytes!="number"||!Number.isFinite(t.max_bytes)||t.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(t.max_bytes,rce)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function gR(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:Zr(e,t),truncated:!0}}function sce(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env,r=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{};return async(o,i)=>{if(typeof t!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=ice(o);if("error"in s)return{content:s.error,isError:!0};if(i.aborted){let u=i.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let a=new AbortController,l=()=>{a.abort(i.reason)},c,d=()=>{let u=a.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(i.addEventListener("abort",l,{once:!0}),c=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.url!==void 0){let p=await iR(s.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(s.mode==="raw"){let p;try{let h={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await ch(t,s.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:h instanceof Vn?{content:`web_scrape blocked: ${h.message}`,isError:!0}:{content:`web_scrape network error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let f;try{f=await p.text()}catch(h){return{content:`web_scrape read error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let g=gR(f,s.maxBytes);return{content:g.content,...g.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let p=await qL(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:a.signal,...e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{}});if(p.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0};let f=gR(dL(p.markdown,p.advisory),s.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 Vn)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),g=Yt(p)&&!aR(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Fu()}\`)`:"";return{content:`web_scrape markdown error: ${f}${g}`,isError:!0}}let u=JL({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in u)return{content:u.error,isError:!0};try{let p=await u.search(s.query,{limit:oce,timeoutMs:s.timeoutMs,signal:a.signal}),f=gR(VL(s.query,p),s.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{c!==void 0&&clearTimeout(c),i.removeEventListener("abort",l)}}}var ece,tce,nce,rce,oce,XL,QL=y(()=>{"use strict";zL();YL();sR();zo();nR();As();ece=3e4,tce=12e4,nce=1e5,rce=1e6,oce=10;XL=sce()});import{existsSync as eN,mkdirSync as ace,readFileSync as lce,renameSync as cce,unlinkSync as dce,writeFileSync as uce}from"node:fs";import{dirname as ZL,join as pce}from"node:path";import{randomBytes as mce}from"node:crypto";function Cn(e){let t=e??rT();if(!eN(t))return[];try{let n=lce(t,"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 ${t}: ${r}`),[]}}function Cs(e,t){let n=t??rT();ace(ZL(n),{recursive:!0});let r=pce(ZL(n),`.schedules.json.${process.pid}.${mce(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{uce(r,o,"utf-8"),cce(r,n)}catch(i){try{eN(r)&&dce(r)}catch{}throw i}}function wh(e,t){let n=Cn(t),r=n.map(l=>l.id),o=fce(e.name),i=gce(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),Cs(n,t),a}function Sh(e,t){let n=Cn(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(Cs(o,t),!0)}function Nu(e,t){return Cn(t).find(n=>n.id===e)}function fce(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function gce(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function tN(e){return{taskId:e.id,command:e.command,trigger:e.trigger??"cron",...e.cron!==void 0?{cronExpression:e.cron}:{},...e.notifyOn!==void 0?{notifyOn:e.notifyOn}:{},...e.notifyChat!==void 0?{notifyChat:e.notifyChat}:{}}}var vh=y(()=>{"use strict";K()});import{existsSync as hce,readFileSync as yce}from"node:fs";import{join as bce}from"node:path";async function Yn(e,t,n){let r;try{let o=bce(_f("default"),"port");if(!hce(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=yce(o,"utf-8").trim();if(r=parseInt(i,10),Number.isNaN(r))return{synced:!1,detail:"daemon-not-detected (invalid port file)"}}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let o=await fetch(`http://localhost:${r}${t}`,{method:e,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return o.ok?{synced:!0,detail:"synced"}:e==="POST"&&o.status===409?{synced:!0,detail:"already-registered"}:e==="DELETE"&&o.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${o.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}var Qo,hR=y(()=>{"use strict";K();Qo="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 wce}from"node:fs";import{readFile as Sce}from"node:fs/promises";var nN,rN,oN,iN,sN=y(()=>{"use strict";vh();K();hR();nN=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;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 i=wh({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}),s=i.enabled?await Yn("POST","/tasks",{taskId:i.id,command:i.command,cron:i.cron,trigger:i.trigger,notifyOn:i.notifyOn,...i.notifyChat!==void 0?{notifyChat:i.notifyChat}:{}}):await Yn("DELETE",`/tasks/${i.id}`);return{content:JSON.stringify({id:i.id,name:i.name,cron:i.cron,enabled:i.enabled,daemonSynced:s.synced,syncDetail:s.detail,...s.synced?{}:{syncNote:Qo}})}},rN=async(e,t)=>{let n=Cn();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})))}},oN=async(e,t)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected object",isError:!0};let n=e;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,i=ur();if(!wce(i))return{content:JSON.stringify([])};let s;try{let c=await Sce(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
|
|
@@ -342,7 +342,7 @@ ${An(e,{headless:t,latched:n})}`,{cause:e})}var kL,ale,lle,vL,dle,ph=y(()=>{"use
|
|
|
342
342
|
`),this.errored=!0)})}catch(n){process.stderr.write(`[afk] session-ledger: write threw for ${this.sessionId}: ${String(n)}
|
|
343
343
|
`),this.errored=!0}}async close(t){if(!this.closed)return this.record({kind:"closed",...t!==void 0?{reason:t}:{}}),this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(n=>{if(!this.stream){n();return}this.stream.end(()=>n())})}};Tde=250});import{readdir as Ede,stat as Rde}from"node:fs/promises";import{join as xde}from"node:path";async function Ku(){let e=Hn(),t;try{t=await Ede(e)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of t){let o=xde(e,r,"trace.jsonl");try{let i=await Rde(o);i.isFile()&&n.push({sessionId:r,tracePath:o,mtimeMs:i.mtimeMs,exists:!0})}catch{}}return n.sort((r,o)=>o.mtimeMs-r.mtimeMs),n}async function Gh(){return(await Ku())[0]?.sessionId??null}var BR=y(()=>{"use strict";K()});import{existsSync as Ade}from"node:fs";import{readFile as Cde}from"node:fs/promises";async function UR(e){if(!Ade(e))return{content:"",truncated:!1};try{let t=await Cde(e);if(t.length<=YN)return{content:t.toString("utf-8"),truncated:!1};let n=t.subarray(t.length-YN),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 YN,XN=y(()=>{"use strict";YN=2097152});import{existsSync as QN}from"node:fs";import{join as ZN}from"node:path";function eB(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.kind=="string"&&typeof t.seq=="number"&&typeof t.payload=="object"&&t.payload!==null}function $de(e){let t=[];for(let n of e.split(`
|
|
344
344
|
`))if(n.trim()!=="")try{let r=JSON.parse(n);eB(r)&&t.push(r)}catch{}return t}function Dde(e){return typeof e!="number"?_de:Math.min(Math.max(1,Math.round(e)),Ide)}function Fde(e){return typeof e!="number"?Mde:Math.min(Math.max(1,Math.round(e)),Ode)}function Lde(e,t){if(t.kinds&&!t.kinds.has(e.kind)||t.toolName&&(e.kind!=="tool_call"||e.payload.name!==t.toolName))return!1;if(t.errorsOnly)if(e.kind==="tool_call"){let n=e.payload;if(n.phase!=="completed"||!n.isError)return!1}else if(e.kind==="subagent_lifecycle"){if(e.payload.transition!=="failed")return!1}else if(e.kind==="background_agent"){if(e.payload.transition!=="failed")return!1}else return!1;return!0}async function qh(e){let t=e.session==="latest"||!e.session?await Gh():e.session;if(!t)return{sessionId:"(none)",events:[],totalInTrace:0,filtered:0};let n=ZN(sn(t),"trace.jsonl");if(!QN(n))try{for await(let l of ei(t))if(l.kind==="meta"){if(l.traceLabel===null)return{sessionId:t,events:[],totalInTrace:0,filtered:0,note:`Session "${t}" ran with tracing disabled (traceLabel: null).`};if(typeof l.traceLabel=="string"&&l.traceLabel.length>0){let c=ZN(sn(l.traceLabel),"trace.jsonl");QN(c)&&(n=c)}break}}catch{}let{content:r}=await UR(n),o=$de(r),i={kinds:e.kinds?new Set(e.kinds):void 0,toolName:e.toolName,errorsOnly:e.errorsOnly},s=Dde(e.limit),a=[];for(let l=o.length-1;l>=0;l--){let c=o[l];if(Lde(c,i)&&(a.push(c),a.length>=s))break}return a.reverse(),{sessionId:t,events:a,totalInTrace:o.length,filtered:a.length}}async function zh(e){let t=Fde(e.sessions),r=(await Ku()).slice(0,t),o=r.length,i=r;if(e.since){let p=Date.parse(e.since);if(Number.isNaN(p))throw new Error(`Invalid "since" date: ${e.since}`);i=r.filter(f=>f.mtimeMs>=p)}let s=e.kinds?new Set(e.kinds):void 0,a=e.query.toLowerCase(),l=[],c=Pde,d=[],u=0;for(let p of i){if(l.length>=c)break;let{content:f,truncated:g}=await UR(p.tracePath);u++,g&&d.push(p.sessionId);for(let h of f.split(`
|
|
345
|
-
`)){if(l.length>=c)break;if(h.trim()!==""&&h.toLowerCase().includes(a))try{let b=JSON.parse(h);if(!eB(b)||s&&!s.has(b.kind))continue;l.push({sessionId:p.sessionId,event:b,matchLine:h.length>500?h.slice(0,500)+"\u2026":h})}catch{}}}return{query:e.query,sessionsAvailable:o,sessionsSearched:u,matches:l,...d.length>0?{truncatedSessions:d}:{}}}var _de,Ide,Pde,Mde,Ode,jR=y(()=>{"use strict";K();Is();BR();XN();_de=50,Ide=200,Pde=200,Mde=20,Ode=100});function tB(e){return!e||typeof e!="object"?null:e}function nB(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}var rB,oB,iB=y(()=>{"use strict";jR();rB=async e=>{let t=tB(e);if(!t)return{content:"Invalid input: expected object",isError:!0};let n=typeof t.session=="string"?t.session:void 0,r=nB(t.kinds),o=typeof t.tool_name=="string"?t.tool_name:void 0,i=typeof t.errors_only=="boolean"?t.errors_only:!1,s=typeof t.limit=="number"?t.limit:void 0;try{let a=await qh({session:n,kinds:r,toolName:o,errorsOnly:i,limit:s});return{content:JSON.stringify(a)}}catch(a){return{content:`read_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},oB=async e=>{let t=tB(e);if(!t)return{content:"Invalid input: expected object",isError:!0};if(typeof t.query!="string"||!t.query)return{content:"Invalid input: query (string) is required",isError:!0};let n=t.query,r=typeof t.sessions=="number"?t.sessions:void 0,o=nB(t.kinds),i=typeof t.since=="string"?t.since:void 0;try{let s=await zh({query:n,sessions:r,kinds:o,since:i});return{content:JSON.stringify(s)}}catch(s){return{content:`search_witness failed: ${s instanceof Error?s.message:String(s)}`,isError:!0}}}});function Nde(e){return e.length<=sB?e:`${e.slice(0,sB)}\u2026(truncated)`}function Bde(e){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${e.title??e.serverName}`,Nde(e.message)];e.url!==void 0&&e.url!==""&&n.push(e.url),xn(n.join(`
|
|
345
|
+
`)){if(l.length>=c)break;if(h.trim()!==""&&h.toLowerCase().includes(a))try{let b=JSON.parse(h);if(!eB(b)||s&&!s.has(b.kind))continue;l.push({sessionId:p.sessionId,event:b,matchLine:h.length>500?h.slice(0,500)+"\u2026":h})}catch{}}}return{query:e.query,sessionsAvailable:o,sessionsSearched:u,sessionsScanned:u,matches:l,...d.length>0?{truncatedSessions:d}:{}}}var _de,Ide,Pde,Mde,Ode,jR=y(()=>{"use strict";K();Is();BR();XN();_de=50,Ide=200,Pde=200,Mde=20,Ode=100});function tB(e){return!e||typeof e!="object"?null:e}function nB(e){if(Array.isArray(e))return e.filter(t=>typeof t=="string")}var rB,oB,iB=y(()=>{"use strict";jR();rB=async e=>{let t=tB(e);if(!t)return{content:"Invalid input: expected object",isError:!0};let n=typeof t.session=="string"?t.session:void 0,r=nB(t.kinds),o=typeof t.tool_name=="string"?t.tool_name:void 0,i=typeof t.errors_only=="boolean"?t.errors_only:!1,s=typeof t.limit=="number"?t.limit:void 0;try{let a=await qh({session:n,kinds:r,toolName:o,errorsOnly:i,limit:s});return{content:JSON.stringify(a)}}catch(a){return{content:`read_witness failed: ${a instanceof Error?a.message:String(a)}`,isError:!0}}},oB=async e=>{let t=tB(e);if(!t)return{content:"Invalid input: expected object",isError:!0};if(typeof t.query!="string"||!t.query)return{content:"Invalid input: query (string) is required",isError:!0};let n=t.query,r=typeof t.sessions=="number"?t.sessions:void 0,o=nB(t.kinds),i=typeof t.since=="string"?t.since:void 0;try{let s=await zh({query:n,sessions:r,kinds:o,since:i});return{content:JSON.stringify(s)}}catch(s){return{content:`search_witness failed: ${s instanceof Error?s.message:String(s)}`,isError:!0}}}});function Nde(e){return e.length<=sB?e:`${e.slice(0,sB)}\u2026(truncated)`}function Bde(e){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${e.title??e.serverName}`,Nde(e.message)];e.url!==void 0&&e.url!==""&&n.push(e.url),xn(n.join(`
|
|
346
346
|
`)).catch(()=>{})}catch{}}function aB(e,t){if(!(e===void 0||e===""))try{lE(e,t).catch(()=>{})}catch{}}var Il,sB,WR,qe,Cr=y(()=>{"use strict";so();hs();Il={action:"decline"},sB=300;WR=class{handler=null;queue=Promise.resolve();queueDepth=0;install(t){this.handler=t}uninstall(){this.handler=null}hasHandler(){return this.handler!==null}pendingCount(){return this.queueDepth}route(t,n){if(n.signal.aborted)return Promise.resolve(Il);this.queueDepth+=1;let r,o=new Promise(s=>{r=s}),i=this.handler;return this.queue=this.queue.then(async()=>{try{if(n.signal.aborted){r(Il);return}if(!i){Bde(t),r(Il);return}let s,a=new Promise(l=>{s=()=>l(Il),n.signal.addEventListener("abort",s,{once:!0})});try{try{n.onActive?.()}catch{}aB(n.sessionId,!0);let l=await Promise.race([i(t,n).catch(()=>Il),a]);r(l)}finally{aB(n.sessionId,!1),n.signal.removeEventListener("abort",s)}}finally{this.queueDepth-=1,r(Il)}}).catch(()=>{}),o}},qe=new WR});var lB,cB=y(()=>{"use strict";Cr();lB=async(e,t,n)=>{if(!e||typeof e!="object")return{content:"Invalid input: expected an object",isError:!0};let r=e,o=r.question;if(typeof o!="string"||o.trim()==="")return{content:"Invalid input: question must be a non-empty string",isError:!0};let i=new Set(["text","confirm","choice","multi_choice","number"]),s=r.type??"text";if(typeof s!="string"||!i.has(s))return{content:"Invalid input: type must be one of: text, confirm, choice, multi_choice, number",isError:!0};if(s==="choice"||s==="multi_choice"){let g=r.choices;if(!Array.isArray(g)||g.length===0)return{content:`Invalid input: choices array is required and must be non-empty for type "${s}"`,isError:!0};if(g.length>100)return{content:`Invalid input: choices array must not exceed 100 items, got ${g.length}`,isError:!0};for(let h of g)if(typeof h!="string")return{content:"Invalid input: all choices must be strings",isError:!0}}let a=r.min,l=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(l!==void 0&&(typeof l!="number"||!Number.isFinite(l)))return{content:"Invalid input: max must be a finite number",isError:!0};if(a!==void 0&&l!==void 0&&a>l)return{content:`Invalid input: min (${a}) must be \u2264 max (${l})`,isError:!0};let c=r.min_length,d=r.max_length;if(c!==void 0&&typeof c!="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((c!==void 0||d!==void 0)&&s!=="text")return{content:`Invalid input: min_length/max_length are only valid for type "text", got "${s}"`,isError:!0};if(r.allow_custom!==void 0&&s!=="choice"&&s!=="multi_choice")return{content:`Invalid input: allow_custom is only valid for type "choice" or "multi_choice", got "${s}"`,isError:!0};let u={serverName:"agent",message:o.trim(),origin:"agent",type:s,...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},...c!==void 0&&{minLength:c},...d!==void 0&&{maxLength:d},...a!==void 0&&{min:a},...l!==void 0&&{max:l},...r.allow_skip!==void 0&&{allowSkip:!!r.allow_skip},...r.allow_custom!==void 0&&{allowCustom:!!r.allow_custom}},p=await qe.route(u,{signal:t,...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 Ude(e){if(!e||typeof e!="object")return{error:"browser_open: input must be an object"};let t=e,n=t.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(t.wait_for!==void 0){if(!dB.includes(t.wait_for))return{error:`browser_open: "wait_for" must be one of ${dB.map(a=>`"${a}"`).join(", ")} (got ${JSON.stringify(t.wait_for)})`};o=t.wait_for}let i;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_open: "screenshot" must be a boolean'};i=t.screenshot}let s;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'browser_open: "timeout_ms" must be a positive finite number'};s=t.timeout_ms}return{url:r.toString(),waitFor:o,screenshot:i,timeoutMs:s}}function jde(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_open aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0,failureClass:Kt(n)}}let o=Ude(t);if("error"in o)return{content:o.error,isError:!0};let i=k.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 s;try{if(e.getBrowserProvider)s=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(xs(),Rs));s=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Yt(c)?{content:An(c),isError:!0}:{content:`browser_open failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await s.open({sessionId:i,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),c=Date.now()-a;if("outcome"in l&&l.outcome==="blocked_by_policy")return gt(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:c}),{content:`browser_open blocked: ${l.reason}`,isError:!0,failureClass:"policy-refusal"};let d=l;return gt(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:d.url,status:"ok",durationMs:c,...d.screenshotPath!==null?{screenshotPath:d.screenshotPath}:{}}),{content:JSON.stringify(d,null,2)}}catch(l){let c=Date.now()-a,d=l instanceof Error?l.message:String(l);gt(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:d,recoverable:!1}});let u=bh(l);return{content:`browser_open failed: ${d}`,isError:!0,...u?{failureClass:u}:{}}}}}var dB,uB,pB=y(()=>{"use strict";j();ds();pe();As();dB=["load","domcontentloaded","networkidle"];uB=jde()});function Wde(e){if(e!=null&&typeof e!="object")return{error:"browser_observe: input must be an object or omitted"};if(!e)return{};let t=e,n;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_observe: "screenshot" must be a boolean'};n=t.screenshot}let r;if(t.include_hidden!==void 0){if(typeof t.include_hidden!="boolean")return{error:'browser_observe: "include_hidden" must be a boolean'};r=t.include_hidden}let o;if(t.max_elements!==void 0){if(typeof t.max_elements!="number"||!Number.isFinite(t.max_elements)||t.max_elements<=0||!Number.isInteger(t.max_elements))return{error:'browser_observe: "max_elements" must be a positive integer'};o=t.max_elements}return{screenshot:n,includeHidden:r,maxElements:o}}function Hde(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_observe aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=Wde(t);if("error"in o)return{content:o.error,isError:!0};let i=k.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 s;try{if(e.getBrowserProvider)s=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(xs(),Rs));s=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Yt(c)?{content:An(c),isError:!0}:{content:`browser_observe failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await s.observe({sessionId:i,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),c=Date.now()-a;return gt(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:l.url,urlAfter:l.url,status:"ok",durationMs:c,...l.screenshotPath!==null?{screenshotPath:l.screenshotPath}:{}}),{content:JSON.stringify(l,null,2)}}catch(l){let c=Date.now()-a,d=l instanceof Error?l.message:String(l);return gt(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:d,recoverable:!1}}),{content:`browser_observe failed: ${d}`,isError:!0}}}}var mB,fB=y(()=>{"use strict";j();pe();As();mB=Hde()});function Kde(e){if(!e||typeof e!="object")return{error:"browser_act: input must be an object"};let t=e;if(typeof t.action!="string")return{error:'browser_act: "action" is required and must be a string'};if(!gB.includes(t.action))return{error:`browser_act: "action" must be one of ${gB.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(t.action)})`};let n=t.action,r=t.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"||!hB.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${hB.map(d=>`"${d}"`).join(", ")} (got ${JSON.stringify(o.kind)})`};let i,s=o.kind;if(s==="semantic"){if(typeof o.text!="string"||o.text.length===0)return{error:'browser_act: target.kind=semantic requires "target.text" (non-empty string)'};i={kind:"semantic",text:o.text,...typeof o.role=="string"&&o.role.length>0?{role:o.role}:{}}}else if(s==="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)'};i={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)'};i={kind:"selector",selector:o.selector}}let a;if(t.value!==void 0){if(typeof t.value!="string")return{error:'browser_act: "value" must be a string when provided'};a=t.value}let l;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:'browser_act: "timeout_ms" must be a positive finite number'};l=t.timeout_ms}let c;if(t.screenshot!==void 0){if(typeof t.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};c=t.screenshot}return{action:n,target:i,value:a,timeoutMs:l,screenshot:c}}function Gde(e,t){let n=e.role?`"${e.text}" (role: ${e.role})`:`"${e.text}"`;return[`browser_act: ambiguous target \u2014 ${t.length} elements matched ${n}.`,'Retry with target.kind="element_id" using one of the following:',...t.map(o=>` id=${o.id} role=${o.role} label=${o.label}`)].join(`
|
|
347
347
|
`)}function qde(e){return e.kind==="semantic"?{kind:"semantic",text:AL(e.text),...e.role!==void 0?{role:e.role}:{}}:e.kind==="element_id"?{kind:"element_id",elementId:e.elementId}:{kind:"selector",selectorHash:xL(e.selector)}}function zde(e={}){return async(t,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_act aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0,failureClass:Kt(n)}}let o=Kde(t);if("error"in o)return{content:o.error,isError:!0};let i=qde(o.target),s=k.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 a;try{if(e.getBrowserProvider)a=await e.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(xs(),Rs));a=await c()}}catch(c){let d=c instanceof Error?c.message:String(c);return Yt(d)?{content:An(d),isError:!0}:{content:`browser_act failed to get provider: ${d}`,isError:!0}}let l=Date.now();try{let c=await a.act({sessionId:s,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),d=Date.now()-l;if("outcome"in c){if(c.outcome==="ambiguous_target")return gt(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:i,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:d}),{content:Gde(c.query,c.candidates),isError:!0};if(c.outcome==="blocked_by_policy")return gt(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:i,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:d}),{content:`browser_act blocked: ${c.reason}`,isError:!0,failureClass:"policy-refusal"}}return gt(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:i,urlBefore:c.url,urlAfter:c.url,status:"ok",durationMs:d,...c.screenshotPath!==null?{screenshotPath:c.screenshotPath}:{}}),{content:JSON.stringify(c,null,2)}}catch(c){let d=Date.now()-l,u=c instanceof Error?c.message:String(c);gt(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:i,urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}});let p=bh(c);return{content:`browser_act failed: ${u}`,isError:!0,...p?{failureClass:p}:{}}}}}var gB,hB,yB,bB=y(()=>{"use strict";gh();j();ds();pe();As();gB=["click","fill","press","select","hover","scroll_to","wait_for"],hB=["semantic","element_id","selector"];yB=zde()});function Jde(e){if(typeof e.kind!="string"||!wB.includes(e.kind))return{error:`browser_screenshot: "target.kind" must be one of ${wB.map(n=>`"${n}"`).join(", ")} (got ${JSON.stringify(e.kind)})`};let t=e.kind;return t==="semantic"?typeof e.text!="string"||e.text.length===0?{error:'browser_screenshot: target.kind=semantic requires "target.text" (non-empty string)'}:{kind:"semantic",text:e.text,...typeof e.role=="string"&&e.role.length>0?{role:e.role}:{}}:t==="element_id"?typeof e.element_id!="string"||e.element_id.length===0?{error:'browser_screenshot: target.kind=element_id requires "target.element_id" (non-empty string)'}:{kind:"element_id",elementId:e.element_id}:typeof e.selector!="string"||e.selector.length===0?{error:'browser_screenshot: target.kind=selector requires "target.selector" (non-empty string)'}:{kind:"selector",selector:e.selector}}function Vde(e){if(e!=null&&typeof e!="object")return{error:"browser_screenshot: input must be an object or omitted"};if(!e)return{};let t=e,n;if(t.target!==void 0){if(!t.target||typeof t.target!="object")return{error:'browser_screenshot: "target" must be an object when provided'};let o=Jde(t.target);if("error"in o)return o;n=o}let r;if(t.full_page!==void 0){if(typeof t.full_page!="boolean")return{error:'browser_screenshot: "full_page" must be a boolean'};r=t.full_page}return{target:n,fullPage:r}}function Yde(e={}){return async(t,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_screenshot aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=Vde(t);if("error"in o)return{content:o.error,isError:!0};let i=k.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 s;try{if(e.getBrowserProvider)s=await e.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(xs(),Rs));s=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Yt(c)?{content:An(c),isError:!0}:{content:`browser_screenshot failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await s.screenshot({sessionId:i,target:o.target,fullPage:o.fullPage}),c=Date.now()-a,{dataBase64:d,mediaType:u,...p}=l;return gt(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:c,screenshotPath:p.path}),p.width>HR||p.height>HR?{content:JSON.stringify({...p,imageOmitted:`dimensions ${p.width}x${p.height}px exceed the ${HR}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(p,null,2),image:{mediaType:u,data:d}}}catch(l){let c=Date.now()-a,d=l instanceof Error?l.message:String(l);return gt(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:d,recoverable:!1}}),{content:`browser_screenshot failed: ${d}`,isError:!0}}}}var wB,HR,SB,vB=y(()=>{"use strict";j();pe();As();wB=["semantic","element_id","selector"],HR=8e3;SB=Yde()});function Xde(e={}){return async(t,n,r)=>{if(n.aborted){let a=n.reason;return{content:`browser_close aborted: ${a instanceof Error?a.message:String(a??"aborted")}`,isError:!0}}let o=k.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 i;try{if(e.getBrowserProvider)i=await e.getBrowserProvider();else{let{getBrowserProvider:a}=await Promise.resolve().then(()=>(xs(),Rs));i=await a()}}catch(a){let l=a instanceof Error?a.message:String(a);return Yt(l)?{content:An(l),isError:!0}:{content:`browser_close failed to get provider: ${l}`,isError:!0}}let s=Date.now();try{await i.close({sessionId:o});let a=Date.now()-s;return gt(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:a}),{content:"Browser session closed."}}catch(a){let l=Date.now()-s,c=a instanceof Error?a.message:String(a);return gt(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:l,error:{reason:c,recoverable:!1}}),{content:`browser_close failed: ${c}`,isError:!0}}}}var kB,TB=y(()=>{"use strict";j();pe();As();kB=Xde()});function Jh(e,t){let n=e!==void 0?Wg(e,t):t!==void 0?Wg("default",t):$D,r=t!==void 0?OE(t):KD,o=t!==void 0?$E(t):YD,i=t!==void 0?IE(t):FD,s=t!==void 0?PE(t):BD,a=t!==void 0?ME(t):jD,l=t!==void 0?DE(t):QD,c=wR(),d=xN(t);return new Map([["bash",n],["read_file",i],["write_file",s],["edit_file",a],["glob",r],["grep",o],["list_directory",l],["send_telegram",iL],["web_scrape",XL],["create_schedule",nN],["list_schedules",rN],["get_schedule_history",oN],["cancel_schedule",iN],["read_witness",rB],["search_witness",oB],["worktree",d],["terminal_font_size",c],["config_get",HN],["config_set",KN],["ask_question",lB],["browser_open",uB],["browser_observe",mB],["browser_act",yB],["browser_screenshot",SB],["browser_close",kB]])}var KR=y(()=>{"use strict";DD();LD();UD();WD();GD();XD();ZD();sL();QL();sN();vR();AN();GN();iB();cB();pB();fB();bB();vB();TB()});function Vh(e){return["The user has switched off plan mode. Writes are now permitted. Do two things, in order:","",`1. Save the plan. Write the plan you developed in this conversation to a new markdown file under \`${e}/\` \u2014 pick a short, descriptive kebab-case filename (e.g. \`${e}/refactor-auth-flow.md\`). Capture the full plan: the chosen approach, the concrete step-by-step changes, the risks named, and the alternatives considered. This is the durable record.`,"","2. Implement the plan. Work through the steps you just recorded, verifying as you go \u2014 run the project's lint/test gates where they apply. End in a terminal state: Done with evidence, Blocked with the exact unblock condition, or Asking one precise question."].join(`
|
|
348
348
|
`)}var GR=y(()=>{"use strict"});function Zde(e){switch(e){case"bypassPermissions":return"Approve \u2014 implement now (restore bypass mode: no prompts, read/write any path)";case"acceptEdits":return"Approve \u2014 implement now (restore accept-edits mode: edits auto-approved)";case"dontAsk":case"auto":return"Approve \u2014 implement now (restore your previous mode: no approval prompts)";default:return"Approve \u2014 implement now (restore default mode: writes ask for confirmation, contained to the workspace)"}}function Xh(e){return async(t,n,r)=>{let o=e.getPrePlanMode()??"default",i=Zde(o),a={serverName:"agent",origin:"agent",type:"choice",message:"Plan ready. How do you want to proceed? (Your plan is in the conversation above.)",choices:o==="bypassPermissions"?[i,qR]:[i,Qde,qR]},l=await qe.route(a,{signal:n,...r?.sessionId!==void 0?{sessionId:r.sessionId}:{}});if(l.action!=="accept")return{content:"Plan exit not confirmed (the user did not approve). Stay in plan mode \u2014 keep refining the plan; do not implement. Call exit_plan_mode again when ready."};let c=typeof l.content?.value=="string"?l.content.value:"";if(c.startsWith("Keep")||c===qR)return{content:"User chose to keep planning. Stay in plan mode and refine the plan; do not implement. Call exit_plan_mode again when ready."};let d=c.includes("bypass")?"bypassPermissions":o,u=Ef(r?.resolveBase??r?.cwd??process.cwd());return e.requestImplementSeed(Vh(u),d),{content:`Plan approved (mode=${d}). The implementation instruction will follow as a new message \u2014 end your turn now.`}}}var pn,Qde,qR,Yh,Ps=y(()=>{"use strict";Cr();GR();K();pn="exit_plan_mode",Qde="Approve \u2014 implement now (bypass mode: no prompts, read/write any path)",qR="Keep planning";Yh={name:pn,category:"other",concurrencySafe:!1,description:`Signal that your plan is ready and present it to the user for approval. The user is shown a picker: approve and implement (you pick neither mode \u2014 the user does), or keep planning.
|
|
@@ -1864,7 +1864,7 @@ ${E}
|
|
|
1864
1864
|
${T}`})}return{fileBlocks:l,warnings:c}}function Y3(e){let t=e.replace(/\s+/g," ").trim();return t.length<=60?t:`${t.slice(0,59)}\u2026`}async function X3(e,t,n){let r=t?.peekQueuedText(),o=r!==void 0?{text:r.text,claimed:!1}:void 0;r!==void 0&&t?.reserveQueued?.(r);let i;try{i=await e.promoteActiveForeground(o)}catch(s){throw r!==void 0&&t?.releaseQueued?.(r),s}if(o?.claimed===!0&&t!==null&&r!==void 0){try{await n?.(o.text)}catch{}return t.dropQueued(r),{jobs:i,flushedText:o.text,flushedPreview:r.preview}}return r!==void 0&&t?.releaseQueued?.(r),{jobs:i}}yS();async function Q3(e,t,n,r,o="summary",i,s){let a=vV(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0),Mc(process.stdout,em(process.cwd(),!0));let l="",c=0,d=!1,u=!1,p=!1,f=!1,g=!1,h,b=!1,w=!1,S={abort:null},v=0,E=3e3,T=[],A=new Map,M=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,_=()=>{let F=r.subagentControl;F?.hasPromotableForeground()&&X3(F,x,r.onQueuedUserMessage).then(({jobs:W,flushedText:G,flushedPreview:I})=>{let L=(i??{fn:console.log}).fn;for(let O of W)L(m.dim(` \u2192 subagent backgrounded as ${O.jobId}: ${O.label}`));G!==void 0&&L(m.dim(` \u2192 queued message sent to this turn: ${Y3(I??G)}`))}).catch(()=>{})},x=r.getCompositor?r.getCompositor():null,C=()=>new nd({out:rd(i),thinkingMode:o,...M?{activeSkillName:M}:{},onCancel:()=>{t.interrupt().catch(F=>{He()&&console.error(" "+m.error("session.interrupt() failed:"),F)})},...r.subagentControl?{onBackground:_}:{},...s?.history?{history:s.history}:{},...s?.autocompleteState?{autocompleteState:s.autocompleteState}:{},...s?.promptText!==void 0?{promptText:s.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...x?{compositor:x}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),P=C(),$=async()=>{if(!f){f=!0;try{await P.dispose()}catch{}}},q=async()=>{await P.arm();let F=P.getCompositor();if(i&&F){let W=F;i.fn=G=>W.commitAbove(G),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(F),r.setInterruptNotifier?.(W=>P.setInterrupting(W)),r.rearmStatus?.()};try{x?x.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{b=!0,P.setSoftStopping(!0),t.interrupt().catch(D=>{He()&&console.error(" "+m.error("soft-stop session.interrupt() failed:"),D)});let O=r.subagentControl;O?.hasActiveForeground()&&O.cancelActiveForeground().catch(D=>{He()&&console.error(" "+m.error("soft-stop cancelActiveForeground() failed:"),D)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{w=!0,t.interrupt().catch(O=>{He()&&console.error(" "+m.error("pause-interrupt session.interrupt() failed:"),O)})}),await q(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(_);let{fileBlocks:F,warnings:W}=V3(e.text,{rootDir:process.cwd()});for(let O of W)(i??{fn:console.log}).fn(m.dim(` @-file: ${O}`));if(e.attachments.length>0&&(await t.waitForInitialization(),t.sessionId===void 0))throw new Error("CLI session initialized without a session id");let G=F.length>0||e.attachments.length>0?await J3(e.text,e.attachments,void 0,F,t.sessionId):e.text,I=t.sendMessageStream(G);if(await Ml((O,D)=>{P.process(O,D)},async()=>{for await(let O of I){if(b||w)break;if(O.type==="chunk"&&O.chunk.type==="content"?(l=d?q3(l,O.chunk.content):l+O.chunk.content,d=!1,u=!0):O.type==="message"&&!u&&(l=O.message.content),O.type==="stream_retry"&&(l=l.slice(0,c),d=l.length>0),O.type==="chunk"&&O.chunk.type==="tool_use_detail"){let D=O.chunk,H={toolName:D.toolName,toolUseId:D.toolUseId,input:D.toolInput,...D.toolInputRaw!==void 0&&{inputRaw:D.toolInputRaw}};A.set(D.toolUseId,H),T.push(H)}else if(O.type==="chunk"&&O.chunk.type==="tool_result"){let D=O.chunk;c=l.length,d=!0;let H=A.get(D.toolUseId);if(H&&(H.result=D.content,H.isError=D.isError,A.delete(D.toolUseId)),r.onContextProgress){let ne=Date.now();if(ne-v>=E){v=ne;try{let ee=r.onContextProgress();ee instanceof Promise&&await ee}catch(ee){He()&&console.error(" "+m.error("onContextProgress (status refresh) failed:"),ee)}}}}if(O.type==="paused"){if(r.setPausedState?.(!0),await $(),x&&O.autoResume===!0){let D=new AbortController;S.abort=D;let H=O.resetsAt?O.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,ne=H?`Keep waiting \u2014 auto-resumes at ${H}`:"Keep waiting \u2014 auto-resume in progress",ee="Switch model / provider (type /model after)",X="Stop waiting",le=[m.warning(" \u23F3 Usage limit reached.")+(H?m.dim(` Auto-resumes at ${H}.`):""),m.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];Bn(x,{header:le,options:[ne,ee,X],signal:D.signal,initialIndex:0}).then(z=>{if(S.abort=null,!z)return;let ke=z[0];ke===void 0||ke===ne||(w=!0,ke===ee&&(i??{fn:console.log}).fn(m.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(ce=>{He()&&console.error(" "+m.error("picker pause-interrupt session.interrupt() failed:"),ce)}))}).catch(z=>{He()&&console.error(" "+m.error("picker promise rejected:"),z)})}else(i??{fn:console.log}).fn(EO({reason:O.reason,...O.resetsAt!==void 0?{resetsAt:O.resetsAt}:{},...O.accountId!==void 0?{accountId:O.accountId}:{},...O.autoResume!==void 0?{autoResume:O.autoResume}:{}}));continue}if(O.type==="resumed"){r.setPausedState?.(!1),S.abort?.abort(),S.abort=null;let D=O.hotSwapped&&O.accountId?`\u25B6 Resumed on ${O.accountId}`:"\u25B6 Resumed";l="",c=0,d=!1,u=!1,T.length=0,A.clear(),g=!1,h=void 0,p=!1,P=C(),f=!1,await q(),(i??{fn:console.log}).fn(m.success(D));continue}if(O.type==="error"){await $(),Va(Wa(O.error)),p=!0;continue}P.process(O),O.type==="done"&&(g=!0,h=O.metadata)}}),await $(),b){let O=i?i.fn:console.log,D=x?x.getPendingCount():0,H=D>0?` \xB7 ${D} queued`:"";O(m.warning(`\u23F8 Stopped${H} \u2014 work so far kept.`)+m.dim(" Send a message to continue.")),O("")}if(w){let O=i?i.fn:console.log;O(m.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),O("")}if(g&&!b&&!w){Xs(n,a,l,h,T),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),Pc(process.stdout),$z(process.stdout,"afk: turn complete");let O=H=>{i?i.fn(H):console.log(H)},D=Zv(l);if(D){O(z3(D)),O("");let H=R5(T);if(r.onTerminalState)try{r.onTerminalState(D,{doneHasCorroboratingEvidence:H})}catch{}if(n.permissionMode==="autonomous"){let ne=D.kind==="done"&&Ou().verifyDone===!0&&!H;A5(D,void 0,{unverified:ne})}}if(sIe(h,n,O),r.onAfterTurn){let H=r.onAfterTurn();H instanceof Promise&&await H.catch(()=>{})}}}catch(F){await $(),p||Va(Wa(F))}finally{await $(),Mc(process.stdout,em(process.cwd(),!1)),i&&(i.fn=i.idleFn,i.suppressSubagentCompletion=!1),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),S.abort?.abort(),S.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function iIe(e,t){let n=Math.round(e*100),r=he(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${he(o)} tok \u2014 model output may be silently truncated`}}return e>=.95?{tier:"near",text:` context ${n}% used of ${r} \u2014 near limit; output may soon truncate (consider /clear or a fresh session)`}:e>=.8?{tier:"caution",text:` context ${n}% used of ${r} \u2014 approaching limit`}:e>.5?{tier:"normal",text:` context ${n}% used of ${r}`}:{tier:"quiet",text:null}}function sIe(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(_e(e.durationMs)),e.totalCostUsd!==void 0&&r.push(St(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(he(o+i)+" tok"),r.length>0&&n(m.dim(" \u25E6 "+r.join(" \xB7 ")));let s=AI(t),a=nt(t.model),l=iIe(s,a);if(l.text!==null){let d=l.tier==="over"||l.tier==="near"?m.error:l.tier==="caution"?m.warning:m.dim;n(d(l.text))}let c=G3(qS(ay()),new Date,{autoResume:ZF()});if(c.text!==null){let d=c.tier==="over"||c.tier==="near"?m.error:c.tier==="caution"?m.warning:m.dim;n(d(c.text))}n("")}Ri();var aIe=5e3,lIe=3,cIe="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function dIe(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function Z3(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,mascotBar:d,verdictLedger:u,shellPassthrough:p,bgResultNotifier:f}=s,g=null,h=[];e.session.current.waitForInitialization().then(async _=>{He()&&(g=uv(_)),await Cm(e.session.current),He()&&(h=kI())}).catch(()=>{});let b=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,w,S=!1,v=!1,E,T,A,M=0;for(f.onInjectable=()=>{M>=lIe||!o.isAwaitingInput()||!o.bufferIsEmpty()||(M++,Pc(process.stdout),b={text:cIe,attachments:[]},o.abortPendingRead())};;){if(g&&(e.replRenderer.writeLine(g),e.replRenderer.writeLine(""),g=null),h.length>0){for(let I of h)e.replRenderer.writeLine(I);e.replRenderer.writeLine(""),h=[]}let _=p.drainNotifications();for(let{job:I,result:L}of _){let O=L.errorReason===void 0?"\u2713":"\u2717",D=L.errorReason==="abort"?"killed":L.errorReason==="timeout"?"timed out":L.errorReason==="signal-killed"?"killed by signal":`exit ${L.exitCode??0}`,H=Math.max(0,Math.round(L.durationMs/100)/10);e.replRenderer.writeLine(m.dim(` ${O} [${I.id}] ${D} \xB7 ${H}s \xB7 `)+I.command)}let x=f.drainNotifications();for(let{job:I}of x){let L=I.status==="completed"?"\u2713":I.status==="failed"?"\u2717":"\u2298",O=I.endedAt!==void 0?Math.max(0,Math.round((I.endedAt-I.startedAt)/100)/10):0,D=se(I.label,60);e.replRenderer.writeLine(m.dim(` ${L} [${I.jobId}] subagent ${I.status} \xB7 ${O}s \xB7 `)+D)}let C=l.renderIfChanged(e.stats.sessionId);if(C.length>0){for(let I of C)e.replRenderer.writeLine(I);e.replRenderer.writeLine("")}let P,$;if(b===void 0){let I=await e.session.current.takePendingPlanExitSeed();I!==void 0&&(e.stats.permissionMode=I.mode,b={text:I.message,attachments:[]})}if(b!==void 0){let I=b;b=void 0;let L=ud(e.stats.permissionMode),O=na({buffer:I.text,promptText:L,isTTY:!!process.stdout.isTTY,attachmentSummary:Kc([...I.attachments])});e.replRenderer.writeLine(O),P=I.text.trim(),$=I.attachments}else{let I=w;w=void 0;let L=await o.readLine({promptFn:()=>ud(e.stats.permissionMode),...I!==void 0?{initialBuffer:I}:{},primePromptSuggestion:!0,onSigint:r,onShiftTab:()=>{Jv(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});P=L.text.trim(),$=L.attachments}if(!P&&$.length===0)continue;if(P.startsWith("!")){let I=/^(0|false|off|no)$/i.test(k.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!I&&(S||(S=!0,e.replRenderer.writeLine(m.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await p.dispatch(P))){e.statusLine.rearm();continue}}let q=!1;if(P.startsWith("/")){let I=await Lz(P,e.slashCtx,$);if(I.handled){if(I.result==="exit"){await e.resolveWorktreeDisposition?.(!0),e.rl.close();return}if((P==="/clear"||P.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),u.reset(),E=void 0),I.result!==null&&typeof I.result=="object"&&"kind"in I.result&&I.result.kind==="submit"){b={text:I.result.message,attachments:$??[]},e.statusLine.rearm();continue}if(I.result!==null&&typeof I.result=="object"&&"kind"in I.result&&I.result.kind==="prefill"){w=I.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}q=!0}a.push(P),await dIe(e,P);let F=P;if(q){let I=o_(P);if(I){let L=I.name.replace(/^\//,"").split(":").pop()??"";if(L&&yI(L)){let O={skillName:L,rawArgs:I.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},D=e.session.current.sessionId,H=ma(D),ne=Date.now();B(`[afk trace] preflight.start commandName=${L}`);let ee=!1,X=await pa(O,{cwd:e.stats.cwd??process.cwd(),artifactDir:H},le=>{He()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${L}) failed: `)+(le instanceof Error?le.message:String(le)))});ee=X!==null,B(`[afk trace] preflight.end commandName=${L} durationMs=${Date.now()-ne} success=${ee}`),F=SI(X?.manifestBlock,P)}}}let W=p.drainInjections();W.length>0&&(F=W+F);let G=f.drainInjections();if(G.length>0&&(F=G+F),E!==void 0&&(F=E+`
|
|
1865
1865
|
|
|
1866
1866
|
`+F,E=void 0),e.hookRegistry)try{let I={event:"UserPromptSubmit",prompt:F,sessionId:e.stats.sessionId},L=await e.hookRegistry.dispatch(I);L.injectContext&&(F=L.injectContext+F)}catch(I){if(I instanceof Ae){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+(I.reason?m.dim(`: ${Ye(I.reason)}`):"")),e.statusLine.rearm();continue}if(I instanceof wr){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+m.dim(`: handler timed out after ${I.timeoutMs}ms`)),e.statusLine.rearm();continue}throw I}if(T=void 0,A=void 0,await Q3({text:F,attachments:$},e.session.current,e.stats,{setInFlight(I){n.turnInFlight=I},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(I){await t.appendUser(I)},async onQueuedUserMessage(I){await t.appendQueuedUser(I)},async onTurnComplete(I,L){if(await t.appendTurn(I,L),e.stats.sessionId)try{Ei(e.stats)}catch(O){v||(v=!0,e.replRenderer.writeLine(m.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(O instanceof Error?O.message:String(O))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(I,L)=>{u?.push(I),T=I.kind,A=L?.doneHasCorroboratingEvidence},setActiveCompositor:I=>{n.activeCompositor=I},setInterruptNotifier:I=>{n.notifyInterrupting=I},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:I=>o.setBackgroundHandler(I),setSoftStopHandler:i,setPausedState:I=>o.setPausedState(I),setPauseInterruptHandler:I=>o.setPauseInterruptHandler(I),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(ar(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:(I,L)=>{c.repaint(I),d?.onStage(I,L)}}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(ud(e.stats.permissionMode))),e.hookRegistry)try{let I=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...T!==void 0?{terminalState:T}:{},...A!==void 0?{doneHasCorroboratingEvidence:A}:{}},void 0,aIe);I.injectContext&&I.injectContext.trim().length>0&&(E=I.injectContext)}catch(I){if(I instanceof kt)throw I;I instanceof wr?(B("[stop hook] handler timed out"),e.completionWriter.fn(m.dim(" [stop hook] timed out"))):I instanceof Ae?e.completionWriter.fn(m.dim(` [stop hook] blocked: ${Ye(I.reason??"no reason given")}`)):B("[stop hook] unexpected error: "+String(I))}}}function uIe(e,t){if(e!==void 0){let n=e.toLowerCase();return!(n==="0"||n==="false"||n==="off"||n==="no")}return typeof t=="boolean"?t:!0}async function eX(e,t,n,r){let o=await w3(),i=new zv({rl:e.rl,history:o,statusLine:e.statusLine}),s=uIe(k.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await x3(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar,getMascotBar:()=>a?.mascotBar});a=H3(e,n),await Z3(e,t,n,r,i,l,a,o),await e.resolveWorktreeDisposition?.(!0)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.bgResultNotifier.dispose(),a?.loopStageBar.stop(),a?.mascotBar.stop(),a?.bgStatusBar.stop(),a?.verdictLedger.stop(),a?.contextPane.dispose();let l=c=>console.log(c);e.completionWriter.fn=l,e.completionWriter.idleFn=l,await i.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}Ru();Tl();import{execFile as pIe}from"node:child_process";import{dirname as mIe,isAbsolute as fIe,resolve as gIe}from"node:path";import{promisify as hIe}from"node:util";var tX=hIe(pIe),yIe=3e3,bIe=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function wIe(){let t=(await tX("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=fIe(t)?t:gIe(process.cwd(),t);return mIe(n)}async function nX(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await wIe()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),yIe)});try{let o=In({execFile:tX,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),i=await Promise.race([o,r]);if(i==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let s=i;return s.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:s.candidates.filter(c=>bIe.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}ng();Ru();import{promises as SIe}from"node:fs";import{dirname as vIe,join as iX}from"node:path";import{randomBytes as kIe}from"node:crypto";var TIe=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
|
|
1867
|
-
`),rX=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,ZP=30,EIe=1024,RIe=8e3,xIe="haiku";async function AIe(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=PIe(n,EIe),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??RIe),s=t.signal?MIe([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await tl({token:t.token,model:t.model??xIe,system:TIe,user:r,maxTokens:32,signal:s})}catch(u){let p=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=CIe(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=vIe(t.worktreePath);return await _Ie(l,c)}function CIe(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(rX.test(t)&&t.length<=ZP)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>ZP)break;o=s}return rX.test(o)?o:null}async function _Ie(e,t){if(!await IIe(iX(t,e)))return e;let n=kIe(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,ZP-5)}-${n}`}async function IIe(e){try{return await SIe.access(e),!0}catch{return!1}}function PIe(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function MIe(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function sX(e){let t,n,r=iX(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await AIe(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${th(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return oX(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return oX(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function oX(e,t){e&&e.setCwd(t),OIe(t)}function OIe(e){try{process.chdir(e)}catch{}}lt();At();Ua();Wr();K();import{spawn as lX}from"child_process";import{existsSync as cX,mkdirSync as NIe,readFileSync as dX,unlinkSync as aX,writeFileSync as uX}from"fs";import{get as BIe}from"https";import{join as pX}from"path";import{readFileSync as $Ie}from"fs";import{dirname as DIe,join as FIe}from"path";import{fileURLToPath as LIe}from"url";function Gr(){try{return"5.114.
|
|
1867
|
+
`),rX=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,ZP=30,EIe=1024,RIe=8e3,xIe="haiku";async function AIe(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=PIe(n,EIe),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??RIe),s=t.signal?MIe([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await tl({token:t.token,model:t.model??xIe,system:TIe,user:r,maxTokens:32,signal:s})}catch(u){let p=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=CIe(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=vIe(t.worktreePath);return await _Ie(l,c)}function CIe(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(rX.test(t)&&t.length<=ZP)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(i=>i.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let i=1;i<r.length;i++){let s=`${o}-${r[i]}`;if(s.length>ZP)break;o=s}return rX.test(o)?o:null}async function _Ie(e,t){if(!await IIe(iX(t,e)))return e;let n=kIe(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,ZP-5)}-${n}`}async function IIe(e){try{return await SIe.access(e),!0}catch{return!1}}function PIe(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function MIe(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function sX(e){let t,n,r=iX(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await AIe(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),i=t??"unknown",s=n;if(o!==null){let l=`${th(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return oX(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){i="create-failed",s=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return oX(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:i,...s!==void 0?{detail:s}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function oX(e,t){e&&e.setCwd(t),OIe(t)}function OIe(e){try{process.chdir(e)}catch{}}lt();At();Ua();Wr();K();import{spawn as lX}from"child_process";import{existsSync as cX,mkdirSync as NIe,readFileSync as dX,unlinkSync as aX,writeFileSync as uX}from"fs";import{get as BIe}from"https";import{join as pX}from"path";import{readFileSync as $Ie}from"fs";import{dirname as DIe,join as FIe}from"path";import{fileURLToPath as LIe}from"url";function Gr(){try{return"5.114.1"}catch{}try{let e=DIe(LIe(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse($Ie(FIe(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}U();j();var UIe=64*1024,jIe=10800*1e3,WIe=800,HIe=3600*1e3,KIe="update-check.json",GIe="pending-update.json";function eM(){return pX(La(),KIe)}function Gm(){return pX(La(),GIe)}function tM(){let e=La();cX(e)||NIe(e,{recursive:!0})}function mX(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),i=n(t).split(".").map(Number),s=Math.max(o.length,i.length);for(let a=0;a<s;a++){let l=o[a]??0,c=i[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function fX(){try{let e=dX(eM(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function gX(){try{tM();let e=`
|
|
1868
1868
|
const https = require('https');
|
|
1869
1869
|
const fs = require('fs');
|
|
1870
1870
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|
|
@@ -2064,7 +2064,7 @@ or "latest" (the default) \u2014 the most recently written trace.`).option("--al
|
|
|
2064
2064
|
`);return}for(let i of o.slice(0,r)){let s=new Date(i.mtimeMs).toISOString().replace("T"," ").slice(0,19);process.stdout.write(`${s} ${i.sessionId}
|
|
2065
2065
|
`)}}catch(r){J(r)}})}jR();function OQ(e){let t=e.command("witness").description(`Search and filter the witness-layer trace history \u2014 the durable record
|
|
2066
2066
|
of everything agents did across sessions.`);t.command("read [session]").description("Read and filter events from a session trace (default: latest)").option("-k, --kinds <kinds>","Comma-separated event kinds to filter by").option("-t, --tool <name>","Filter tool_call events to this tool name").option("-e, --errors","Show only error events",!1).option("-n, --limit <number>","Max events to return (default: 50, max: 200)").option("--json","Emit raw JSON (for piping to jq)",!1).action(async(n,r)=>{try{let o=typeof r.kinds=="string"?r.kinds.split(",").map(a=>a.trim()):void 0,i=typeof r.limit=="string"?parseInt(r.limit,10):void 0,s=await qh({session:n??"latest",kinds:o,toolName:typeof r.tool=="string"?r.tool:void 0,errorsOnly:r.errors===!0,limit:i});if(r.json){console.log(JSON.stringify(s,null,2));return}console.log(`Session: ${s.sessionId} (${s.totalInTrace} events, ${s.filtered} matched)
|
|
2067
|
-
`);for(let a of s.events){let l=a.payload,c=l.name??l.transition??l.phase??"",d=l.isError?" \u2717":"",u=typeof l.durationMs=="number"?` (${l.durationMs}ms)`:"";console.log(` ${a.ts} [${a.kind}] ${c}${d}${u}`)}}catch(o){J(o)}}),t.command("search <query>").description("Text-search across recent sessions' traces").option("-n, --sessions <number>","Number of recent sessions to scan (default: 20)").option("-k, --kinds <kinds>","Comma-separated event kinds to filter by").option("--since <date>","Only search sessions modified after this ISO date").option("--json","Emit raw JSON (for piping to jq)",!1).action(async(n,r)=>{try{let o=typeof r.kinds=="string"?r.kinds.split(",").map(l=>l.trim()):void 0,i=typeof r.sessions=="string"?parseInt(r.sessions,10):void 0,s=await zh({query:n,sessions:i,kinds:o,since:typeof r.since=="string"?r.since:void 0});if(r.json){console.log(JSON.stringify(s,null,2));return}console.log(`Search: "${s.query}" (${s.sessionsSearched} sessions
|
|
2067
|
+
`);for(let a of s.events){let l=a.payload,c=l.name??l.transition??l.phase??"",d=l.isError?" \u2717":"",u=typeof l.durationMs=="number"?` (${l.durationMs}ms)`:"";console.log(` ${a.ts} [${a.kind}] ${c}${d}${u}`)}}catch(o){J(o)}}),t.command("search <query>").description("Text-search across recent sessions' traces").option("-n, --sessions <number>","Number of recent sessions to scan (default: 20)").option("-k, --kinds <kinds>","Comma-separated event kinds to filter by").option("--since <date>","Only search sessions modified after this ISO date").option("--json","Emit raw JSON (for piping to jq)",!1).action(async(n,r)=>{try{let o=typeof r.kinds=="string"?r.kinds.split(",").map(l=>l.trim()):void 0,i=typeof r.sessions=="string"?parseInt(r.sessions,10):void 0,s=await zh({query:n,sessions:i,kinds:o,since:typeof r.since=="string"?r.since:void 0});if(r.json){console.log(JSON.stringify(s,null,2));return}console.log(`Search: "${s.query}" (${s.sessionsSearched} of ${s.sessionsAvailable} sessions searched, ${s.matches.length} matches)
|
|
2068
2068
|
`);let a="";for(let l of s.matches){l.sessionId!==a&&(a=l.sessionId,console.log(`
|
|
2069
2069
|
\u2500\u2500 ${a} \u2500\u2500`));let c=l.event.payload,d=c.name??c.transition??c.phase??"";console.log(` ${l.event.ts} [${l.event.kind}] ${d}`)}}catch(o){J(o)}})}U();import{execFileSync as $Oe}from"child_process";import{existsSync as DOe}from"fs";K();import{homedir as $Q}from"os";import{join as $M}from"path";function rn(e){return`com.afk.${e}`}function DM(e=$Q()){return $M(e,"Library","LaunchAgents")}function zr(e,t=$Q()){return $M(DM(t),`${rn(e)}.plist`)}function wd(e){return $M(Lo(),`service-${e}.log`)}function Aa(){return`gui/${process.getuid?.()??501}`}var $o=8e3;import{execFileSync as Tk}from"child_process";import{existsSync as FM,mkdirSync as BQ,readFileSync as EOe,renameSync as ROe,rmSync as xOe,unlinkSync as AOe,writeFileSync as COe}from"fs";import{homedir as _Oe}from"os";import{dirname as IOe}from"path";import{execFileSync as hOe}from"child_process";import{existsSync as DQ,realpathSync as FQ}from"fs";import{homedir as yOe}from"os";import{delimiter as bOe,dirname as wOe,resolve as SOe}from"path";function Ki(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}function LQ(e){let t=[];t.push('<?xml version="1.0" encoding="UTF-8"?>'),t.push('<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">'),t.push('<plist version="1.0">'),t.push("<dict>"),t.push(" <key>Label</key>"),t.push(` <string>${Ki(e.label)}</string>`),t.push(" <key>ProgramArguments</key>"),t.push(" <array>");for(let n of e.programArguments)t.push(` <string>${Ki(n)}</string>`);if(t.push(" </array>"),t.push(" <key>WorkingDirectory</key>"),t.push(` <string>${Ki(e.workingDirectory)}</string>`),t.push(" <key>StandardOutPath</key>"),t.push(` <string>${Ki(e.standardOutPath)}</string>`),t.push(" <key>StandardErrorPath</key>"),t.push(` <string>${Ki(e.standardErrorPath)}</string>`),t.push(" <key>RunAtLoad</key>"),t.push(" <true/>"),t.push(" <key>KeepAlive</key>"),t.push(" <true/>"),t.push(" <key>ProcessType</key>"),t.push(" <string>Interactive</string>"),e.watchPaths&&e.watchPaths.length>0){t.push(" <key>WatchPaths</key>"),t.push(" <array>");for(let n of e.watchPaths)t.push(` <string>${Ki(n)}</string>`);t.push(" </array>")}if(e.environmentVariables&&Object.keys(e.environmentVariables).length>0){t.push(" <key>EnvironmentVariables</key>"),t.push(" <dict>");let n=Object.keys(e.environmentVariables).sort();for(let r of n){let o=e.environmentVariables[r]??"";t.push(` <key>${Ki(r)}</key>`),t.push(` <string>${Ki(o)}</string>`)}t.push(" </dict>")}return t.push("</dict>"),t.push("</plist>"),t.join(`
|
|
2070
2070
|
`)+`
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var v_=Object.defineProperty;var Ae=(t,e)=>()=>(t&&(e=t(t=0)),e);var Fu=(t,e)=>{for(var n in e)v_(t,n,{get:e[n],enumerable:!0})};function $o(t){return Uo.find(e=>e.name===t)}function al(t){return process.env[t]!==void 0}var Uo,y,O=Ae(()=>{"use strict";Uo=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_COMPACT_SHRINK_FRACTION",description:"Context-fullness fraction (0\u20131, exclusive) at/above which /compact and auto-compaction relax the keep-window so a short-but-full session (few turns, huge tool exchanges) can still be summarized instead of no-oping on turn count. Default 0.7 (see shared/compaction.ts DEFAULT_COMPACT_SHRINK_THRESHOLD).",type:"number",required:!1,example:"0.8",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS",description:"Maximum concurrency-safe tool calls run simultaneously within one dispatcher batch. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"4",category:"model"},{name:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",description:"Maximum subagent calls run simultaneously from one compose/DAG layer or skill wave. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"2",category:"model"},{name:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",description:"Maximum background subagent jobs running simultaneously in one registry. Default 10; accepted range 1-64; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"10",example:"5",category:"model"},{name:"AFK_MAX_NESTING_DEPTH",description:"Maximum sub-agent/skill nesting depth; 0 disables nested delegation entirely (the agent, skill, AND compose tools all refuse). A top-level session is depth 0, so the default 3 permits three generations of forked descendants (depth 1 \u2192 2 \u2192 3) and refuses the agent and skill tools at depth 3. Resolved once at the root of each session and propagated down through child AgentConfig, so descendants inherit the root value rather than re-reading the environment. Raise with care: depth is a fan-out exponent (a width-N wave at depth D reaches ~N^D concurrent children), so values above 4 invite provider rate-limit (429) cascades. Accepted range 0-6; unset, empty, unparseable, negative, or out-of-range input falls back to the default. An explicit programmatic maxDepth (SubagentExecutorContext / SkillExecutorContext) still wins.",type:"number",required:!1,default:"3",example:"2",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. When unset, falls back to the model output ceiling (AFK's own per-model limit, 64k\u2013128k \u2014 NOT a small provider default), so every request advertises the full ceiling by default. An over-ceiling value is clamped down with a warning.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS (or --max-output-tokens) to cap per-response output tokens; falls back to the model output ceiling when unset.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MAX_TOOL_USE_ITERATIONS",description:"Opt-in ceiling on tool-use rounds per turn for TOP-LEVEL (non-subagent) sessions, on both providers. Mirrors the maxToolUseIterations config key / max_tool_use_iterations tool param. Unset, non-numeric, or <=0 means unlimited (the default \u2014 zero behavior change): a top-level turn ends only when the model stops calling tools, the abort signal fires, the provider errors, or the dollar budget trips. A positive integer N makes top-level turns wind down gracefully after N tool rounds (one tools-stripped final round). An explicit config/CLI value wins over this env default. Does NOT affect subagent forks \u2014 they keep their own non-zero anti-hang default (SUBAGENT_DEFAULT_MAX_TOOL_USE_ITERATIONS) regardless of this var.",type:"number",required:!1,default:"0",example:"150",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Opt-in (set to 1) evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an `evidence` citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. Default off \u2014 memory behaves identically to legacy when unset.',type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_MICROCOMPACT_KEEP_LAST",description:"Number of the most-recent tool_result blocks that tool-result microcompaction keeps intact regardless of size, so the agent does not lose the tool output it is actively reasoning over. Older results are the safe ones to trim. Default 4 (see shared/compaction.ts DEFAULT_MICROCOMPACT_KEEP_LAST). Values <= 0 protect nothing.",type:"number",required:!1,default:"4",example:"3",category:"model"},{name:"AFK_MICROCOMPACT_TOOL_RESULT_BYTES",description:"Byte threshold (tool_result content length) at/above which a tool_result block becomes a microcompaction candidate. When /compact and auto-compaction would otherwise no-op on a short-but-full session, microcompaction clears large/old tool_result CONTENT in place (largest first) \u2014 replacing it with a short placeholder, never removing the block \u2014 to reclaim context deterministically (no LLM call). Blocks below this size are left intact. Default 2048 (see shared/compaction.ts DEFAULT_MICROCOMPACT_TOOL_RESULT_BYTES).",type:"number",required:!1,default:"2048",example:"4096",category:"model"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), fixed-identity aliases (opus, sonnet, haiku, fable), or full model IDs. Migration: AFK_MODEL=sonnet now pins the fixed Sonnet identity rather than following a rebound medium tier.",type:"string",required:!1,default:"medium",example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_TTFB_TIMEOUT_MS",description:"Per-ROUND time-to-first-token budget (ms) for the anthropic-direct streaming loop. Bounds how long a round may stall BEFORE its first streamed CONTENT token (a text/thinking delta or tool_use); the connection-level message_start and keep-alive pings do NOT count. Once a content token streams, the timer is cleared and the rest of the response is governed instead by the progress-aware AFK_MODEL_STALL_TIMEOUT_MS window, so a normal slow call (below the bound) and any actively-streaming extended-thinking response are never aborted. The budget is divided into 3 shorter first-byte ATTEMPTS (each ~2/3 of this value, so the worst-case wall time per round is unchanged from the previous 2-attempt regime while a transient stall gets 3 chances instead of 2). NOTE: a request whose FIRST token takes longer than the per-attempt bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted and re-driven, then surfaces as an error once the budget is spent (raise this value or set 0 for such workloads); this trims the degrading-call tail instead of a silent ~10-min hang on the SDK default. Default 180000 (180s \u2248 2\xD7 the measured p99 ttfb), i.e. 3 \xD7 120s. Set to 0 to disable.",type:"number",required:!1,default:"180000",example:"120000",category:"model"},{name:"AFK_MODEL_STALL_TIMEOUT_MS",description:"Progress-aware POST-first-byte stall window (ms) for the anthropic-direct streaming loop. Bounds how long a stream that has ALREADY produced content may then go completely silent. Every streamed output event resets the window, so this is NOT a total-round cap: a legitimately long, actively-streaming round (large code emission, extended thinking) survives indefinitely, while a stream wedged mid-flight is aborted and surfaces as a real terminal error instead of hanging. Complements AFK_MODEL_TTFB_TIMEOUT_MS, which governs only the window BEFORE the first token; this one takes over after it. Default 1200000 (20min) \u2014 above the 18.5min maximum post-first-byte stream duration observed across 86,076 rounds in 12,381 local traces (p99 122s, p99.9 234s), so no healthy round trips it. Set to 0 to disable (issue #762).",type:"number",required:!1,default:"1200000",example:"600000",category:"model"},{name:"AFK_SUBAGENT_TIMEOUT_MS",description:"Foreground forked-subagent wall-clock budget in ms; 0 disables the cap; explicit per-fork config.timeoutMs and the 60-min background mode still win. Bounds how long a single forked child turn may run before `withTimeout` aborts its controller (cascading through the AbortGraph to descendants) and the parent receives a legible TimeoutError tool_result instead of hanging. Default 2700000 (45 min \u2248 headroom over the longest healthy review/research agent observed in production). Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to opt a whole session back into unbounded child turns. Does NOT affect the background dispatch budget (SUBAGENT_BACKGROUND_TIMEOUT_MS) or a per-fork config.timeoutMs \u2014 both take precedence.",type:"number",required:!1,default:"2700000",example:"3600000",category:"model"},{name:"AFK_SUBAGENT_IDLE_TIMEOUT_MS",description:"Forked-subagent progress-aware idle-watchdog window in ms; 0 disables the watchdog; an explicit per-fork config.idleTimeoutMs still wins. Fires when a forked child produces no observable output event for this window, aborting the same controller the wall-clock timeout targets so partial output is preserved and the run classifies as a failure. This is distinct from AFK_SUBAGENT_TIMEOUT_MS, the blunt wall-clock that bounds total turn time: the idle watchdog is the tighter first-to-fire bound and never fires while the stream is legitimately parked on a provider-communicated backoff (OAuth pause, or a rate-limit event carrying a retry-after), extending the deadline for the pause window instead. Default 480000 (8 min) clears the worst-case transient-429 backoff the watchdog is currently blind to (about 363s) with roughly 2 min of margin, while staying materially tighter than the 45-min wall-clock. Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to disable the idle watchdog for a whole session (the wall-clock still applies). v1 applies to forked sub-agent turns only, not top-level or daemon sessions.",type:"number",required:!1,default:"480000",example:"300000",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_OVERLOAD_PAUSE_MS",description:"Wall-clock ceiling (ms) for the bounded pause after a mid-stream overload (529) exhausts its retry budget. Overrides the per-surface default for ALL surfaces: 0 disables the pause (fail fast). Interactive surfaces (cli/repl/telegram) default to 600000; daemon/cron default to 0 so an always-on runner never silently parks on upstream capacity.",type:"number",required:!1,example:"600000",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_PROMPT",description:"Enable LLM-generated empty-prompt suggestions \u2014 a proposed next action shown as ghost text when the prompt is blank, accepted with Tab or Right-arrow. Fires only after a turn has completed in the session: the startup prompt (and the prompt right after /clear) is left clean because there is no session context to ground a proposal in. Set to 1/true/yes/on to activate. Off by default. Requires AFK_SUGGEST_ENABLED (it reuses the same suggestion model and provider).",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_THINKING_UI",description:"Default thinking-display mode for the interactive REPL: summary | live | digest | off. Display-only \u2014 controls how extended-thinking blocks render, never whether thinking runs (cost/latency unaffected). Overridden per-launch by --thinking-ui and mutable mid-session via /thinking. Precedence: --thinking-ui flag > this env > interactive.thinkingUi config > live. Invalid values are ignored.",type:"string",required:!1,default:"live",example:"digest",category:"misc"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Opt into using ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. READ-ONLY: AFK never refreshes these tokens \u2014 re-run `codex` when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to a truthy value ('1'/'true'/'yes'/'on', case-insensitive) to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"true",category:"telegram"},{name:"TMUX",description:"OS-level tmux session identifier. Set automatically by tmux to the socket path and session info (e.g. /tmp/tmux-501/default,12345,0) inside any tmux pane. Not set by AFK. Read by configureColor() to detect a tmux environment; for truecolor support on Node \u2264 24, set FORCE_COLOR=3 in your shell or ~/.afk/config/afk.env.",type:"string",required:!1,example:"/tmp/tmux-501/default,12345,0",category:"process"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"AFK_COMPANION_PRIMER",description:'Opt-in: absolute path to a single companion-primer file. When set, its content is bounded (capped, fenced as <companion-primer>) and appended to the system prompt at session start for top-level sessions (chat/REPL/telegram/daemon), as lower-authority "reflections, not facts" context. Unset (default) = no-op. Only the one named file is ever read \u2014 never a directory or repo walk.',type:"string",required:!1,example:"/Users/me/Projects/afk-companion/PRIMER.md",category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WEB_PORT",description:"Port for the `afk web` browser surface. Defaults to 4141; falls back to an ephemeral port when taken. Overridden by --port.",type:"number",required:!1,example:"4141",category:"daemon"},{name:"AFK_WEB_HOST",description:"Bind address for the `afk web` browser surface. Defaults to 127.0.0.1. Unlike the daemon control surface, a non-loopback bind is REFUSED unless AFK_WEB_TOKEN (or --token) is also set, because this surface can submit prompts and approve tool use. Overridden by --host.",type:"string",required:!1,example:"127.0.0.1",category:"daemon"},{name:"AFK_WEB_TOKEN",description:"Bearer token for the `afk web` surface. When unset, a random per-run token is minted and printed in the startup URL. Setting this explicitly is also what permits a non-loopback bind.",type:"string",required:!1,category:"daemon",secret:!0},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_ON_EXIT",description:"Clean-worktree quit policy for interactive --worktree sessions: ask, keep, or remove.",type:"string",required:!1,example:"ask",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_GOBLIN_MASCOT",description:"Reacting goblin mini-sprite in the reserved footer band while the agent runs tools (3 rows, animated). 1 = on, unset/0 = off (default). Claims terminal rows, so it is opt-in.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | umber | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark; umber matches the Umber terminal, is dark-only, and is never chosen by auto. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"AFK_TEXT_MEASURE",description:"Maximum line length (columns) for unbordered streamed text in the interactive REPL: assistant prose, thinking blocks, tool-lane text, and subagent text. Display-only \u2014 affects wrapping, never behavior. Bordered elements (cards, error boxes) already cap at 100; this applies the same ceiling to the unbordered surfaces, which previously scaled to the full terminal width. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable capping and restore full-width wrapping. Unparseable or below-minimum values fall back to the default. No-op on terminals at or below the measure, so narrow terminals are unaffected.",type:"string",required:!1,default:"100",example:"full",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"COLORTERM",description:"OS-level terminal color-depth hint. Accepted values: truecolor or 24bit (24-bit color), 256color (256-color). Set by the outer terminal emulator, not by AFK. Read by chalk's supports-color to set its initial color level; also read by configureColor() to recommend FORCE_COLOR=3 for tmux truecolor users on Node \u2264 24.",type:"string",required:!1,example:"truecolor",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_RETENTION_DISABLE",description:"Disable the witness-tree retention sweep entirely, so no session directory is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_MAX_AGE_DAYS",description:"Evict a witness session directory once its newest content is older than this many days. Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_WITNESS_MAX_BYTES",description:"Aggregate byte cap for the witness tree; oldest session directories are evicted first once exceeded. Default 2147483648 (2 GiB).",type:"number",required:!1,default:"2147483648",category:"debug"},{name:"AFK_SESSION_LEDGER_DISABLED",description:"Disable the per-session durable event ledger (state/sessions/<id>/events.jsonl). Set to 1 to skip ledger writes; live cross-surface watching (e.g. the Telegram /watch command) will report no activity for sessions started while disabled.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_RUN_RECEIPT_DISABLED",description:"Disable the post-session run receipt (state/receipts/<label>.json and .md). Set to 1 to skip receipt writes; the underlying witness trace is unaffected. Receipts are also implicitly off when AFK_TRACE_DISABLED=1 (no trace to summarize).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_PROMPTS",description:"Opt-in: when set to 1, every prompt a parent session sends to a subagent is written as a redacted markdown file under state/witness/<label>/prompts/. Off by default because nothing prunes the witness tree and prompts may carry secrets the regex redactor cannot catch (connection strings, PEM blocks, PII).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_CAPTURE_SUBAGENT_OUTPUT",description:"Opt-in: when set to 1, a subagent's conversational OUTPUT (assistant text plus each tool call with its arguments) is appended incrementally to a redacted markdown transcript under state/witness/<label>/outputs/. Flushed at every tool-call boundary, so a child killed by a timeout still leaves a usable partial record \u2014 the case where final-message capture yields nothing. Off by default for the same reasons as AFK_CAPTURE_SUBAGENT_PROMPTS (unpruned witness tree, best-effort regex redaction).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless on every AFK surface \u2014 the CLI entrypoint reports surface `afk`, which is in the headless set \u2014 so watching the agent work in a visible window is opt-in via `AFK_BROWSER_HEADLESS=0`, not implied by running the REPL. Note headed and headless use different chromium downloads (`chromium-*` vs `chromium_headless_shell-*`).",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_READ_DENYLIST",description:"Colon-separated list of additional absolute paths the read_file/grep/glob/list_directory tools refuse to read, and that the bash-restriction hook refuses to let a shell command reference on interactive surfaces (REPL, Telegram) \u2014 on headless surfaces (afk chat, daemon) bash fails open regardless of this list. A leading ~/ is expanded (~user/ is not \u2014 spell those absolutely). Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed. One built-in exception exists: ~/.afk/config/mcp.json (the MCP registry) IS readable \u2014 paths listed here outrank that carve-out, so set this to ~/.afk/config/mcp.json if your registry holds inline secrets rather than ${VAR} placeholders.",type:"string",required:!1,example:"/Users/me/project/.env:/Users/me/secrets",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_WEB_ALLOW_PRIVATE_HOSTS",description:"Opt out of the web_scrape SSRF egress guard. When unset (default) the guard is ACTIVE: the markdown, raw, and headless-render paths refuse loopback (127/8, ::1), link-local (169.254/16 \u2014 including the 169.254.169.254 cloud instance-metadata endpoint), RFC1918 (10/8, 172.16/12, 192.168/16), carrier-grade NAT (100.64/10), IPv6 unique-local (fc00::/7), 0.0.0.0/8, and the IPv4-mapped/compatible IPv6 forms of all of those. Hostnames are resolved and the RESOLVED addresses are classified (DNS-rebinding guard), and the check is re-applied on every redirect hop. Set to 1/true to allow private-host access \u2014 needed only to scrape a local dev server. Enabling it restores a model-reachable SSRF path (issue #575).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],y={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_COMPACT_SHRINK_FRACTION(){return process.env.AFK_COMPACT_SHRINK_FRACTION},get AFK_COMPANION_PRIMER(){return process.env.AFK_COMPANION_PRIMER},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_CONCURRENT_BACKGROUND_JOBS(){return process.env.AFK_MAX_CONCURRENT_BACKGROUND_JOBS},get AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS(){return process.env.AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS},get AFK_MAX_CONCURRENT_SUBAGENT_CALLS(){return process.env.AFK_MAX_CONCURRENT_SUBAGENT_CALLS},get AFK_MAX_NESTING_DEPTH(){return process.env.AFK_MAX_NESTING_DEPTH},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MAX_TOOL_USE_ITERATIONS(){return process.env.AFK_MAX_TOOL_USE_ITERATIONS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MICROCOMPACT_KEEP_LAST(){return process.env.AFK_MICROCOMPACT_KEEP_LAST},get AFK_MICROCOMPACT_TOOL_RESULT_BYTES(){return process.env.AFK_MICROCOMPACT_TOOL_RESULT_BYTES},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_TTFB_TIMEOUT_MS(){return process.env.AFK_MODEL_TTFB_TIMEOUT_MS},get AFK_MODEL_STALL_TIMEOUT_MS(){return process.env.AFK_MODEL_STALL_TIMEOUT_MS},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_OVERLOAD_PAUSE_MS(){return process.env.AFK_OVERLOAD_PAUSE_MS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_PROMPT(){return process.env.AFK_SUGGEST_PROMPT},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_SUBAGENT_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_TIMEOUT_MS},get AFK_SUBAGENT_IDLE_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_IDLE_TIMEOUT_MS},get AFK_TASK_BUDGET(){return process.env.AFK_TASK_BUDGET},get AFK_TEMPERATURE(){return process.env.AFK_TEMPERATURE},get AFK_THINKING(){return process.env.AFK_THINKING},get AFK_THINKING_UI(){return process.env.AFK_THINKING_UI},get AFK_TIMEOUT_MS(){return process.env.AFK_TIMEOUT_MS},get CLAUDE_MODEL(){return process.env.CLAUDE_MODEL},get AFK_SYSTEM_PROMPT(){return process.env.AFK_SYSTEM_PROMPT},get AFK_DUMP_PROMPT(){return process.env.AFK_DUMP_PROMPT},get ANTHROPIC_API_KEY(){return process.env.ANTHROPIC_API_KEY},get CLAUDE_CODE_OAUTH_TOKEN(){return process.env.CLAUDE_CODE_OAUTH_TOKEN},get OPENAI_API_KEY(){return process.env.OPENAI_API_KEY},get CODEX_API_KEY(){return process.env.CODEX_API_KEY},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_TAG_ONLY_CHAT_IDS(){return process.env.AFK_TELEGRAM_TAG_ONLY_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get TMUX(){return process.env.TMUX},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WEB_PORT(){return process.env.AFK_WEB_PORT},get AFK_WEB_HOST(){return process.env.AFK_WEB_HOST},get AFK_WEB_TOKEN(){return process.env.AFK_WEB_TOKEN},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_ON_EXIT(){return process.env.AFK_WORKTREE_ON_EXIT},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_PLAIN_OUTPUT(){return process.env.AFK_PLAIN_OUTPUT},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_GOBLIN_SPINNER(){return process.env.AFK_GOBLIN_SPINNER},get AFK_GOBLIN_MASCOT(){return process.env.AFK_GOBLIN_MASCOT},get AFK_TERM_TITLE(){return process.env.AFK_TERM_TITLE},get AFK_NOTIFY(){return process.env.AFK_NOTIFY},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_THEME(){return process.env.AFK_THEME},get AFK_TEXT_MEASURE(){return process.env.AFK_TEXT_MEASURE},get COLORFGBG(){return process.env.COLORFGBG},get COLORTERM(){return process.env.COLORTERM},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_WITNESS_RETENTION_DISABLE(){return process.env.AFK_WITNESS_RETENTION_DISABLE},get AFK_WITNESS_MAX_AGE_DAYS(){return process.env.AFK_WITNESS_MAX_AGE_DAYS},get AFK_WITNESS_MAX_BYTES(){return process.env.AFK_WITNESS_MAX_BYTES},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get AFK_CAPTURE_SUBAGENT_PROMPTS(){return process.env.AFK_CAPTURE_SUBAGENT_PROMPTS},get AFK_CAPTURE_SUBAGENT_OUTPUT(){return process.env.AFK_CAPTURE_SUBAGENT_OUTPUT},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_READ_DENYLIST(){return process.env.AFK_READ_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_WEB_ALLOW_PRIVATE_HOSTS(){return process.env.AFK_WEB_ALLOW_PRIVATE_HOSTS},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get VISUAL(){return process.env.VISUAL},get EDITOR(){return process.env.EDITOR},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let e of Uo){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(y,e.name);n&&Object.defineProperty(y,e.name,{...n,enumerable:!1})}})()});function k_(){return y.AFK_DEBUG==="1"||y.DEBUG==="1"}function C(...t){k_()&&console.log(...t)}var oe=Ae(()=>{"use strict";O()});import{existsSync as Lu,mkdirSync as __,renameSync as E_,cpSync as T_,rmSync as A_}from"fs";import{join as j,dirname as ll,basename as R_,isAbsolute as cl}from"path";import{homedir as Uu}from"os";import{fileURLToPath as x_}from"url";function le(){let t=y.AFK_HOME;if(t!==void 0&&t!==""){if(!cl(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return j(Uu(),".afk")}function Oe(){let t=y.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!cl(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return j(le(),"agent-framework")}function Bo(){return j(Oe(),"forge-telemetry.jsonl")}function $u(){return j(Oe(),"briefs")}function Bu(){return j(Oe(),"facets")}function or(){return j(le(),"skills")}function pn(){return j(le(),"plugins")}function ju(t=process.cwd()){return j(t,".afk")}function Hu(t=process.cwd()){return j(ju(t),"skills")}function Wu(t=process.cwd()){return j(ju(t),"plugins")}function Ku(t=process.cwd()){return j(t,".afk","plans")}function jo(){return j(pn(),".index.json")}function dl(){return j(sr(),"schedules.json")}function Gu(){let t=x_(import.meta.url),e=ll(t);return j(e,"bundled-plugins")}function sr(){return j(le(),"config")}function be(){let t=y.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!cl(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return j(le(),"state")}function Re(){return j(be(),"sessions")}function Ho(){return j(be(),"presence")}function Wo(){return j(be(),"memory")}function Ko(){return j(be(),"session-grants.jsonl")}function qu(){return j(le(),"farms")}function zu(t){return j(qu(),t)}function Go(t){if(!I_.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function ir(){return j(be(),"witness")}function kt(t){return Go(t),j(ir(),t)}function Ju(t){return j(kt(t),"inbound-attachments")}function Vu(t){return j(kt(t),"prompts")}function Yu(t){return j(kt(t),"outputs")}function fn(t){return!t||t.startsWith("in-memory:")?null:R_(ll(t))}function Xu(t="default"){return j(be(),"daemon",`agent-afk@${t}`)}function Qu(){return j(be(),"worktree-sweep.lock")}function qo(){return j(be(),"worktree-roots.json")}function ul(){return j(sr(),"afk.env")}function mn(){return j(sr(),"afk.config.json")}function zo(){return j(Uu(),".afk.config.json")}function C_(){return j(le(),"sessions")}function P_(t,e){if(t!==e&&Lu(t)&&!Lu(e))try{__(ll(e),{recursive:!0});try{E_(t,e)}catch(n){if(n.code==="EXDEV")try{T_(t,e,{recursive:!0}),A_(t,{recursive:!0,force:!0})}catch(r){process.stderr.write(`[afk] migrateDirOnce: EXDEV fallback failed for ${t} \u2192 ${e}: ${String(r)}
|
|
2
2
|
`)}}}catch{}}function Zu(){P_(C_(),Re())}function pl(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>Nu)throw new Error(`Invalid browser profile: exceeds ${Nu} chars`);if(!M_.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function O_(){return j(be(),"browser")}function D_(t){return pl(t),j(O_(),t)}function fl(t){return j(D_(t),"storageState.json")}function gn(t){return typeof t=="string"&&t.length>0&&t.length<=L_&&F_.test(t)}function ar(t){if(!gn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return j(Re(),t)}function lr(t){return j(ar(t),"events.jsonl")}function ep(t){return j(ar(t),"session.key")}var I_,M_,Nu,F_,L_,F=Ae(()=>{"use strict";O();I_=/^[a-zA-Z0-9_-]+$/;M_=/^[A-Za-z0-9_-]+$/,Nu=128;F_=/^[A-Za-z0-9_-]+$/,L_=128});import{readFileSync as KI}from"node:fs";import{join as GI}from"path";function qI(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function cg(t,e){return qI(e).test(t)}function VI(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(zI.has(e))return!0;if(JI.has(e))return!1}return!1}function dg(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function YI(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function ug(t){let e=t===void 0||t.trim()===""?"default":t.trim();return pl(e),e}function XI(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function QI(t){try{return KI(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function ZI(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")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=ug(e.defaultProfile)),n}function pg(t){let e=t?.env??y,n=t?.readFileSync??QI,r=t?.surface??e.AGENT_SURFACE,o=VI(e.AFK_BROWSER_HEADLESS,r),s=dg(e.AFK_BROWSER_ALLOWED_DOMAINS),i=dg(e.AFK_BROWSER_BLOCKED_DOMAINS),a=XI(e.AFK_BROWSER_DOM_SNAPSHOTS),l=YI(e.AFK_BROWSER_BACKEND),c=ug(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():GI(sr(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(h){throw new Error(`Failed to parse browser config at ${p}: ${String(h)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let g=ZI(d,m);return g.configPath=p,g}function Ws(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(cg(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>cg(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var zI,JI,Ks=Ae(()=>{"use strict";O();F();zI=new Set(["daemon","subagent","telegram","afk"]),JI=new Set(["repl","interactive","cli"])});import{existsSync as eC,readFileSync as tC}from"node:fs";import{createRequire as nC}from"node:module";import{dirname as rC,join as oC}from"node:path";function gg(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<iC&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function Te(t){let e=gg(t);return mg.some(n=>e.includes(n))}function aC(){try{let e=nC(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(tC(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=oC(rC(e),o);return eC(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function Kr(){return fg??=aC()??sC,fg}function Sc(t){return t.includes("install chromium")}function $e(t,e){let n=gg(t),r=e?.latched===!0?` ${lC}`:"";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: ${Kr()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Kr()}). Or pick a different tool.${r}`}function vc(t,e,n=!1){if(!Te(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
3
3
|
|
|
4
|
-
${$e(t,{headless:e,latched:n})}`,{cause:t})}var mg,sC,iC,fg,lC,kc=Ae(()=>{"use strict";mg=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],sC="pnpm exec playwright install chromium",iC=4;lC="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 tn from"node:fs";import Gs from"node:path";import{randomBytes as cC}from"node:crypto";import{chromium as dC}from"playwright";function uC(){try{return"5.114.0"}catch{}try{let t=Gs.resolve(import.meta.dirname,"../../../package.json"),e=tn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var pC,qs,hg=Ae(()=>{"use strict";kc();F();oe();pC=uC(),qs=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=dC.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=vc(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),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(l){s=l,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(),l;try{l=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let c=await a.content();if(s!==void 0)throw s;let d=a.url(),u=l!==null?l.status():null;return{html:c,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/${pC}`}}loadStorageState(e){let n=fl(e);try{if(!tn.existsSync(n))return;let r=JSON.parse(tn.readFileSync(n,"utf8"));return C("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){C("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=fl(e);if(!tn.existsSync(r))return;let o=await n.storageState(),s=Gs.join(Gs.dirname(r),`.${Gs.basename(r)}.${process.pid}.${cC(4).toString("hex")}.tmp`);tn.writeFileSync(s,JSON.stringify(o),{mode:384}),tn.chmodSync(s,384),tn.renameSync(s,r),C("[browser/vault] saved session",{profile:e,file:r})}catch(r){C("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as fC}from"crypto";function yg(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&mC.test(t.label))}function bg(t){return fC("sha256").update(t,"utf8").digest("hex").slice(0,8)}function wg(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var mC,zs=Ae(()=>{"use strict";mC=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as gC}from"node:crypto";function hC(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function yC(t,e,n){return`el_${gC("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function bC(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Sg(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function kg(t,e){let n=t.role??"",r=t.name??"";vg.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])kg(s,e)}async function wC(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(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,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},_g).catch(()=>[])}async function SC(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")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)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:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},_g).catch(()=>[])}function vC(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Js(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=vC(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=wC(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,b=!1;u!==null?(h=[],kg(u,h)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,h=(await SC(t)).filter(W=>vg.has(W.role??"")));let _=new Map;for(let T of p){let W=Sg(T.name),Q=_.get(W);(!Q||Q.bbox.w===0&&T.bbox.w>0)&&_.set(W,T)}let E=h.map(T=>({ax:T,dom:_.get(Sg(T.name??""))})),w=r?E:E.filter(T=>T.dom?T.dom.bbox.w>0||T.dom.bbox.h>0:!0);w.sort((T,W)=>{let Q=T.dom?.bbox.y??0,M=W.dom?.bbox.y??0;if(Q!==M)return Q-M;let L=T.dom?.bbox.x??0,D=W.dom?.bbox.x??0;return L-D}),w.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=w.slice(0,n).map((T,W)=>{let Q=T.ax.role??"generic",M=T.ax.name??"",L=yC(Q,M,W),D=T.dom?.bbox??{x:0,y:0,w:0,h:0},P=T.dom?.type??null,G=null;T.ax.value!==void 0&&T.ax.value!==null&&(G=String(T.ax.value)),T.ax.checked!==void 0&&(G=String(T.ax.checked)),yg({role:Q,kind:P})&&(G="[redacted]");let U={disabled:T.ax.disabled??!1};T.ax.checked!==void 0&&(U.checked=T.ax.checked===!0||T.ax.checked==="mixed"),T.ax.selected!==void 0&&(U.selected=T.ax.selected),T.ax.expanded!==void 0&&(U.expanded=T.ax.expanded);let J;T.dom?.testId?J=`[data-testid="${T.dom.testId}"]`:T.dom?.id&&(J=`#${T.dom.id}`);let Z={id:L,role:Q,label:hC(M),kind:P,value:G,state:U,bbox:D};return J!==void 0&&(Z.selector=J),Z}),x="idle";try{let T=await t.evaluate(()=>document.readyState);T==="loading"?x="loading":T==="interactive"?x="navigating":x="idle"}catch{x="navigating"}x!=="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=bC(f),S=`obs_${e.observationCounter.toString(36)}`,R=new Date().toISOString();return{observationId:S,url:m,title:g,textSummary:I,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:x,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:R}}var vg,_g,Eg=Ae(()=>{"use strict";zs();vg=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);_g="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Tg(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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 _c(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Tg(t,s)))).filter(o=>o!==null)}async function kC(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 l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Ec(t,e,n){switch(e.kind){case"element_id":return _C(t,e,n);case"selector":return EC(t,e);case"semantic":return TC(t,e)}}async function _C(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 l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}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 _c(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function EC(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 _c(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function TC(t,e){return e.role!==void 0?AC(t,e.text,e.role):RC(t,e.text,e)}async function AC(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 _c(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function RC(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===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}),l>0&&d.push({loc:s,count:l});let u=await kC(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 h=p[g];if(h===void 0)continue;let b=await Tg(h.locator,h.index);if(b!==null){let _=`${b.role}:${b.label}:${g}`,E=0;for(let w=0;w<_.length;w++)E=E*31+_.charCodeAt(w)>>>0;f.push({...b,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Ag=Ae(()=>{"use strict"});async function Tc(t,e,n,r){let o=t.url();if(o===n)return null;let s=Ws(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 Rg=Ae(()=>{"use strict";Ks()});import{randomBytes as xC}from"crypto";import{mkdir as IC,stat as CC,writeFile as PC}from"fs/promises";import{join as Ac}from"path";import{gzip as MC}from"zlib";import{promisify as OC}from"util";function DC(t){return Ac(kt(t),"browser")}function FC(t){return Ac(DC(t),"screenshots")}function LC(){return new Date().toISOString().replace(/[:.]/g,"-")}function NC(){return xC(3).toString("hex")}async function Rc(t,e,n){if(e.length>xg)throw new Error(`writeScreenshotSidecar: buffer exceeds ${xg} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=FC(t);await IC(r,{recursive:!0});let o=`${LC()}-${NC()}-${n}.png`,s=Ac(r,o);await PC(s,e);let{size:i}=await CC(s);return{path:s,bytes:i}}var iq,xg,Ig=Ae(()=>{"use strict";F();zs();iq=OC(MC);xg=5*1024*1024});var Pg={};Fu(Pg,{PlaywrightProvider:()=>xc});function Cg(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 xc,Mg=Ae(()=>{"use strict";hg();Eg();Ag();Ks();Rg();Ig();xc=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new qs(e)}async open(e){let n=Ws(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 l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Tc(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 Js(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 Js(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 Ec(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Cg(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.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(h){c=h}else c=g}let u=await Tc(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Js(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),c!==null)throw c;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 Ec(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Cg(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 Rc(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,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 Rc(n,o,r);return s}catch{return null}}}});var rn={};Fu(rn,{__resetBrowserRegistryForTests:()=>HC,browserProviderActive:()=>BC,closeBrowserProvider:()=>Ic,getBrowserProvider:()=>$C,peekBrowserProvider:()=>jC});function Og(){Promise.resolve(Ic()).then(()=>{process.exit(130)})}function Dg(){Promise.resolve(Ic()).then(()=>{process.exit(143)})}function Fg(){Ze=null}function UC(){Vs||(process.on("SIGINT",Og),process.on("SIGTERM",Dg),process.on("exit",Fg),Vs=!0)}function Lg(){Vs&&(process.removeListener("SIGINT",Og),process.removeListener("SIGTERM",Dg),process.removeListener("exit",Fg),Vs=!1)}async function $C(t){return Ze!==null?Ze:(nn!==null||(nn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Mg(),Pg)),n=pg(t),r=new e(n);return UC(),Ze=r,nn=null,r})()),nn)}async function Ic(){if(Ze===null)return;let t=Ze;Ze=null,nn=null,Lg(),await t.shutdown()}function BC(){return Ze!==null}function jC(){return Ze}function HC(){Ze=null,nn=null,Lg()}var Ze,nn,Vs,on=Ae(()=>{"use strict";Ks();Ze=null,nn=null,Vs=!1});oe();O();F();import{randomBytes as X_}from"node:crypto";import{mkdir as Q_,writeFile as Z_}from"node:fs/promises";import{join as eE}from"node:path";oe();var N_=256,tp=new WeakMap,cr=new Map;function U_(t){return t instanceof Error?t.message:String(t)}function $_(t,e){if(typeof e=="object"&&e!==null){let r=tp.get(e);return r||(r=new Set,tp.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(cr.has(n))return!1;if(cr.set(n,!0),cr.size>N_){let r=cr.keys().next().value;r!==void 0&&cr.delete(r)}return!0}function ge(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${U_(r)}`;if(!$_(t,e)){C(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}O();import{mkdirSync as j_,appendFileSync as H_,existsSync as W_}from"fs";import{resolve as K_}from"path";import{dirname as G_}from"path";function np(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>ml(e)||B_(e)?e:"[REDACTED]")}function ml(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function B_(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var q_=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
4
|
+
${$e(t,{headless:e,latched:n})}`,{cause:t})}var mg,sC,iC,fg,lC,kc=Ae(()=>{"use strict";mg=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],sC="pnpm exec playwright install chromium",iC=4;lC="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 tn from"node:fs";import Gs from"node:path";import{randomBytes as cC}from"node:crypto";import{chromium as dC}from"playwright";function uC(){try{return"5.114.1"}catch{}try{let t=Gs.resolve(import.meta.dirname,"../../../package.json"),e=tn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var pC,qs,hg=Ae(()=>{"use strict";kc();F();oe();pC=uC(),qs=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=dC.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=vc(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),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(l){s=l,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(),l;try{l=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let c=await a.content();if(s!==void 0)throw s;let d=a.url(),u=l!==null?l.status():null;return{html:c,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/${pC}`}}loadStorageState(e){let n=fl(e);try{if(!tn.existsSync(n))return;let r=JSON.parse(tn.readFileSync(n,"utf8"));return C("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){C("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=fl(e);if(!tn.existsSync(r))return;let o=await n.storageState(),s=Gs.join(Gs.dirname(r),`.${Gs.basename(r)}.${process.pid}.${cC(4).toString("hex")}.tmp`);tn.writeFileSync(s,JSON.stringify(o),{mode:384}),tn.chmodSync(s,384),tn.renameSync(s,r),C("[browser/vault] saved session",{profile:e,file:r})}catch(r){C("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as fC}from"crypto";function yg(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&mC.test(t.label))}function bg(t){return fC("sha256").update(t,"utf8").digest("hex").slice(0,8)}function wg(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var mC,zs=Ae(()=>{"use strict";mC=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as gC}from"node:crypto";function hC(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function yC(t,e,n){return`el_${gC("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function bC(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Sg(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function kg(t,e){let n=t.role??"",r=t.name??"";vg.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])kg(s,e)}async function wC(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(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,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},_g).catch(()=>[])}async function SC(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")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)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:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},_g).catch(()=>[])}function vC(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Js(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=vC(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=wC(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,b=!1;u!==null?(h=[],kg(u,h)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,h=(await SC(t)).filter(W=>vg.has(W.role??"")));let _=new Map;for(let T of p){let W=Sg(T.name),Q=_.get(W);(!Q||Q.bbox.w===0&&T.bbox.w>0)&&_.set(W,T)}let E=h.map(T=>({ax:T,dom:_.get(Sg(T.name??""))})),w=r?E:E.filter(T=>T.dom?T.dom.bbox.w>0||T.dom.bbox.h>0:!0);w.sort((T,W)=>{let Q=T.dom?.bbox.y??0,M=W.dom?.bbox.y??0;if(Q!==M)return Q-M;let L=T.dom?.bbox.x??0,D=W.dom?.bbox.x??0;return L-D}),w.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=w.slice(0,n).map((T,W)=>{let Q=T.ax.role??"generic",M=T.ax.name??"",L=yC(Q,M,W),D=T.dom?.bbox??{x:0,y:0,w:0,h:0},P=T.dom?.type??null,G=null;T.ax.value!==void 0&&T.ax.value!==null&&(G=String(T.ax.value)),T.ax.checked!==void 0&&(G=String(T.ax.checked)),yg({role:Q,kind:P})&&(G="[redacted]");let U={disabled:T.ax.disabled??!1};T.ax.checked!==void 0&&(U.checked=T.ax.checked===!0||T.ax.checked==="mixed"),T.ax.selected!==void 0&&(U.selected=T.ax.selected),T.ax.expanded!==void 0&&(U.expanded=T.ax.expanded);let J;T.dom?.testId?J=`[data-testid="${T.dom.testId}"]`:T.dom?.id&&(J=`#${T.dom.id}`);let Z={id:L,role:Q,label:hC(M),kind:P,value:G,state:U,bbox:D};return J!==void 0&&(Z.selector=J),Z}),x="idle";try{let T=await t.evaluate(()=>document.readyState);T==="loading"?x="loading":T==="interactive"?x="navigating":x="idle"}catch{x="navigating"}x!=="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=bC(f),S=`obs_${e.observationCounter.toString(36)}`,R=new Date().toISOString();return{observationId:S,url:m,title:g,textSummary:I,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:x,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:R}}var vg,_g,Eg=Ae(()=>{"use strict";zs();vg=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);_g="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Tg(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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 _c(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Tg(t,s)))).filter(o=>o!==null)}async function kC(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 l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Ec(t,e,n){switch(e.kind){case"element_id":return _C(t,e,n);case"selector":return EC(t,e);case"semantic":return TC(t,e)}}async function _C(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 l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}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 _c(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function EC(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 _c(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function TC(t,e){return e.role!==void 0?AC(t,e.text,e.role):RC(t,e.text,e)}async function AC(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 _c(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function RC(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===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}),l>0&&d.push({loc:s,count:l});let u=await kC(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 h=p[g];if(h===void 0)continue;let b=await Tg(h.locator,h.index);if(b!==null){let _=`${b.role}:${b.label}:${g}`,E=0;for(let w=0;w<_.length;w++)E=E*31+_.charCodeAt(w)>>>0;f.push({...b,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Ag=Ae(()=>{"use strict"});async function Tc(t,e,n,r){let o=t.url();if(o===n)return null;let s=Ws(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 Rg=Ae(()=>{"use strict";Ks()});import{randomBytes as xC}from"crypto";import{mkdir as IC,stat as CC,writeFile as PC}from"fs/promises";import{join as Ac}from"path";import{gzip as MC}from"zlib";import{promisify as OC}from"util";function DC(t){return Ac(kt(t),"browser")}function FC(t){return Ac(DC(t),"screenshots")}function LC(){return new Date().toISOString().replace(/[:.]/g,"-")}function NC(){return xC(3).toString("hex")}async function Rc(t,e,n){if(e.length>xg)throw new Error(`writeScreenshotSidecar: buffer exceeds ${xg} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=FC(t);await IC(r,{recursive:!0});let o=`${LC()}-${NC()}-${n}.png`,s=Ac(r,o);await PC(s,e);let{size:i}=await CC(s);return{path:s,bytes:i}}var iq,xg,Ig=Ae(()=>{"use strict";F();zs();iq=OC(MC);xg=5*1024*1024});var Pg={};Fu(Pg,{PlaywrightProvider:()=>xc});function Cg(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 xc,Mg=Ae(()=>{"use strict";hg();Eg();Ag();Ks();Rg();Ig();xc=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new qs(e)}async open(e){let n=Ws(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 l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await Tc(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 Js(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 Js(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 Ec(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Cg(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.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(h){c=h}else c=g}let u=await Tc(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Js(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),c!==null)throw c;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 Ec(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Cg(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 Rc(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,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 Rc(n,o,r);return s}catch{return null}}}});var rn={};Fu(rn,{__resetBrowserRegistryForTests:()=>HC,browserProviderActive:()=>BC,closeBrowserProvider:()=>Ic,getBrowserProvider:()=>$C,peekBrowserProvider:()=>jC});function Og(){Promise.resolve(Ic()).then(()=>{process.exit(130)})}function Dg(){Promise.resolve(Ic()).then(()=>{process.exit(143)})}function Fg(){Ze=null}function UC(){Vs||(process.on("SIGINT",Og),process.on("SIGTERM",Dg),process.on("exit",Fg),Vs=!0)}function Lg(){Vs&&(process.removeListener("SIGINT",Og),process.removeListener("SIGTERM",Dg),process.removeListener("exit",Fg),Vs=!1)}async function $C(t){return Ze!==null?Ze:(nn!==null||(nn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Mg(),Pg)),n=pg(t),r=new e(n);return UC(),Ze=r,nn=null,r})()),nn)}async function Ic(){if(Ze===null)return;let t=Ze;Ze=null,nn=null,Lg(),await t.shutdown()}function BC(){return Ze!==null}function jC(){return Ze}function HC(){Ze=null,nn=null,Lg()}var Ze,nn,Vs,on=Ae(()=>{"use strict";Ks();Ze=null,nn=null,Vs=!1});oe();O();F();import{randomBytes as X_}from"node:crypto";import{mkdir as Q_,writeFile as Z_}from"node:fs/promises";import{join as eE}from"node:path";oe();var N_=256,tp=new WeakMap,cr=new Map;function U_(t){return t instanceof Error?t.message:String(t)}function $_(t,e){if(typeof e=="object"&&e!==null){let r=tp.get(e);return r||(r=new Set,tp.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(cr.has(n))return!1;if(cr.set(n,!0),cr.size>N_){let r=cr.keys().next().value;r!==void 0&&cr.delete(r)}return!0}function ge(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${U_(r)}`;if(!$_(t,e)){C(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}O();import{mkdirSync as j_,appendFileSync as H_,existsSync as W_}from"fs";import{resolve as K_}from"path";import{dirname as G_}from"path";function np(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>ml(e)||B_(e)?e:"[REDACTED]")}function ml(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function B_(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var q_=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
5
5
|
`,z_=/key|token|secret|password|credential|auth/i;function rp(t){let e=t[1],n=t[2],r=n[0],o=(r==='"'||r==="'")&&n.at(-1)===r?n.slice(1,-1):n,s=/(?:^|_)(?:PATH|FILE)(?:_|$)/i.test(e),i=o.startsWith("/")||o.startsWith("~/"),l=o.split("/").filter(Boolean).some(c=>/[A-Z0-9.\-]/.test(c));return s&&i&&l&&ml(o)?`${e}=${n}`:`${e}=<REDACTED length=${n.length}>`}var J_=[[/sk-ant-[A-Za-z0-9_\-]{8,200}/g,t=>`<REDACTED sk-ant length=${t[0].length}>`],[/sk-(?!ant-)[A-Za-z0-9_\-]{20,200}/g,t=>`<REDACTED sk- length=${t[0].length}>`],[/Bearer\s+[A-Za-z0-9\-._~+/]+=*/gi,t=>`<REDACTED Bearer length=${t[0].length}>`],[/AKIA[A-Z0-9]{16}/g,t=>`<REDACTED AKIA length=${t[0].length}>`],[/xox[baprs]-[A-Za-z0-9\-]{10,200}/g,t=>`<REDACTED xox token length=${t[0].length}>`],[/\d{8,12}:[A-Za-z0-9_\-]{35}/g,t=>`<REDACTED Telegram token length=${t[0].length}>`],[/([A-Za-z_]{3,}(?:[Kk][Ee][Yy]|[Tt][Oo][Kk][Ee][Nn]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Cc][Rr][Ee][Dd][Ee][Nn][Tt][Ii][Aa][Ll])[A-Za-z_]*)=([^\s]{16,})/g,rp],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,rp]];function dr(t){let e=t;for(let[n,r]of J_)e=e.replace(n,(...o)=>{let s=o.slice(0,o.length-2);return r(s)});return e}function gl(t){return typeof t=="string"?dr(t):Array.isArray(t)?t.map(gl):t}function V_(t){if(t===null||typeof t!="object")return t;let e=t,n={...e},r=e.env;if(r&&typeof r=="object"){let o={};for(let[s,i]of Object.entries(r))z_.test(s)&&typeof i=="string"?o[s]=`<REDACTED length=${i.length}>`:o[s]=i;n.env=o}return"system"in e&&(n.system=gl(e.system)),"systemPrompt"in e&&(n.systemPrompt=gl(e.systemPrompt)),n}function Y_(t){if(t==null)return{kind:"undefined",note:"SDK uses minimal prompt; claude_code preset NOT loaded"};if(typeof t=="string")return{kind:"custom-string",note:"SDK uses this string as full system prompt; claude_code preset NOT loaded"};if(Array.isArray(t))return{kind:"custom-string-array",note:"SDK uses array as full system prompt with cache boundaries; claude_code preset NOT loaded"};if(typeof t=="object"){let e=t;if(e.type==="preset"&&e.preset==="claude_code"){let n={kind:"preset-claude-code",note:"claude_code preset loaded"};return typeof e.append=="string"&&(n.append={length:e.append.length}),e.excludeDynamicSections===!0&&(n.excludeDynamicSections=!0),n}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}return{kind:"custom-string",note:"Unrecognized systemPrompt shape; treated as opaque"}}function op(t){let e=y.AFK_DUMP_PROMPT;if(!e||e===""||e==="0"||e.toLowerCase()==="false")return;process.stderr.write(`[--dump-prompt] WARNING: dump may contain secrets from system prompt or messages. Inspect before sharing.
|
|
6
6
|
`);let n=t.options,r=typeof n=="object"&&n!==null?n.systemPrompt:void 0,o=Y_(r),s={timestamp:new Date().toISOString(),prompt:t.prompt,options:V_(t.options),provenance:t.provenance,resolution:o};if(e==="1"||e.toLowerCase()==="true"||e.toLowerCase()==="stderr"){let l=JSON.stringify(s,null,2)+`
|
|
7
7
|
`;process.stderr.write(l);return}let i=K_(e),a=G_(i);try{j_(a,{recursive:!0});let c=(!W_(i)?q_:"")+JSON.stringify(s)+`
|
|
@@ -251,7 +251,7 @@ ${e}`}O();import{BlockList as FI,isIP as bc}from"node:net";import{lookup as LI}f
|
|
|
251
251
|
`);a=_.pop()??"";for(let E of _){let w=Qh(E);if(w&&(w.kind==="closed"&&(l=!0),yield w,l))return}}catch(m){m.code!=="ENOENT"&&process.stderr.write(`[afk] session-ledger: tail read error for ${t}: ${String(m)}
|
|
252
252
|
`)}finally{f&&await f.close().catch(()=>{})}}if(o){if(yield*c(),l)return}else try{i=(await sn.stat(n)).size}catch{}let d=null,u=null,p=()=>new Promise(f=>{let m=setTimeout(()=>{u=null,f()},_M);u=()=>{clearTimeout(m),u=null,f()},s?.addEventListener("abort",()=>{clearTimeout(m),u=null,f()},{once:!0})});try{d=On.watch(r,{persistent:!1},()=>{u?.()})}catch{}try{for(;!s?.aborted&&!l&&(await p(),!s?.aborted);)yield*c()}finally{d?.close()}}F();import{readdir as EM,stat as TM}from"node:fs/promises";import{join as AM}from"node:path";async function zc(){let t=ir(),e;try{e=await EM(t)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of e){let o=AM(t,r,"trace.jsonl");try{let s=await TM(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 ty(){return(await zc())[0]?.sessionId??null}import{existsSync as RM}from"node:fs";import{readFile as xM}from"node:fs/promises";var ny=2097152;async function Jc(t){if(!RM(t))return{content:"",truncated:!1};try{let e=await xM(t);if(e.length<=ny)return{content:e.toString("utf-8"),truncated:!1};let n=e.subarray(e.length-ny),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 IM=50,CM=200,PM=200,MM=20,OM=100;function sy(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 DM(t){let e=[];for(let n of t.split(`
|
|
253
253
|
`))if(n.trim()!=="")try{let r=JSON.parse(n);sy(r)&&e.push(r)}catch{}return e}function FM(t){return typeof t!="number"?IM:Math.min(Math.max(1,Math.round(t)),CM)}function LM(t){return typeof t!="number"?MM:Math.min(Math.max(1,Math.round(t)),OM)}function NM(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 iy(t){let e=t.session==="latest"||!t.session?await ty():t.session;if(!e)return{sessionId:"(none)",events:[],totalInTrace:0,filtered:0};let n=oy(kt(e),"trace.jsonl");if(!ry(n))try{for await(let l of Zh(e))if(l.kind==="meta"){if(l.traceLabel===null)return{sessionId:e,events:[],totalInTrace:0,filtered:0,note:`Session "${e}" ran with tracing disabled (traceLabel: null).`};if(typeof l.traceLabel=="string"&&l.traceLabel.length>0){let c=oy(kt(l.traceLabel),"trace.jsonl");ry(c)&&(n=c)}break}}catch{}let{content:r}=await Jc(n),o=DM(r),s={kinds:t.kinds?new Set(t.kinds):void 0,toolName:t.toolName,errorsOnly:t.errorsOnly},i=FM(t.limit),a=[];for(let l=o.length-1;l>=0;l--){let c=o[l];if(NM(c,s)&&(a.push(c),a.length>=i))break}return a.reverse(),{sessionId:e,events:a,totalInTrace:o.length,filtered:a.length}}async function ay(t){let e=LM(t.sessions),r=(await zc()).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(),l=[],c=PM,d=[],u=0;for(let p of s){if(l.length>=c)break;let{content:f,truncated:m}=await Jc(p.tracePath);u++,m&&d.push(p.sessionId);for(let g of f.split(`
|
|
254
|
-
`)){if(l.length>=c)break;if(g.trim()!==""&&g.toLowerCase().includes(a))try{let h=JSON.parse(g);if(!sy(h)||i&&!i.has(h.kind))continue;l.push({sessionId:p.sessionId,event:h,matchLine:g.length>500?g.slice(0,500)+"\u2026":g})}catch{}}}return{query:t.query,sessionsAvailable:o,sessionsSearched:u,matches:l,...d.length>0?{truncatedSessions:d}:{}}}function ly(t){return!t||typeof t!="object"?null:t}function cy(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string")}var dy=async t=>{let e=ly(t);if(!e)return{content:"Invalid input: expected object",isError:!0};let n=typeof e.session=="string"?e.session:void 0,r=cy(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 iy({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}}},uy=async t=>{let e=ly(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=cy(e.kinds),s=typeof e.since=="string"?e.since:void 0;try{let i=await ay({query:n,sessions:r,kinds:o,since:s});return{content:JSON.stringify(i)}}catch(i){return{content:`search_witness failed: ${i instanceof Error?i.message:String(i)}`,isError:!0}}};var Dn={action:"decline"},py=300;function UM(t){return t.length<=py?t:`${t.slice(0,py)}\u2026(truncated)`}function $M(t){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${t.title??t.serverName}`,UM(t.message)];t.url!==void 0&&t.url!==""&&n.push(t.url),Qm(n.join(`
|
|
254
|
+
`)){if(l.length>=c)break;if(g.trim()!==""&&g.toLowerCase().includes(a))try{let h=JSON.parse(g);if(!sy(h)||i&&!i.has(h.kind))continue;l.push({sessionId:p.sessionId,event:h,matchLine:g.length>500?g.slice(0,500)+"\u2026":g})}catch{}}}return{query:t.query,sessionsAvailable:o,sessionsSearched:u,sessionsScanned:u,matches:l,...d.length>0?{truncatedSessions:d}:{}}}function ly(t){return!t||typeof t!="object"?null:t}function cy(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string")}var dy=async t=>{let e=ly(t);if(!e)return{content:"Invalid input: expected object",isError:!0};let n=typeof e.session=="string"?e.session:void 0,r=cy(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 iy({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}}},uy=async t=>{let e=ly(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=cy(e.kinds),s=typeof e.since=="string"?e.since:void 0;try{let i=await ay({query:n,sessions:r,kinds:o,since:s});return{content:JSON.stringify(i)}}catch(i){return{content:`search_witness failed: ${i instanceof Error?i.message:String(i)}`,isError:!0}}};var Dn={action:"decline"},py=300;function UM(t){return t.length<=py?t:`${t.slice(0,py)}\u2026(truncated)`}function $M(t){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${t.title??t.serverName}`,UM(t.message)];t.url!==void 0&&t.url!==""&&n.push(t.url),Qm(n.join(`
|
|
255
255
|
`)).catch(()=>{})}catch{}}function fy(t,e){if(!(t===void 0||t===""))try{$l(t,e).catch(()=>{})}catch{}}var Vc=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(Dn);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(Dn);return}if(!s){$M(e),r(Dn);return}let i,a=new Promise(l=>{i=()=>l(Dn),n.signal.addEventListener("abort",i,{once:!0})});try{try{n.onActive?.()}catch{}fy(n.sessionId,!0);let l=await Promise.race([s(e,n).catch(()=>Dn),a]);r(l)}finally{fy(n.sessionId,!1),n.signal.removeEventListener("abort",i)}}finally{this.queueDepth-=1,r(Dn)}}).catch(()=>{}),o}},an=new Vc;var my=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,l=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(l!==void 0&&(typeof l!="number"||!Number.isFinite(l)))return{content:"Invalid input: max must be a finite number",isError:!0};if(a!==void 0&&l!==void 0&&a>l)return{content:`Invalid input: min (${a}) must be \u2264 max (${l})`,isError:!0};let c=r.min_length,d=r.max_length;if(c!==void 0&&typeof c!="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((c!==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},...c!==void 0&&{minLength:c},...d!==void 0&&{maxLength:d},...a!==void 0&&{min:a},...l!==void 0&&{max:l},...r.allow_skip!==void 0&&{allowSkip:!!r.allow_skip},...r.allow_custom!==void 0&&{allowCustom:!!r.allow_custom}},p=await an.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"}}};O();var gy=["load","domcontentloaded","networkidle"];function BM(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(!gy.includes(e.wait_for))return{error:`browser_open: "wait_for" must be one of ${gy.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 jM(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_open aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0,failureClass:ke(n)}}let o=BM(e);if("error"in o)return{content:o.error,isError:!0};let s=y.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;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(on(),rn));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Te(c)?{content:$e(c),isError:!0}:{content:`browser_open failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.open({sessionId:s,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),c=Date.now()-a;if("outcome"in l&&l.outcome==="blocked_by_policy")return pe(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:c}),{content:`browser_open blocked: ${l.reason}`,isError:!0,failureClass:"policy-refusal"};let d=l;return pe(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:d.url,status:"ok",durationMs:c,...d.screenshotPath!==null?{screenshotPath:d.screenshotPath}:{}}),{content:JSON.stringify(d,null,2)}}catch(l){let c=Date.now()-a,d=l instanceof Error?l.message:String(l);pe(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:d,recoverable:!1}});let u=Ys(l);return{content:`browser_open failed: ${d}`,isError:!0,...u?{failureClass:u}:{}}}}}var hy=jM();O();function HM(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 WM(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_observe aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=HM(e);if("error"in o)return{content:o.error,isError:!0};let s=y.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;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(on(),rn));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Te(c)?{content:$e(c),isError:!0}:{content:`browser_observe failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.observe({sessionId:s,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),c=Date.now()-a;return pe(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:l.url,urlAfter:l.url,status:"ok",durationMs:c,...l.screenshotPath!==null?{screenshotPath:l.screenshotPath}:{}}),{content:JSON.stringify(l,null,2)}}catch(l){let c=Date.now()-a,d=l instanceof Error?l.message:String(l);return pe(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:d,recoverable:!1}}),{content:`browser_observe failed: ${d}`,isError:!0}}}}var yy=WM();zs();O();var by=["click","fill","press","select","hover","scroll_to","wait_for"],wy=["semantic","element_id","selector"];function KM(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(!by.includes(e.action))return{error:`browser_act: "action" must be one of ${by.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"||!wy.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${wy.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 l;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'};l=e.timeout_ms}let c;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};c=e.screenshot}return{action:n,target:s,value:a,timeoutMs:l,screenshot:c}}function GM(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(`
|
|
256
256
|
`)}function qM(t){return t.kind==="semantic"?{kind:"semantic",text:wg(t.text),...t.role!==void 0?{role:t.role}:{}}:t.kind==="element_id"?{kind:"element_id",elementId:t.elementId}:{kind:"selector",selectorHash:bg(t.selector)}}function zM(t={}){return async(e,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_act aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0,failureClass:ke(n)}}let o=KM(e);if("error"in o)return{content:o.error,isError:!0};let s=qM(o.target),i=y.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;try{if(t.getBrowserProvider)a=await t.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(on(),rn));a=await c()}}catch(c){let d=c instanceof Error?c.message:String(c);return Te(d)?{content:$e(d),isError:!0}:{content:`browser_act failed to get provider: ${d}`,isError:!0}}let l=Date.now();try{let c=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),d=Date.now()-l;if("outcome"in c){if(c.outcome==="ambiguous_target")return pe(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:d}),{content:GM(c.query,c.candidates),isError:!0};if(c.outcome==="blocked_by_policy")return pe(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:d}),{content:`browser_act blocked: ${c.reason}`,isError:!0,failureClass:"policy-refusal"}}return pe(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:c.url,urlAfter:c.url,status:"ok",durationMs:d,...c.screenshotPath!==null?{screenshotPath:c.screenshotPath}:{}}),{content:JSON.stringify(c,null,2)}}catch(c){let d=Date.now()-l,u=c instanceof Error?c.message:String(c);pe(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}});let p=Ys(c);return{content:`browser_act failed: ${u}`,isError:!0,...p?{failureClass:p}:{}}}}}var Sy=zM();O();var vy=["semantic","element_id","selector"],Yc=8e3;function JM(t){if(typeof t.kind!="string"||!vy.includes(t.kind))return{error:`browser_screenshot: "target.kind" must be one of ${vy.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 VM(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=JM(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 YM(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_screenshot aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=VM(e);if("error"in o)return{content:o.error,isError:!0};let s=y.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;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(on(),rn));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return Te(c)?{content:$e(c),isError:!0}:{content:`browser_screenshot failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),c=Date.now()-a,{dataBase64:d,mediaType:u,...p}=l;return pe(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:c,screenshotPath:p.path}),p.width>Yc||p.height>Yc?{content:JSON.stringify({...p,imageOmitted:`dimensions ${p.width}x${p.height}px exceed the ${Yc}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(p,null,2),image:{mediaType:u,data:d}}}catch(l){let c=Date.now()-a,d=l instanceof Error?l.message:String(l);return pe(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:d,recoverable:!1}}),{content:`browser_screenshot failed: ${d}`,isError:!0}}}}var ky=YM();O();function XM(t={}){return async(e,n,r)=>{if(n.aborted){let a=n.reason;return{content:`browser_close aborted: ${a instanceof Error?a.message:String(a??"aborted")}`,isError:!0}}let o=y.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;try{if(t.getBrowserProvider)s=await t.getBrowserProvider();else{let{getBrowserProvider:a}=await Promise.resolve().then(()=>(on(),rn));s=await a()}}catch(a){let l=a instanceof Error?a.message:String(a);return Te(l)?{content:$e(l),isError:!0}:{content:`browser_close failed to get provider: ${l}`,isError:!0}}let i=Date.now();try{await s.close({sessionId:o});let a=Date.now()-i;return pe(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:a}),{content:"Browser session closed."}}catch(a){let l=Date.now()-i,c=a instanceof Error?a.message:String(a);return pe(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:l,error:{reason:c,recoverable:!1}}),{content:`browser_close failed: ${c}`,isError:!0}}}}var _y=XM();function Fn(t,e){let n=t!==void 0?Ms(t,e):e!==void 0?Ms("default",e):Vf,r=e!==void 0?ec(e):tm,o=e!==void 0?tc(e):om,s=e!==void 0?Xl(e):Yf,i=e!==void 0?Ql(e):Qf,a=e!==void 0?Zl(e):Zf,l=e!==void 0?nc(e):sm,c=Dc(),d=wh(e);return new Map([["bash",n],["read_file",s],["write_file",i],["edit_file",a],["glob",r],["grep",o],["list_directory",l],["send_telegram",eg],["web_scrape",jg],["create_schedule",zg],["list_schedules",Jg],["get_schedule_history",Vg],["cancel_schedule",Yg],["read_witness",dy],["search_witness",uy],["worktree",d],["terminal_font_size",c],["config_get",zh],["config_set",Jh],["ask_question",my],["browser_open",hy],["browser_observe",yy],["browser_act",Sy],["browser_screenshot",ky],["browser_close",_y]])}function Ey(t){return["The user has switched off plan mode. Writes are now permitted. Do two things, in order:","",`1. Save the plan. Write the plan you developed in this conversation to a new markdown file under \`${t}/\` \u2014 pick a short, descriptive kebab-case filename (e.g. \`${t}/refactor-auth-flow.md\`). Capture the full plan: the chosen approach, the concrete step-by-step changes, the risks named, and the alternatives considered. This is the durable record.`,"","2. Implement the plan. Work through the steps you just recorded, verifying as you go \u2014 run the project's lint/test gates where they apply. End in a terminal state: Done with evidence, Blocked with the exact unblock condition, or Asking one precise question."].join(`
|
|
257
257
|
`)}F();var ft="exit_plan_mode",QM="Approve \u2014 implement now (bypass mode: no prompts, read/write any path)",Xc="Keep planning";function ZM(t){switch(t){case"bypassPermissions":return"Approve \u2014 implement now (restore bypass mode: no prompts, read/write any path)";case"acceptEdits":return"Approve \u2014 implement now (restore accept-edits mode: edits auto-approved)";case"dontAsk":case"auto":return"Approve \u2014 implement now (restore your previous mode: no approval prompts)";default:return"Approve \u2014 implement now (restore default mode: writes ask for confirmation, contained to the workspace)"}}var pi={name:ft,category:"other",concurrencySafe:!1,description:`Signal that your plan is ready and present it to the user for approval. The user is shown a picker: approve and implement (you pick neither mode \u2014 the user does), or keep planning.
|
package/dist/telegram.mjs
CHANGED
|
@@ -211,7 +211,7 @@ ${o}`,paths:[e,n]}:o!==null?s={content:o,paths:[n]}:r!==null?s={content:r,paths:
|
|
|
211
211
|
|
|
212
212
|
${e}`}var aB,mf=h(()=>{"use strict";aB=new Set(["script","style","noscript","template","svg"])});function dB(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 vv(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function uB(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 kv(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??dB,l=n.signal??void 0,c;for(let d=0;d<=o;d++){if(l?.aborted)throw l.reason??new Error("aborted");try{let u=await t(e,n);if(!cB.has(u.status)||d===o)return u;let p=uB(u,i)??vv(d,s,i);N("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let p=vv(d,s,i);N("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var cB,Ev=h(()=>{"use strict";pe();cB=new Set([429,502,503,504])});import{BlockList as pB,isIP as hf}from"node:net";import{lookup as fB}from"node:dns/promises";import{Agent as mB}from"undici";function Tv(){let t=v.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return t==="1"||t==="true"}function bB(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function gf(t){let e=hf(t);return e===0?!1:yB.check(t,e===4?"ipv4":"ipv6")}async function Av(t){return fB(t,{all:!0,verbatim:!0})}async function yf(t,e={}){if(e.allowPrivateHosts??Tv())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=bB(n.hostname),o=(a,l)=>`refusing to fetch ${l} \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(hf(r)!==0)return gf(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let s=e.lookupFn??Av,i;try{i=await s(r)}catch{return{allowed:!0}}for(let a of i)if(gf(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function bs(t,e={}){let n=await yf(t,e);if(!n.allowed)throw new bt(n.reason)}async function ul(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<=_v;i++){await bs(s,o);let a={...n,redirect:"manual",...t===globalThis.fetch&&!(r.allowPrivateHosts??Tv())?{dispatcher:wB}:{}},l=await kv(t,s,a,r.retry??{});if(!SB.has(l.status))return l;let c=l.headers.get("location");if(c===null||c.trim()==="")return l;let d;try{d=new URL(c,l.url||s).toString()}catch{return l}await l.body?.cancel().catch(()=>{}),s=d}throw new bt(`too many redirects (>${_v}) starting from ${e}`)}var gB,hB,yB,bt,wB,_v,SB,bf=h(()=>{"use strict";U();Ev();gB=[["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]],hB=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],yB=(()=>{let t=new pB;for(let[e,n]of gB)t.addSubnet(e,n,"ipv4");for(let[e,n]of hB)t.addSubnet(e,n,"ipv6");return t})(),bt=class extends Error{constructor(e){super(e),this.name="EgressBlockedError"}};wB=new mB({connect:{lookup(t,e,n){Av(t).then(r=>{let o=r.find(i=>gf(i.address));if(o!==void 0){n(new bt(`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,hf(s.address))},r=>n(r,"",0))}}});_v=20,SB=new Set([301,302,303,307,308])});import{readFileSync as vB}from"node:fs";import{join as kB}from"path";function EB(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Rv(t,e){return EB(e).test(t)}function AB(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(_B.has(e))return!0;if(TB.has(e))return!1}return!1}function xv(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function RB(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function Cv(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Du(e),e}function xB(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function CB(t){try{return vB(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function IB(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")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=Cv(e.defaultProfile)),n}function Iv(t){let e=t?.env??v,n=t?.readFileSync??CB,r=t?.surface??e.AGENT_SURFACE,o=AB(e.AFK_BROWSER_HEADLESS,r),s=xv(e.AFK_BROWSER_ALLOWED_DOMAINS),i=xv(e.AFK_BROWSER_BLOCKED_DOMAINS),a=xB(e.AFK_BROWSER_DOM_SNAPSHOTS),l=RB(e.AFK_BROWSER_BACKEND),c=Cv(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():kB(jt(),"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=IB(d,m);return g.configPath=p,g}function pl(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(Rv(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Rv(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var _B,TB,fl=h(()=>{"use strict";U();j();_B=new Set(["daemon","subagent","telegram","afk"]),TB=new Set(["repl","interactive","cli"])});import{existsSync as PB,readFileSync as MB}from"node:fs";import{createRequire as OB}from"node:module";import{dirname as DB,join as FB}from"node:path";function Ov(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<NB&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function je(t){let e=Ov(t);return Mv.some(n=>e.includes(n))}function $B(){try{let e=OB(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(MB(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=FB(DB(e),o);return PB(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function ws(){return Pv??=$B()??LB,Pv}function wf(t){return t.includes("install chromium")}function lt(t,e){let n=Ov(t),r=e?.latched===!0?` ${UB}`:"";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: ${ws()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${ws()}). Or pick a different tool.${r}`}function Sf(t,e,n=!1){if(!je(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
213
213
|
|
|
214
|
-
${lt(t,{headless:e,latched:n})}`,{cause:t})}var Mv,LB,NB,Pv,UB,vf=h(()=>{"use strict";Mv=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],LB="pnpm exec playwright install chromium",NB=4;UB="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 Zn from"node:fs";import ml from"node:path";import{randomBytes as BB}from"node:crypto";import{chromium as jB}from"playwright";function HB(){try{return"5.114.0"}catch{}try{let t=ml.resolve(import.meta.dirname,"../../../package.json"),e=Zn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var WB,gl,Dv=h(()=>{"use strict";vf();j();pe();WB=HB(),gl=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=jB.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Sf(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),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(l){s=l,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(),l;try{l=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let c=await a.content();if(s!==void 0)throw s;let d=a.url(),u=l!==null?l.status():null;return{html:c,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/${WB}`}}loadStorageState(e){let n=Fu(e);try{if(!Zn.existsSync(n))return;let r=JSON.parse(Zn.readFileSync(n,"utf8"));return N("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){N("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Fu(e);if(!Zn.existsSync(r))return;let o=await n.storageState(),s=ml.join(ml.dirname(r),`.${ml.basename(r)}.${process.pid}.${BB(4).toString("hex")}.tmp`);Zn.writeFileSync(s,JSON.stringify(o),{mode:384}),Zn.chmodSync(s,384),Zn.renameSync(s,r),N("[browser/vault] saved session",{profile:e,file:r})}catch(r){N("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as KB}from"crypto";function Fv(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&GB.test(t.label))}function Lv(t){return KB("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Nv(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var GB,hl=h(()=>{"use strict";GB=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as qB}from"node:crypto";function zB(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function VB(t,e,n){return`el_${qB("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function JB(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function $v(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Bv(t,e){let n=t.role??"",r=t.name??"";Uv.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Bv(s,e)}async function YB(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(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,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},jv).catch(()=>[])}async function XB(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")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)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:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},jv).catch(()=>[])}function QB(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function yl(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=QB(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=YB(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),y,w=!1;u!==null?(y=[],Bv(u,y)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,y=(await XB(t)).filter($=>Uv.has($.role??"")));let E=new Map;for(let I of p){let $=$v(I.name),V=E.get($);(!V||V.bbox.w===0&&I.bbox.w>0)&&E.set($,I)}let _=y.map(I=>({ax:I,dom:E.get($v(I.name??""))})),k=r?_:_.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,$)=>{let V=I.dom?.bbox.y??0,P=$.dom?.bbox.y??0;if(V!==P)return V-P;let B=I.dom?.bbox.x??0,L=$.dom?.bbox.x??0;return B-L}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((I,$)=>{let V=I.ax.role??"generic",P=I.ax.name??"",B=VB(V,P,$),L=I.dom?.bbox??{x:0,y:0,w:0,h:0},M=I.dom?.type??null,F=null;I.ax.value!==void 0&&I.ax.value!==null&&(F=String(I.ax.value)),I.ax.checked!==void 0&&(F=String(I.ax.checked)),Fv({role:V,kind:M})&&(F="[redacted]");let H={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(H.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(H.selected=I.ax.selected),I.ax.expanded!==void 0&&(H.expanded=I.ax.expanded);let X;I.dom?.testId?X=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(X=`#${I.dom.id}`);let te={id:B,role:V,label:zB(P),kind:M,value:F,state:H,bbox:L};return X!==void 0&&(te.selector=X),te}),C="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?C="loading":I==="interactive"?C="navigating":C="idle"}catch{C="navigating"}C!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let x=JB(f),S=`obs_${e.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:S,url:m,title:g,textSummary:x,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:C,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:A}}var Uv,jv,Hv=h(()=>{"use strict";hl();Uv=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);jv="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Wv(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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 kf(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Wv(t,s)))).filter(o=>o!==null)}async function ZB(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 l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Ef(t,e,n){switch(e.kind){case"element_id":return ej(t,e,n);case"selector":return tj(t,e);case"semantic":return nj(t,e)}}async function ej(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 l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}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 kf(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function tj(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 kf(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function nj(t,e){return e.role!==void 0?rj(t,e.text,e.role):oj(t,e.text,e)}async function rj(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 kf(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function oj(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===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}),l>0&&d.push({loc:s,count:l});let u=await ZB(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 w=await Wv(y.locator,y.index);if(w!==null){let E=`${w.role}:${w.label}:${g}`,_=0;for(let k=0;k<E.length;k++)_=_*31+E.charCodeAt(k)>>>0;f.push({...w,id:`el_${_.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Kv=h(()=>{"use strict"});async function _f(t,e,n,r){let o=t.url();if(o===n)return null;let s=pl(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 Gv=h(()=>{"use strict";fl()});import{randomBytes as sj}from"crypto";import{mkdir as ij,stat as aj,writeFile as lj}from"fs/promises";import{join as Tf}from"path";import{gzip as cj}from"zlib";import{promisify as dj}from"util";function uj(t){return Tf(Et(t),"browser")}function pj(t){return Tf(uj(t),"screenshots")}function fj(){return new Date().toISOString().replace(/[:.]/g,"-")}function mj(){return sj(3).toString("hex")}async function Af(t,e,n){if(e.length>qv)throw new Error(`writeScreenshotSidecar: buffer exceeds ${qv} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=pj(t);await ij(r,{recursive:!0});let o=`${fj()}-${mj()}-${n}.png`,s=Tf(r,o);await lj(s,e);let{size:i}=await aj(s);return{path:s,bytes:i}}var nee,qv,zv=h(()=>{"use strict";j();hl();nee=dj(cj);qv=5*1024*1024});var Jv={};Au(Jv,{PlaywrightProvider:()=>Rf});function Vv(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 Rf,Yv=h(()=>{"use strict";Dv();Hv();Kv();fl();Gv();zv();Rf=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new gl(e)}async open(e){let n=pl(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 l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await _f(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 yl(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 yl(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 Ef(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Vv(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.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){c=y}else c=g}let u=await _f(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await yl(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),c!==null)throw c;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 Ef(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Vv(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 Af(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,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 Af(n,o,r);return s}catch{return null}}}});var tr={};Au(tr,{__resetBrowserRegistryForTests:()=>wj,browserProviderActive:()=>yj,closeBrowserProvider:()=>xf,getBrowserProvider:()=>hj,peekBrowserProvider:()=>bj});function Xv(){Promise.resolve(xf()).then(()=>{process.exit(130)})}function Qv(){Promise.resolve(xf()).then(()=>{process.exit(143)})}function Zv(){Dt=null}function gj(){bl||(process.on("SIGINT",Xv),process.on("SIGTERM",Qv),process.on("exit",Zv),bl=!0)}function ek(){bl&&(process.removeListener("SIGINT",Xv),process.removeListener("SIGTERM",Qv),process.removeListener("exit",Zv),bl=!1)}async function hj(t){return Dt!==null?Dt:(er!==null||(er=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Yv(),Jv)),n=Iv(t),r=new e(n);return gj(),Dt=r,er=null,r})()),er)}async function xf(){if(Dt===null)return;let t=Dt;Dt=null,er=null,ek(),await t.shutdown()}function yj(){return Dt!==null}function bj(){return Dt}function wj(){Dt=null,er=null,ek()}var Dt,er,bl,nr=h(()=>{"use strict";fl();Dt=null,er=null,bl=!1});async function tk(t,e){try{return await bv(t,e)}catch(n){return N("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function Tj(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(nr(),tr));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}async function nk(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??Tj,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,l=null,c=null;try{let u=await ul(n,t,{headers:_j,signal:e.signal},o);l=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(Ej.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(kj.test(p)&&!vj.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await tk(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof bt||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;c=u}if(!(s===null||s.textLength<200)&&s!==null){let u=ff({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await bs(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>bs(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await bs(u.finalUrl,o);let p=await tk(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=ff({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 bt)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=c instanceof Error?c.message:`HTTP ${l??"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 ${l??"error"}).`)}var vj,kj,Ej,_j,rk=h(()=>{"use strict";wv();mf();bf();pe();vj=/(text\/html|application\/xhtml\+xml)/i,kj=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,Ej=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,_j={"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 xj(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(Aj,{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),Rj),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=Te(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function ok(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?xj({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 sk(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
214
|
+
${lt(t,{headless:e,latched:n})}`,{cause:t})}var Mv,LB,NB,Pv,UB,vf=h(()=>{"use strict";Mv=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],LB="pnpm exec playwright install chromium",NB=4;UB="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 Zn from"node:fs";import ml from"node:path";import{randomBytes as BB}from"node:crypto";import{chromium as jB}from"playwright";function HB(){try{return"5.114.1"}catch{}try{let t=ml.resolve(import.meta.dirname,"../../../package.json"),e=Zn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var WB,gl,Dv=h(()=>{"use strict";vf();j();pe();WB=HB(),gl=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=jB.launch({headless:this.config.headless}).then(e=>(this.browser=e,this.launchPromise=void 0,this.clearLaunchFailure(),e)).catch(e=>{this.launchPromise=void 0;let n=Sf(e,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),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(l){s=l,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(),l;try{l=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let c=await a.content();if(s!==void 0)throw s;let d=a.url(),u=l!==null?l.status():null;return{html:c,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/${WB}`}}loadStorageState(e){let n=Fu(e);try{if(!Zn.existsSync(n))return;let r=JSON.parse(Zn.readFileSync(n,"utf8"));return N("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){N("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Fu(e);if(!Zn.existsSync(r))return;let o=await n.storageState(),s=ml.join(ml.dirname(r),`.${ml.basename(r)}.${process.pid}.${BB(4).toString("hex")}.tmp`);Zn.writeFileSync(s,JSON.stringify(o),{mode:384}),Zn.chmodSync(s,384),Zn.renameSync(s,r),N("[browser/vault] saved session",{profile:e,file:r})}catch(r){N("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as KB}from"crypto";function Fv(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&GB.test(t.label))}function Lv(t){return KB("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Nv(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var GB,hl=h(()=>{"use strict";GB=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as qB}from"node:crypto";function zB(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function VB(t,e,n){return`el_${qB("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function JB(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function $v(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Bv(t,e){let n=t.role??"",r=t.name??"";Uv.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Bv(s,e)}async function YB(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(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,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},jv).catch(()=>[])}async function XB(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")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?c="checkbox":g==="radio"?c="radio":g==="button"||g==="submit"||g==="reset"?c="button":g==="search"?c="searchbox":c="textbox"}if(!c)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:c,name:l,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},jv).catch(()=>[])}function QB(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function yl(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=QB(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=YB(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),y,w=!1;u!==null?(y=[],Bv(u,y)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,y=(await XB(t)).filter($=>Uv.has($.role??"")));let E=new Map;for(let I of p){let $=$v(I.name),V=E.get($);(!V||V.bbox.w===0&&I.bbox.w>0)&&E.set($,I)}let _=y.map(I=>({ax:I,dom:E.get($v(I.name??""))})),k=r?_:_.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,$)=>{let V=I.dom?.bbox.y??0,P=$.dom?.bbox.y??0;if(V!==P)return V-P;let B=I.dom?.bbox.x??0,L=$.dom?.bbox.x??0;return B-L}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((I,$)=>{let V=I.ax.role??"generic",P=I.ax.name??"",B=VB(V,P,$),L=I.dom?.bbox??{x:0,y:0,w:0,h:0},M=I.dom?.type??null,F=null;I.ax.value!==void 0&&I.ax.value!==null&&(F=String(I.ax.value)),I.ax.checked!==void 0&&(F=String(I.ax.checked)),Fv({role:V,kind:M})&&(F="[redacted]");let H={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(H.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(H.selected=I.ax.selected),I.ax.expanded!==void 0&&(H.expanded=I.ax.expanded);let X;I.dom?.testId?X=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(X=`#${I.dom.id}`);let te={id:B,role:V,label:zB(P),kind:M,value:F,state:H,bbox:L};return X!==void 0&&(te.selector=X),te}),C="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?C="loading":I==="interactive"?C="navigating":C="idle"}catch{C="navigating"}C!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let x=JB(f),S=`obs_${e.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:S,url:m,title:g,textSummary:x,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:C,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:A}}var Uv,jv,Hv=h(()=>{"use strict";hl();Uv=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);jv="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Wv(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:l,label:c,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 kf(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Wv(t,s)))).filter(o=>o!==null)}async function ZB(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 l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Ef(t,e,n){switch(e.kind){case"element_id":return ej(t,e,n);case"selector":return tj(t,e);case"semantic":return nj(t,e)}}async function ej(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 l=t.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}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 kf(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function tj(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 kf(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function nj(t,e){return e.role!==void 0?rj(t,e.text,e.role):oj(t,e.text,e)}async function rj(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 kf(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function oj(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===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}),l>0&&d.push({loc:s,count:l});let u=await ZB(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 w=await Wv(y.locator,y.index);if(w!==null){let E=`${w.role}:${w.label}:${g}`,_=0;for(let k=0;k<E.length;k++)_=_*31+E.charCodeAt(k)>>>0;f.push({...w,id:`el_${_.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var Kv=h(()=>{"use strict"});async function _f(t,e,n,r){let o=t.url();if(o===n)return null;let s=pl(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 Gv=h(()=>{"use strict";fl()});import{randomBytes as sj}from"crypto";import{mkdir as ij,stat as aj,writeFile as lj}from"fs/promises";import{join as Tf}from"path";import{gzip as cj}from"zlib";import{promisify as dj}from"util";function uj(t){return Tf(Et(t),"browser")}function pj(t){return Tf(uj(t),"screenshots")}function fj(){return new Date().toISOString().replace(/[:.]/g,"-")}function mj(){return sj(3).toString("hex")}async function Af(t,e,n){if(e.length>qv)throw new Error(`writeScreenshotSidecar: buffer exceeds ${qv} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=pj(t);await ij(r,{recursive:!0});let o=`${fj()}-${mj()}-${n}.png`,s=Tf(r,o);await lj(s,e);let{size:i}=await aj(s);return{path:s,bytes:i}}var nee,qv,zv=h(()=>{"use strict";j();hl();nee=dj(cj);qv=5*1024*1024});var Jv={};Au(Jv,{PlaywrightProvider:()=>Rf});function Vv(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 Rf,Yv=h(()=>{"use strict";Dv();Hv();Kv();fl();Gv();zv();Rf=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new gl(e)}async open(e){let n=pl(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 l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let u=await _f(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 yl(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 yl(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 Ef(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Vv(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,d=async()=>{switch(e.action){case"click":await l.click({timeout:i});break;case"fill":await l.fill(e.value??"");break;case"press":await l.press(e.value??"");break;case"select":await l.selectOption(e.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.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){c=y}else c=g}let u=await _f(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await yl(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),c!==null)throw c;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 Ef(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Vv(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 Af(n,s,"browser_screenshot"),l=0,c=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=d.w,c=d.h}catch{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}else{let d=r.viewportSize();l=d?.width??0,c=d?.height??0}return{path:i,bytes:a,width:l,height:c,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 Af(n,o,r);return s}catch{return null}}}});var tr={};Au(tr,{__resetBrowserRegistryForTests:()=>wj,browserProviderActive:()=>yj,closeBrowserProvider:()=>xf,getBrowserProvider:()=>hj,peekBrowserProvider:()=>bj});function Xv(){Promise.resolve(xf()).then(()=>{process.exit(130)})}function Qv(){Promise.resolve(xf()).then(()=>{process.exit(143)})}function Zv(){Dt=null}function gj(){bl||(process.on("SIGINT",Xv),process.on("SIGTERM",Qv),process.on("exit",Zv),bl=!0)}function ek(){bl&&(process.removeListener("SIGINT",Xv),process.removeListener("SIGTERM",Qv),process.removeListener("exit",Zv),bl=!1)}async function hj(t){return Dt!==null?Dt:(er!==null||(er=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Yv(),Jv)),n=Iv(t),r=new e(n);return gj(),Dt=r,er=null,r})()),er)}async function xf(){if(Dt===null)return;let t=Dt;Dt=null,er=null,ek(),await t.shutdown()}function yj(){return Dt!==null}function bj(){return Dt}function wj(){Dt=null,er=null,ek()}var Dt,er,bl,nr=h(()=>{"use strict";fl();Dt=null,er=null,bl=!1});async function tk(t,e){try{return await bv(t,e)}catch(n){return N("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function Tj(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(nr(),tr));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}async function nk(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??Tj,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,l=null,c=null;try{let u=await ul(n,t,{headers:_j,signal:e.signal},o);l=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(Ej.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(kj.test(p)&&!vj.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await tk(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof bt||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;c=u}if(!(s===null||s.textLength<200)&&s!==null){let u=ff({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await bs(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>bs(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await bs(u.finalUrl,o);let p=await tk(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=ff({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 bt)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=c instanceof Error?c.message:`HTTP ${l??"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 ${l??"error"}).`)}var vj,kj,Ej,_j,rk=h(()=>{"use strict";wv();mf();bf();pe();vj=/(text\/html|application\/xhtml\+xml)/i,kj=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,Ej=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,_j={"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 xj(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(Aj,{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),Rj),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=Te(d);u&&(l=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function ok(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?xj({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 sk(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
215
215
|
|
|
216
216
|
(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(`
|
|
217
217
|
`).trimEnd()}var Aj,Rj,ik=h(()=>{"use strict";zt();Aj="https://api.exa.ai/search",Rj=10});function wl(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 rr=h(()=>{"use strict";vf()});function Dj(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 l;try{l=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.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,Ij)}let a=Pj;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,Mj)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Cf(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:Gt(t,e),truncated:!0}}function Fj(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=Dj(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,l=()=>{a.abort(s.reason)},c,d=()=>{let u=a.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(s.addEventListener("abort",l,{once:!0}),c=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${i.timeoutMs}ms`))},i.timeoutMs),i.url!==void 0){let p=await yf(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 ul(e,i.url,g,r)}catch(g){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:g instanceof bt?{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=Cf(f,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let p=await nk(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=Cf(Sv(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 bt)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),m=je(p)&&!wf(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${ws()}\`)`:"";return{content:`web_scrape markdown error: ${f}${m}`,isError:!0}}let u=ok({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:Oj,timeoutMs:i.timeoutMs,signal:a.signal}),f=Cf(sk(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{c!==void 0&&clearTimeout(c),s.removeEventListener("abort",l)}}}var Cj,Ij,Pj,Mj,Oj,ak,lk=h(()=>{"use strict";rk();ik();bf();un();mf();rr();Cj=3e4,Ij=12e4,Pj=1e5,Mj=1e6,Oj=10;ak=Fj()});import{existsSync as dk,mkdirSync as Lj,readFileSync as Nj,renameSync as $j,unlinkSync as Uj,writeFileSync as Bj}from"node:fs";import{dirname as ck,join as jj}from"node:path";import{randomBytes as Hj}from"node:crypto";function Kr(t){let e=t??Pu();if(!dk(e))return[];try{let n=Nj(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 Sl(t,e){let n=e??Pu();Lj(ck(n),{recursive:!0});let r=jj(ck(n),`.schedules.json.${process.pid}.${Hj(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{Bj(r,o,"utf-8"),$j(r,n)}catch(s){try{dk(r)&&Uj(r)}catch{}throw s}}function uk(t,e){let n=Kr(e),r=n.map(l=>l.id),o=Wj(t.name),s=Kj(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),Sl(n,e),a}function pk(t,e){let n=Kr(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(Sl(o,e),!0)}function fk(t,e){return Kr(e).find(n=>n.id===t)}function Wj(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function Kj(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}var mk=h(()=>{"use strict";j()});import{existsSync as Gj,readFileSync as qj}from"node:fs";import{join as zj}from"node:path";async function Ss(t,e,n){let r;try{let o=zj(ky("default"),"port");if(!Gj(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let s=qj(o,"utf-8").trim();if(r=parseInt(s,10),Number.isNaN(r))return{synced:!1,detail:"daemon-not-detected (invalid port file)"}}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let o=await fetch(`http://localhost:${r}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return o.ok?{synced:!0,detail:"synced"}:t==="POST"&&o.status===409?{synced:!0,detail:"already-registered"}:t==="DELETE"&&o.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${o.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}var If,gk=h(()=>{"use strict";j();If="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 Vj}from"node:fs";import{readFile as Jj}from"node:fs/promises";var hk,yk,bk,wk,Sk=h(()=>{"use strict";mk();j();gk();hk=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=uk({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 Ss("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 Ss("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:If}})}},yk=async(t,e)=>{let n=Kr();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})))}},bk=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=$i();if(!Vj(s))return{content:JSON.stringify([])};let i;try{let c=await Jj(s);i=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
|
|
@@ -239,7 +239,7 @@ ${lt(t,{headless:e,latched:n})}`,{cause:t})}var Mv,LB,NB,Pv,UB,vf=h(()=>{"use st
|
|
|
239
239
|
`),this.errored=!0)})}catch(n){process.stderr.write(`[afk] session-ledger: write threw for ${this.sessionId}: ${String(n)}
|
|
240
240
|
`),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())})}};eW=250});import{readdir as tW,stat as nW}from"node:fs/promises";import{join as rW}from"node:path";async function Zf(){let t=Co(),e;try{e=await tW(t)}catch(r){if(r.code==="ENOENT")return[];throw r}let n=[];for(let r of e){let o=rW(t,r,"trace.jsonl");try{let s=await nW(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 xE(){return(await Zf())[0]?.sessionId??null}var CE=h(()=>{"use strict";j()});import{existsSync as oW}from"node:fs";import{readFile as sW}from"node:fs/promises";async function em(t){if(!oW(t))return{content:"",truncated:!1};try{let e=await sW(t);if(e.length<=IE)return{content:e.toString("utf-8"),truncated:!1};let n=e.subarray(e.length-IE),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 IE,PE=h(()=>{"use strict";IE=2097152});import{existsSync as ME}from"node:fs";import{join as OE}from"node:path";function DE(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 uW(t){let e=[];for(let n of t.split(`
|
|
241
241
|
`))if(n.trim()!=="")try{let r=JSON.parse(n);DE(r)&&e.push(r)}catch{}return e}function pW(t){return typeof t!="number"?iW:Math.min(Math.max(1,Math.round(t)),aW)}function fW(t){return typeof t!="number"?cW:Math.min(Math.max(1,Math.round(t)),dW)}function mW(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 FE(t){let e=t.session==="latest"||!t.session?await xE():t.session;if(!e)return{sessionId:"(none)",events:[],totalInTrace:0,filtered:0};let n=OE(Et(e),"trace.jsonl");if(!ME(n))try{for await(let l of AE(e))if(l.kind==="meta"){if(l.traceLabel===null)return{sessionId:e,events:[],totalInTrace:0,filtered:0,note:`Session "${e}" ran with tracing disabled (traceLabel: null).`};if(typeof l.traceLabel=="string"&&l.traceLabel.length>0){let c=OE(Et(l.traceLabel),"trace.jsonl");ME(c)&&(n=c)}break}}catch{}let{content:r}=await em(n),o=uW(r),s={kinds:t.kinds?new Set(t.kinds):void 0,toolName:t.toolName,errorsOnly:t.errorsOnly},i=pW(t.limit),a=[];for(let l=o.length-1;l>=0;l--){let c=o[l];if(mW(c,s)&&(a.push(c),a.length>=i))break}return a.reverse(),{sessionId:e,events:a,totalInTrace:o.length,filtered:a.length}}async function LE(t){let e=fW(t.sessions),r=(await Zf()).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(),l=[],c=lW,d=[],u=0;for(let p of s){if(l.length>=c)break;let{content:f,truncated:m}=await em(p.tracePath);u++,m&&d.push(p.sessionId);for(let g of f.split(`
|
|
242
|
-
`)){if(l.length>=c)break;if(g.trim()!==""&&g.toLowerCase().includes(a))try{let y=JSON.parse(g);if(!DE(y)||i&&!i.has(y.kind))continue;l.push({sessionId:p.sessionId,event:y,matchLine:g.length>500?g.slice(0,500)+"\u2026":g})}catch{}}}return{query:t.query,sessionsAvailable:o,sessionsSearched:u,matches:l,...d.length>0?{truncatedSessions:d}:{}}}var iW,aW,lW,cW,dW,NE=h(()=>{"use strict";j();_s();CE();PE();iW=50,aW=200,lW=200,cW=20,dW=100});function $E(t){return!t||typeof t!="object"?null:t}function UE(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string")}var BE,jE,HE=h(()=>{"use strict";NE();BE=async t=>{let e=$E(t);if(!e)return{content:"Invalid input: expected object",isError:!0};let n=typeof e.session=="string"?e.session:void 0,r=UE(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 FE({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}}},jE=async t=>{let e=$E(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=UE(e.kinds),s=typeof e.since=="string"?e.since:void 0;try{let i=await LE({query:n,sessions:r,kinds:o,since:s});return{content:JSON.stringify(i)}}catch(i){return{content:`search_witness failed: ${i instanceof Error?i.message:String(i)}`,isError:!0}}}});function gW(t){return t.length<=WE?t:`${t.slice(0,WE)}\u2026(truncated)`}function hW(t){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${t.title??t.serverName}`,gW(t.message)];t.url!==void 0&&t.url!==""&&n.push(t.url),hs(n.join(`
|
|
242
|
+
`)){if(l.length>=c)break;if(g.trim()!==""&&g.toLowerCase().includes(a))try{let y=JSON.parse(g);if(!DE(y)||i&&!i.has(y.kind))continue;l.push({sessionId:p.sessionId,event:y,matchLine:g.length>500?g.slice(0,500)+"\u2026":g})}catch{}}}return{query:t.query,sessionsAvailable:o,sessionsSearched:u,sessionsScanned:u,matches:l,...d.length>0?{truncatedSessions:d}:{}}}var iW,aW,lW,cW,dW,NE=h(()=>{"use strict";j();_s();CE();PE();iW=50,aW=200,lW=200,cW=20,dW=100});function $E(t){return!t||typeof t!="object"?null:t}function UE(t){if(Array.isArray(t))return t.filter(e=>typeof e=="string")}var BE,jE,HE=h(()=>{"use strict";NE();BE=async t=>{let e=$E(t);if(!e)return{content:"Invalid input: expected object",isError:!0};let n=typeof e.session=="string"?e.session:void 0,r=UE(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 FE({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}}},jE=async t=>{let e=$E(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=UE(e.kinds),s=typeof e.since=="string"?e.since:void 0;try{let i=await LE({query:n,sessions:r,kinds:o,since:s});return{content:JSON.stringify(i)}}catch(i){return{content:`search_witness failed: ${i instanceof Error?i.message:String(i)}`,isError:!0}}}});function gW(t){return t.length<=WE?t:`${t.slice(0,WE)}\u2026(truncated)`}function hW(t){try{let n=[`\u{1F514} AFK needs you \u2014 stuck on: ${t.title??t.serverName}`,gW(t.message)];t.url!==void 0&&t.url!==""&&n.push(t.url),hs(n.join(`
|
|
243
243
|
`)).catch(()=>{})}catch{}}function KE(t,e){if(!(t===void 0||t===""))try{kp(t,e).catch(()=>{})}catch{}}var zr,WE,tm,Qe,sr=h(()=>{"use strict";ys();zn();zr={action:"decline"},WE=300;tm=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(zr);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(zr);return}if(!s){hW(e),r(zr);return}let i,a=new Promise(l=>{i=()=>l(zr),n.signal.addEventListener("abort",i,{once:!0})});try{try{n.onActive?.()}catch{}KE(n.sessionId,!0);let l=await Promise.race([s(e,n).catch(()=>zr),a]);r(l)}finally{KE(n.sessionId,!1),n.signal.removeEventListener("abort",i)}}finally{this.queueDepth-=1,r(zr)}}).catch(()=>{}),o}},Qe=new tm});var GE,qE=h(()=>{"use strict";sr();GE=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,l=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(l!==void 0&&(typeof l!="number"||!Number.isFinite(l)))return{content:"Invalid input: max must be a finite number",isError:!0};if(a!==void 0&&l!==void 0&&a>l)return{content:`Invalid input: min (${a}) must be \u2264 max (${l})`,isError:!0};let c=r.min_length,d=r.max_length;if(c!==void 0&&typeof c!="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((c!==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},...c!==void 0&&{minLength:c},...d!==void 0&&{maxLength:d},...a!==void 0&&{min:a},...l!==void 0&&{max:l},...r.allow_skip!==void 0&&{allowSkip:!!r.allow_skip},...r.allow_custom!==void 0&&{allowCustom:!!r.allow_custom}},p=await Qe.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 yW(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(!zE.includes(e.wait_for))return{error:`browser_open: "wait_for" must be one of ${zE.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 bW(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_open aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0,failureClass:$e(n)}}let o=yW(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;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(nr(),tr));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return je(c)?{content:lt(c),isError:!0}:{content:`browser_open failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.open({sessionId:s,url:o.url,waitFor:o.waitFor,screenshot:o.screenshot,timeoutMs:o.timeoutMs}),c=Date.now()-a;if("outcome"in l&&l.outcome==="blocked_by_policy")return Se(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:c}),{content:`browser_open blocked: ${l.reason}`,isError:!0,failureClass:"policy-refusal"};let d=l;return Se(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:d.url,status:"ok",durationMs:c,...d.screenshotPath!==null?{screenshotPath:d.screenshotPath}:{}}),{content:JSON.stringify(d,null,2)}}catch(l){let c=Date.now()-a,d=l instanceof Error?l.message:String(l);Se(r?.traceWriter,{tool:"browser_open",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:d,recoverable:!1}});let u=wl(l);return{content:`browser_open failed: ${d}`,isError:!0,...u?{failureClass:u}:{}}}}}var zE,VE,JE=h(()=>{"use strict";U();Bn();Y();rr();zE=["load","domcontentloaded","networkidle"];VE=bW()});function wW(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 SW(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_observe aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=wW(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;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(nr(),tr));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return je(c)?{content:lt(c),isError:!0}:{content:`browser_observe failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.observe({sessionId:s,screenshot:o.screenshot,includeHidden:o.includeHidden,maxElements:o.maxElements}),c=Date.now()-a;return Se(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:l.url,urlAfter:l.url,status:"ok",durationMs:c,...l.screenshotPath!==null?{screenshotPath:l.screenshotPath}:{}}),{content:JSON.stringify(l,null,2)}}catch(l){let c=Date.now()-a,d=l instanceof Error?l.message:String(l);return Se(r?.traceWriter,{tool:"browser_observe",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:d,recoverable:!1}}),{content:`browser_observe failed: ${d}`,isError:!0}}}}var YE,XE=h(()=>{"use strict";U();Y();rr();YE=SW()});function vW(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(!QE.includes(e.action))return{error:`browser_act: "action" must be one of ${QE.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"||!ZE.includes(o.kind))return{error:`browser_act: "target.kind" must be one of ${ZE.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 l;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'};l=e.timeout_ms}let c;if(e.screenshot!==void 0){if(typeof e.screenshot!="boolean")return{error:'browser_act: "screenshot" must be a boolean'};c=e.screenshot}return{action:n,target:s,value:a,timeoutMs:l,screenshot:c}}function kW(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(`
|
|
244
244
|
`)}function EW(t){return t.kind==="semantic"?{kind:"semantic",text:Nv(t.text),...t.role!==void 0?{role:t.role}:{}}:t.kind==="element_id"?{kind:"element_id",elementId:t.elementId}:{kind:"selector",selectorHash:Lv(t.selector)}}function _W(t={}){return async(e,n,r)=>{if(n.aborted){let c=n.reason;return{content:`browser_act aborted: ${c instanceof Error?c.message:String(c??"aborted")}`,isError:!0,failureClass:$e(n)}}let o=vW(e);if("error"in o)return{content:o.error,isError:!0};let s=EW(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;try{if(t.getBrowserProvider)a=await t.getBrowserProvider();else{let{getBrowserProvider:c}=await Promise.resolve().then(()=>(nr(),tr));a=await c()}}catch(c){let d=c instanceof Error?c.message:String(c);return je(d)?{content:lt(d),isError:!0}:{content:`browser_act failed to get provider: ${d}`,isError:!0}}let l=Date.now();try{let c=await a.act({sessionId:i,action:o.action,target:o.target,value:o.value,timeoutMs:o.timeoutMs,screenshot:o.screenshot}),d=Date.now()-l;if("outcome"in c){if(c.outcome==="ambiguous_target")return Se(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"ambiguous_target",durationMs:d}),{content:kW(c.query,c.candidates),isError:!0};if(c.outcome==="blocked_by_policy")return Se(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"blocked_by_policy",durationMs:d}),{content:`browser_act blocked: ${c.reason}`,isError:!0,failureClass:"policy-refusal"}}return Se(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:c.url,urlAfter:c.url,status:"ok",durationMs:d,...c.screenshotPath!==null?{screenshotPath:c.screenshotPath}:{}}),{content:JSON.stringify(c,null,2)}}catch(c){let d=Date.now()-l,u=c instanceof Error?c.message:String(c);Se(r?.traceWriter,{tool:"browser_act",action:o.action,toolUseId:r?.toolUseId??"",target:s,urlBefore:null,urlAfter:null,status:"error",durationMs:d,error:{reason:u,recoverable:!1}});let p=wl(c);return{content:`browser_act failed: ${u}`,isError:!0,...p?{failureClass:p}:{}}}}}var QE,ZE,e_,t_=h(()=>{"use strict";hl();U();Bn();Y();rr();QE=["click","fill","press","select","hover","scroll_to","wait_for"],ZE=["semantic","element_id","selector"];e_=_W()});function TW(t){if(typeof t.kind!="string"||!n_.includes(t.kind))return{error:`browser_screenshot: "target.kind" must be one of ${n_.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 AW(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=TW(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 RW(t={}){return async(e,n,r)=>{if(n.aborted){let l=n.reason;return{content:`browser_screenshot aborted: ${l instanceof Error?l.message:String(l??"aborted")}`,isError:!0}}let o=AW(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;try{if(t.getBrowserProvider)i=await t.getBrowserProvider();else{let{getBrowserProvider:l}=await Promise.resolve().then(()=>(nr(),tr));i=await l()}}catch(l){let c=l instanceof Error?l.message:String(l);return je(c)?{content:lt(c),isError:!0}:{content:`browser_screenshot failed to get provider: ${c}`,isError:!0}}let a=Date.now();try{let l=await i.screenshot({sessionId:s,target:o.target,fullPage:o.fullPage}),c=Date.now()-a,{dataBase64:d,mediaType:u,...p}=l;return Se(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:c,screenshotPath:p.path}),p.width>nm||p.height>nm?{content:JSON.stringify({...p,imageOmitted:`dimensions ${p.width}x${p.height}px exceed the ${nm}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(p,null,2),image:{mediaType:u,data:d}}}catch(l){let c=Date.now()-a,d=l instanceof Error?l.message:String(l);return Se(r?.traceWriter,{tool:"browser_screenshot",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:c,error:{reason:d,recoverable:!1}}),{content:`browser_screenshot failed: ${d}`,isError:!0}}}}var n_,nm,r_,o_=h(()=>{"use strict";U();Y();rr();n_=["semantic","element_id","selector"],nm=8e3;r_=RW()});function xW(t={}){return async(e,n,r)=>{if(n.aborted){let a=n.reason;return{content:`browser_close aborted: ${a instanceof Error?a.message:String(a??"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;try{if(t.getBrowserProvider)s=await t.getBrowserProvider();else{let{getBrowserProvider:a}=await Promise.resolve().then(()=>(nr(),tr));s=await a()}}catch(a){let l=a instanceof Error?a.message:String(a);return je(l)?{content:lt(l),isError:!0}:{content:`browser_close failed to get provider: ${l}`,isError:!0}}let i=Date.now();try{await s.close({sessionId:o});let a=Date.now()-i;return Se(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"ok",durationMs:a}),{content:"Browser session closed."}}catch(a){let l=Date.now()-i,c=a instanceof Error?a.message:String(a);return Se(r?.traceWriter,{tool:"browser_close",toolUseId:r?.toolUseId??"",urlBefore:null,urlAfter:null,status:"error",durationMs:l,error:{reason:c,recoverable:!1}}),{content:`browser_close failed: ${c}`,isError:!0}}}}var s_,i_=h(()=>{"use strict";U();Y();rr();s_=xW()});function $l(t,e){let n=t!==void 0?Qa(t,e):e!==void 0?Qa("default",e):Qw,r=e!==void 0?Vp(e):lS,o=e!==void 0?Jp(e):mS,s=e!==void 0?Kp(e):eS,i=e!==void 0?qp(e):rS,a=e!==void 0?zp(e):sS,l=e!==void 0?Yp(e):hS,c=Of(),d=Wk(e);return new Map([["bash",n],["read_file",s],["write_file",i],["edit_file",a],["glob",r],["grep",o],["list_directory",l],["send_telegram",gv],["web_scrape",ak],["create_schedule",hk],["list_schedules",yk],["get_schedule_history",bk],["cancel_schedule",wk],["read_witness",BE],["search_witness",jE],["worktree",d],["terminal_font_size",c],["config_get",wE],["config_set",SE],["ask_question",GE],["browser_open",VE],["browser_observe",YE],["browser_act",e_],["browser_screenshot",r_],["browser_close",s_]])}var rm=h(()=>{"use strict";Zw();tS();oS();iS();cS();gS();yS();hv();lk();Sk();_k();Kk();vE();HE();qE();JE();XE();t_();o_();i_()});function a_(t){return["The user has switched off plan mode. Writes are now permitted. Do two things, in order:","",`1. Save the plan. Write the plan you developed in this conversation to a new markdown file under \`${t}/\` \u2014 pick a short, descriptive kebab-case filename (e.g. \`${t}/refactor-auth-flow.md\`). Capture the full plan: the chosen approach, the concrete step-by-step changes, the risks named, and the alternatives considered. This is the durable record.`,"","2. Implement the plan. Work through the steps you just recorded, verifying as you go \u2014 run the project's lint/test gates where they apply. End in a terminal state: Done with evidence, Blocked with the exact unblock condition, or Asking one precise question."].join(`
|
|
245
245
|
`)}var l_=h(()=>{"use strict"});function IW(t){switch(t){case"bypassPermissions":return"Approve \u2014 implement now (restore bypass mode: no prompts, read/write any path)";case"acceptEdits":return"Approve \u2014 implement now (restore accept-edits mode: edits auto-approved)";case"dontAsk":case"auto":return"Approve \u2014 implement now (restore your previous mode: no approval prompts)";default:return"Approve \u2014 implement now (restore default mode: writes ask for confirmation, contained to the workspace)"}}function Bl(t){return async(e,n,r)=>{let o=t.getPrePlanMode()??"default",s=IW(o),a={serverName:"agent",origin:"agent",type:"choice",message:"Plan ready. How do you want to proceed? (Your plan is in the conversation above.)",choices:o==="bypassPermissions"?[s,om]:[s,CW,om]},l=await Qe.route(a,{signal:n,...r?.sessionId!==void 0?{sessionId:r.sessionId}:{}});if(l.action!=="accept")return{content:"Plan exit not confirmed (the user did not approve). Stay in plan mode \u2014 keep refining the plan; do not implement. Call exit_plan_mode again when ready."};let c=typeof l.content?.value=="string"?l.content.value:"";if(c.startsWith("Keep")||c===om)return{content:"User chose to keep planning. Stay in plan mode and refine the plan; do not implement. Call exit_plan_mode again when ready."};let d=c.includes("bypass")?"bypassPermissions":o,u=gy(r?.resolveBase??r?.cwd??process.cwd());return t.requestImplementSeed(a_(u),d),{content:`Plan approved (mode=${d}). The implementation instruction will follow as a new message \u2014 end your turn now.`}}}var dt,CW,om,Ul,ir=h(()=>{"use strict";sr();l_();j();dt="exit_plan_mode",CW="Approve \u2014 implement now (bypass mode: no prompts, read/write any path)",om="Keep planning";Ul={name:dt,category:"other",concurrencySafe:!1,description:`Signal that your plan is ready and present it to the user for approval. The user is shown a picker: approve and implement (you pick neither mode \u2014 the user does), or keep planning.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-afk",
|
|
3
|
-
"version": "5.114.
|
|
3
|
+
"version": "5.114.1",
|
|
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",
|