agent-afk 5.95.6 → 5.95.7
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 +7 -3
- package/dist/index.mjs +1 -1
- package/dist/telegram.mjs +1 -1
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -891,7 +891,7 @@ Retrying it verbatim will fail the same way. Fix the underlying cause, change th
|
|
|
891
891
|
|
|
892
892
|
`).trim()}function I7(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}async function a0(e,t){let{JSDOM:n,Readability:r,turndown:o}=await _7(),s=new n(e,{url:t}).window.document,a=(s.title??"").trim(),l=(()=>{try{let m=s.cloneNode(!0);return new r(m).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let m=s0(o.turndown(l.content)),f=(l.title??"").trim()||a,g=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:m,textLength:g,usedFallback:!1}}let c=s.body,d=c?.innerHTML??"",u=s0(o.turndown(d));return{title:a,markdown:u,textLength:I7(c),usedFallback:!0}}var fk,l0=T(()=>{"use strict";fk=null});function M7(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 c0(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function O7(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 d0(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??M7,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(!P7.has(u.status)||d===o)return u;let m=O7(u,s)??c0(d,i,s);B("[web/retryFetch] retrying",{url:t,attempt:d,status:u.status,waitMs:m}),await u.body?.cancel().catch(()=>{}),await a(m,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let m=c0(d,i,s);B("[web/retryFetch] retrying after error",{url:t,attempt:d,waitMs:m}),await a(m,l)}}throw c??new Error("retryFetch: exhausted without a result")}var P7,u0=T(()=>{"use strict";ue();P7=new Set([429,502,503,504])});import{BlockList as $7,isIP as hk}from"node:net";import{lookup as D7}from"node:dns/promises";import{Agent as F7}from"undici";function m0(){let e=k.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return e==="1"||e==="true"}function U7(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function gk(e){let t=hk(e);return t===0?!1:B7.check(e,t===4?"ipv4":"ipv6")}async function f0(e){return D7(e,{all:!0,verbatim:!0})}async function yk(e,t={}){if(t.allowPrivateHosts??m0())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=U7(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(hk(r)!==0)return gk(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let i=t.lookupFn??f0,s;try{s=await i(r)}catch{return{allowed:!0}}for(let a of s)if(gk(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Sd(e,t={}){let n=await yk(e,t);if(!n.allowed)throw new Mn(n.reason)}async function wf(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<=p0;s++){await Sd(i,o);let a={...n,redirect:"manual",...e===globalThis.fetch&&!(r.allowPrivateHosts??m0())?{dispatcher:j7}:{}},l=await d0(e,i,a,r.retry??{});if(!H7.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 Mn(`too many redirects (>${p0}) starting from ${t}`)}var L7,N7,B7,Mn,j7,p0,H7,bk=T(()=>{"use strict";K();u0();L7=[["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]],N7=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],B7=(()=>{let e=new $7;for(let[t,n]of L7)e.addSubnet(t,n,"ipv4");for(let[t,n]of N7)e.addSubnet(t,n,"ipv6");return e})(),Mn=class extends Error{constructor(t){super(t),this.name="EgressBlockedError"}};j7=new F7({connect:{lookup(e,t,n){f0(e).then(r=>{let o=r.find(s=>gk(s.address));if(o!==void 0){n(new Mn(`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,hk(i.address))},r=>n(r,"",0))}}});p0=20,H7=new Set([301,302,303,307,308])});import{readFileSync as W7}from"node:fs";import{join as K7}from"path";function G7(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function g0(e,t){return G7(t).test(e)}function J7(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(q7.has(t))return!0;if(z7.has(t))return!1}return!1}function h0(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function Y7(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 y0(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Mc(t),t}function V7(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function X7(e){try{return W7(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function Q7(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=y0(t.defaultProfile)),n}function b0(e){let t=e?.env??k,n=e?.readFileSync??X7,r=e?.surface??t.AGENT_SURFACE,o=J7(t.AFK_BROWSER_HEADLESS,r),i=h0(t.AFK_BROWSER_ALLOWED_DOMAINS),s=h0(t.AFK_BROWSER_BLOCKED_DOMAINS),a=V7(t.AFK_BROWSER_DOM_SNAPSHOTS),l=Y7(t.AFK_BROWSER_BACKEND),c=y0(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,m=u!==void 0&&u.trim()!==""?u.trim():K7(Rn(),"browser.json"),f=n(m);if(f===void 0)return d;let g;try{g=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${m}: ${String(y)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${m} must be a JSON object`);let h=Q7(d,g);return h.configPath=m,h}function Sf(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(g0(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>g0(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var q7,z7,vf=T(()=>{"use strict";K();G();q7=new Set(["daemon","subagent","telegram","afk"]),z7=new Set(["repl","interactive","cli"])});import{existsSync as Z7,readFileSync as eQ}from"node:fs";import{createRequire as tQ}from"node:module";import{dirname as nQ,join as rQ}from"node:path";function v0(e){if(typeof e=="string")return e;let t=[],n=e;for(let r=0;r<iQ&&n instanceof Error;r++)t.push(n.message),n=n.cause;return t.length>0?t.join(" | "):String(e)}function Lt(e){let t=v0(e);return S0.some(n=>t.includes(n))}function sQ(){try{let t=tQ(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(eQ(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=rQ(nQ(t),o);return Z7(i)?`node ${/\s/.test(i)?`"${i}"`:i} install chromium`:void 0}catch{return}}function vd(){return w0??=sQ()??oQ,w0}function wk(e){return e.includes("install chromium")}function ln(e,t){let n=v0(e),r=t?.latched===!0?` ${aQ}`:"";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: ${vd()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${vd()}). Or pick a different tool.${r}`}function kd(e,t,n=!1){if(!Lt(e))return e;let r=e instanceof Error?e.message:String(e);return new Error(`${r}
|
|
893
893
|
|
|
894
|
-
${ln(e,{headless:t,latched:n})}`,{cause:e})}var S0,oQ,iQ,w0,aQ,kf=T(()=>{"use strict";S0=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],oQ="pnpm exec playwright install chromium",iQ=4;aQ="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 $i from"node:fs";import Tf from"node:path";import{randomBytes as lQ}from"node:crypto";import{chromium as cQ}from"playwright";function dQ(){try{return"5.95.6"}catch{}try{let e=Tf.resolve(import.meta.dirname,"../../../package.json"),t=$i.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var uQ,Ef,k0=T(()=>{"use strict";kf();G();ue();uQ=dQ(),Ef=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=cQ.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=kd(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(m){throw i??m}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/${uQ}`}}loadStorageState(t){let n=Oc(t);try{if(!$i.existsSync(n))return;let r=JSON.parse($i.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=Oc(t);if(!$i.existsSync(r))return;let o=await n.storageState(),i=Tf.join(Tf.dirname(r),`.${Tf.basename(r)}.${process.pid}.${lQ(4).toString("hex")}.tmp`);$i.writeFileSync(i,JSON.stringify(o),{mode:384}),$i.chmodSync(i,384),$i.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 pQ}from"crypto";function T0(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&mQ.test(e.label))}function E0(e){return pQ("sha256").update(e,"utf8").digest("hex").slice(0,8)}function R0(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var mQ,Rf=T(()=>{"use strict";mQ=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as fQ}from"node:crypto";function gQ(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function hQ(e,t,n){return`el_${fQ("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function yQ(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function x0(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function C0(e,t){let n=e.role??"",r=e.name??"";A0.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])C0(i,t)}async function bQ(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},_0).catch(()=>[])}async function wQ(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,m=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},_0).catch(()=>[])}function SQ(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function xf(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=SQ(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=bQ(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,m,f,g,h]=await Promise.all([s,a,l,c,d]),y,b=!1;u!==null?(y=[],C0(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await wQ(e)).filter(N=>A0.has(N.role??"")));let w=new Map;for(let I of m){let N=x0(I.name),H=w.get(N);(!H||H.bbox.w===0&&I.bbox.w>0)&&w.set(N,I)}let S=y.map(I=>({ax:I,dom:w.get(x0(I.name??""))})),v=r?S:S.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);v.sort((I,N)=>{let H=I.dom?.bbox.y??0,L=N.dom?.bbox.y??0;if(H!==L)return H-L;let W=I.dom?.bbox.x??0,q=N.dom?.bbox.x??0;return W-q}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=v.slice(0,n).map((I,N)=>{let H=I.ax.role??"generic",L=I.ax.name??"",W=hQ(H,L,N),q=I.dom?.bbox??{x:0,y:0,w:0,h:0},P=I.dom?.type??null,D=null;I.ax.value!==void 0&&I.ax.value!==null&&(D=String(I.ax.value)),I.ax.checked!==void 0&&(D=String(I.ax.checked)),T0({role:H,kind:P})&&(D="[redacted]");let M={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(M.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(M.selected=I.ax.selected),I.ax.expanded!==void 0&&(M.expanded=I.ax.expanded);let O;I.dom?.testId?O=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(O=`#${I.dom.id}`);let U={id:W,role:H,label:gQ(L),kind:P,value:D,state:M,bbox:q};return O!==void 0&&(U.selector=O),U}),$="idle";try{let I=await e.evaluate(()=>document.readyState);I==="loading"?$="loading":I==="interactive"?$="navigating":$="idle"}catch{$="navigating"}$!=="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 _=yQ(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:$,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var A0,_0,I0=T(()=>{"use strict";Rf();A0=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);_0="a[href], button, input, select, textarea, [role], [tabindex], label"});async function P0(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 Sk(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>P0(e,i)))).filter(o=>o!==null)}async function vQ(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 vk(e,t,n){switch(t.kind){case"element_id":return kQ(e,t,n);case"selector":return TQ(e,t);case"semantic":return EQ(e,t)}}async function kQ(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 Sk(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function TQ(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 Sk(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function EQ(e,t){return t.role!==void 0?RQ(e,t.text,t.role):xQ(e,t.text,t)}async function RQ(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 Sk(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function xQ(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 vQ(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 m=u.slice(0,5),f=[];for(let h=0;h<m.length;h++){let y=m[h];if(y===void 0)continue;let b=await P0(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,S=0;for(let v=0;v<w.length;v++)S=S*31+w.charCodeAt(v)>>>0;f.push({...b,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var M0=T(()=>{"use strict"});async function kk(e,t,n,r){let o=e.url();if(o===n)return null;let i=Sf(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 O0=T(()=>{"use strict";vf()});import{randomBytes as AQ}from"crypto";import{mkdir as CQ,stat as _Q,writeFile as IQ}from"fs/promises";import{join as Tk}from"path";import{gzip as PQ}from"zlib";import{promisify as MQ}from"util";function OQ(e){return Tk(kr(e),"browser")}function $Q(e){return Tk(OQ(e),"screenshots")}function DQ(){return new Date().toISOString().replace(/[:.]/g,"-")}function FQ(){return AQ(3).toString("hex")}async function Ek(e,t,n){if(t.length>$0)throw new Error(`writeScreenshotSidecar: buffer exceeds ${$0} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=$Q(e);await CQ(r,{recursive:!0});let o=`${DQ()}-${FQ()}-${n}.png`,i=Tk(r,o);await IQ(i,t);let{size:s}=await _Q(i);return{path:i,bytes:s}}var IDe,$0,D0=T(()=>{"use strict";G();Rf();IDe=MQ(PQ);$0=5*1024*1024});var L0={};$p(L0,{PlaywrightProvider:()=>Rk});function F0(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 Rk,N0=T(()=>{"use strict";k0();I0();M0();vf();O0();D0();Rk=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Ef(t)}async open(t){let n=Sf(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 kk(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 xf(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 xf(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 vk(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${F0(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(y){c=y}else c=h}let u=await kk(r,this.config,i,()=>this.close({sessionId:n}));if(u!==null)return u;let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await xf(r,{observationCounter:o.observationCounter,screenshotPath:m,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 vk(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${F0(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 Ek(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 Ek(n,o,r);return i}catch{return null}}}});var Fi={};$p(Fi,{__resetBrowserRegistryForTests:()=>jQ,browserProviderActive:()=>BQ,closeBrowserProvider:()=>xk,getBrowserProvider:()=>NQ,peekBrowserProvider:()=>UQ});function B0(){Promise.resolve(xk()).then(()=>{process.exit(130)})}function U0(){Promise.resolve(xk()).then(()=>{process.exit(143)})}function j0(){ir=null}function LQ(){Af||(process.on("SIGINT",B0),process.on("SIGTERM",U0),process.on("exit",j0),Af=!0)}function H0(){Af&&(process.removeListener("SIGINT",B0),process.removeListener("SIGTERM",U0),process.removeListener("exit",j0),Af=!1)}async function NQ(e){return ir!==null?ir:(Di!==null||(Di=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(N0(),L0)),n=b0(e),r=new t(n);return LQ(),ir=r,Di=null,r})()),Di)}async function xk(){if(ir===null)return;let e=ir;ir=null,Di=null,H0(),await e.shutdown()}function BQ(){return ir!==null}function UQ(){return ir}function jQ(){ir=null,Di=null,H0()}var ir,Di,Af,Li=T(()=>{"use strict";vf();ir=null,Di=null,Af=!1});async function W0(e,t){try{return await a0(e,t)}catch(n){return B("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function zQ(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Li(),Fi));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function K0(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??zQ,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s=e,a=null,l=null;try{let d=await wf(n,e,{headers:qQ,signal:t.signal},o);a=d.status,s=d.url||e;let u=d.headers.get("content-type")??"";if(d.ok){if(GQ.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let m=await d.text();if(KQ.test(u)&&!WQ.test(u))return{title:"",markdown:m.trim(),finalUrl:s,usedRender:!1};if(i=await W0(m,s),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof Mn||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;l=d}if(!(i===null||i.textLength<200)&&i!==null)return{title:i.title,markdown:i.markdown,finalUrl:s,usedRender:!1};try{await Sd(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:m=>Sd(m,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await Sd(d.finalUrl,o);let u=await W0(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||u.textLength>=i.textLength)return{title:u.title,markdown:u.markdown,finalUrl:d.finalUrl,usedRender:!0}}catch(d){if(t.signal.aborted||d instanceof Mn)throw d;if(i===null){let u=d instanceof Error?d.message:String(d),m=l instanceof Error?l.message:`HTTP ${a??"error"}`,f=new Error(`web_scrape could not retrieve ${e}: fetch failed (${m}) and render failed (${u}).`);throw f.cause=d,f}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${a??"error"}).`)}var WQ,KQ,GQ,qQ,G0=T(()=>{"use strict";l0();bk();ue();WQ=/(text\/html|application\/xhtml\+xml)/i,KQ=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,GQ=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,qQ={"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 VQ(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(JQ,{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),YQ),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Ir(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 q0(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?VQ({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 z0(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
894
|
+
${ln(e,{headless:t,latched:n})}`,{cause:e})}var S0,oQ,iQ,w0,aQ,kf=T(()=>{"use strict";S0=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],oQ="pnpm exec playwright install chromium",iQ=4;aQ="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 $i from"node:fs";import Tf from"node:path";import{randomBytes as lQ}from"node:crypto";import{chromium as cQ}from"playwright";function dQ(){try{return"5.95.7"}catch{}try{let e=Tf.resolve(import.meta.dirname,"../../../package.json"),t=$i.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var uQ,Ef,k0=T(()=>{"use strict";kf();G();ue();uQ=dQ(),Ef=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=cQ.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=kd(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(m){throw i??m}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/${uQ}`}}loadStorageState(t){let n=Oc(t);try{if(!$i.existsSync(n))return;let r=JSON.parse($i.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=Oc(t);if(!$i.existsSync(r))return;let o=await n.storageState(),i=Tf.join(Tf.dirname(r),`.${Tf.basename(r)}.${process.pid}.${lQ(4).toString("hex")}.tmp`);$i.writeFileSync(i,JSON.stringify(o),{mode:384}),$i.chmodSync(i,384),$i.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 pQ}from"crypto";function T0(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&mQ.test(e.label))}function E0(e){return pQ("sha256").update(e,"utf8").digest("hex").slice(0,8)}function R0(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var mQ,Rf=T(()=>{"use strict";mQ=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as fQ}from"node:crypto";function gQ(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function hQ(e,t,n){return`el_${fQ("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function yQ(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function x0(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function C0(e,t){let n=e.role??"",r=e.name??"";A0.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])C0(i,t)}async function bQ(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},_0).catch(()=>[])}async function wQ(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,m=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};u!==void 0&&(g.value=u),f!==void 0&&(g.checked=f),o.push(g)}return o},_0).catch(()=>[])}function SQ(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function xf(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=SQ(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=bQ(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),d=e.title().catch(()=>""),[u,m,f,g,h]=await Promise.all([s,a,l,c,d]),y,b=!1;u!==null?(y=[],C0(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await wQ(e)).filter(N=>A0.has(N.role??"")));let w=new Map;for(let I of m){let N=x0(I.name),H=w.get(N);(!H||H.bbox.w===0&&I.bbox.w>0)&&w.set(N,I)}let S=y.map(I=>({ax:I,dom:w.get(x0(I.name??""))})),v=r?S:S.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);v.sort((I,N)=>{let H=I.dom?.bbox.y??0,L=N.dom?.bbox.y??0;if(H!==L)return H-L;let W=I.dom?.bbox.x??0,q=N.dom?.bbox.x??0;return W-q}),v.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=v.slice(0,n).map((I,N)=>{let H=I.ax.role??"generic",L=I.ax.name??"",W=hQ(H,L,N),q=I.dom?.bbox??{x:0,y:0,w:0,h:0},P=I.dom?.type??null,D=null;I.ax.value!==void 0&&I.ax.value!==null&&(D=String(I.ax.value)),I.ax.checked!==void 0&&(D=String(I.ax.checked)),T0({role:H,kind:P})&&(D="[redacted]");let M={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(M.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(M.selected=I.ax.selected),I.ax.expanded!==void 0&&(M.expanded=I.ax.expanded);let O;I.dom?.testId?O=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(O=`#${I.dom.id}`);let U={id:W,role:H,label:gQ(L),kind:P,value:D,state:M,bbox:q};return O!==void 0&&(U.selector=O),U}),$="idle";try{let I=await e.evaluate(()=>document.readyState);I==="loading"?$="loading":I==="interactive"?$="navigating":$="idle"}catch{$="navigating"}$!=="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 _=yQ(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:$,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var A0,_0,I0=T(()=>{"use strict";Rf();A0=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);_0="a[href], button, input, select, textarea, [role], [tabindex], label"});async function P0(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 Sk(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>P0(e,i)))).filter(o=>o!==null)}async function vQ(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 vk(e,t,n){switch(t.kind){case"element_id":return kQ(e,t,n);case"selector":return TQ(e,t);case"semantic":return EQ(e,t)}}async function kQ(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 Sk(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function TQ(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 Sk(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function EQ(e,t){return t.role!==void 0?RQ(e,t.text,t.role):xQ(e,t.text,t)}async function RQ(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 Sk(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function xQ(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 vQ(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 m=u.slice(0,5),f=[];for(let h=0;h<m.length;h++){let y=m[h];if(y===void 0)continue;let b=await P0(y.locator,y.index);if(b!==null){let w=`${b.role}:${b.label}:${h}`,S=0;for(let v=0;v<w.length;v++)S=S*31+w.charCodeAt(v)>>>0;f.push({...b,id:`el_${S.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var M0=T(()=>{"use strict"});async function kk(e,t,n,r){let o=e.url();if(o===n)return null;let i=Sf(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 O0=T(()=>{"use strict";vf()});import{randomBytes as AQ}from"crypto";import{mkdir as CQ,stat as _Q,writeFile as IQ}from"fs/promises";import{join as Tk}from"path";import{gzip as PQ}from"zlib";import{promisify as MQ}from"util";function OQ(e){return Tk(kr(e),"browser")}function $Q(e){return Tk(OQ(e),"screenshots")}function DQ(){return new Date().toISOString().replace(/[:.]/g,"-")}function FQ(){return AQ(3).toString("hex")}async function Ek(e,t,n){if(t.length>$0)throw new Error(`writeScreenshotSidecar: buffer exceeds ${$0} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=$Q(e);await CQ(r,{recursive:!0});let o=`${DQ()}-${FQ()}-${n}.png`,i=Tk(r,o);await IQ(i,t);let{size:s}=await _Q(i);return{path:i,bytes:s}}var IDe,$0,D0=T(()=>{"use strict";G();Rf();IDe=MQ(PQ);$0=5*1024*1024});var L0={};$p(L0,{PlaywrightProvider:()=>Rk});function F0(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 Rk,N0=T(()=>{"use strict";k0();I0();M0();vf();O0();D0();Rk=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Ef(t)}async open(t){let n=Sf(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 kk(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 xf(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 xf(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 vk(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${F0(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(y){c=y}else c=h}let u=await kk(r,this.config,i,()=>this.close({sessionId:n}));if(u!==null)return u;let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await xf(r,{observationCounter:o.observationCounter,screenshotPath:m,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 vk(r,t.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${F0(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 Ek(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 Ek(n,o,r);return i}catch{return null}}}});var Fi={};$p(Fi,{__resetBrowserRegistryForTests:()=>jQ,browserProviderActive:()=>BQ,closeBrowserProvider:()=>xk,getBrowserProvider:()=>NQ,peekBrowserProvider:()=>UQ});function B0(){Promise.resolve(xk()).then(()=>{process.exit(130)})}function U0(){Promise.resolve(xk()).then(()=>{process.exit(143)})}function j0(){ir=null}function LQ(){Af||(process.on("SIGINT",B0),process.on("SIGTERM",U0),process.on("exit",j0),Af=!0)}function H0(){Af&&(process.removeListener("SIGINT",B0),process.removeListener("SIGTERM",U0),process.removeListener("exit",j0),Af=!1)}async function NQ(e){return ir!==null?ir:(Di!==null||(Di=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(N0(),L0)),n=b0(e),r=new t(n);return LQ(),ir=r,Di=null,r})()),Di)}async function xk(){if(ir===null)return;let e=ir;ir=null,Di=null,H0(),await e.shutdown()}function BQ(){return ir!==null}function UQ(){return ir}function jQ(){ir=null,Di=null,H0()}var ir,Di,Af,Li=T(()=>{"use strict";vf();ir=null,Di=null,Af=!1});async function W0(e,t){try{return await a0(e,t)}catch(n){return B("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function zQ(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Li(),Fi));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function K0(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??zQ,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s=e,a=null,l=null;try{let d=await wf(n,e,{headers:qQ,signal:t.signal},o);a=d.status,s=d.url||e;let u=d.headers.get("content-type")??"";if(d.ok){if(GQ.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let m=await d.text();if(KQ.test(u)&&!WQ.test(u))return{title:"",markdown:m.trim(),finalUrl:s,usedRender:!1};if(i=await W0(m,s),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof Mn||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;l=d}if(!(i===null||i.textLength<200)&&i!==null)return{title:i.title,markdown:i.markdown,finalUrl:s,usedRender:!1};try{await Sd(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:m=>Sd(m,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await Sd(d.finalUrl,o);let u=await W0(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||u.textLength>=i.textLength)return{title:u.title,markdown:u.markdown,finalUrl:d.finalUrl,usedRender:!0}}catch(d){if(t.signal.aborted||d instanceof Mn)throw d;if(i===null){let u=d instanceof Error?d.message:String(d),m=l instanceof Error?l.message:`HTTP ${a??"error"}`,f=new Error(`web_scrape could not retrieve ${e}: fetch failed (${m}) and render failed (${u}).`);throw f.cause=d,f}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${a??"error"}).`)}var WQ,KQ,GQ,qQ,G0=T(()=>{"use strict";l0();bk();ue();WQ=/(text\/html|application\/xhtml\+xml)/i,KQ=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,GQ=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,qQ={"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 VQ(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(JQ,{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),YQ),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let d=await i.text(),u=Ir(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 q0(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?VQ({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 z0(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
895
895
|
|
|
896
896
|
(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(`
|
|
897
897
|
`).trimEnd()}var JQ,YQ,J0=T(()=>{"use strict";bo();JQ="https://api.exa.ai/search",YQ=10});function Cf(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 Ni=T(()=>{"use strict";kf()});function nZ(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=XQ;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,QQ)}let a=ZQ;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,eZ)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function Ak(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:_r(e,t),truncated:!0}}function rZ(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=nZ(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 m=await yk(s.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(!m.allowed)return{content:`web_scrape blocked: ${m.reason}`,isError:!0}}if(s.mode==="raw"){let m;try{let h={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};m=await wf(t,s.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:h instanceof Mn?{content:`web_scrape blocked: ${h.message}`,isError:!0}:{content:`web_scrape network error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}if(!m.ok)return{content:`web_scrape HTTP ${m.status} ${m.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let f;try{f=await m.text()}catch(h){return{content:`web_scrape read error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let g=Ak(f,s.maxBytes);return{content:g.content,...g.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let m=await K0(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:a.signal,...e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{}});if(m.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0};let f=Ak(m.markdown,s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(m){if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(m instanceof Mn)return{content:`web_scrape blocked: ${m.message}`,isError:!0};let f=m instanceof Error?m.message:String(m),g=Lt(m)&&!wk(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${vd()}\`)`:"";return{content:`web_scrape markdown error: ${f}${g}`,isError:!0}}let u=q0({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in u)return{content:u.error,isError:!0};try{let m=await u.search(s.query,{limit:tZ,timeoutMs:s.timeoutMs,signal:a.signal}),f=Ak(z0(s.query,m),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(m){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${m instanceof Error?m.message:String(m)}`,isError:!0}}}finally{c!==void 0&&clearTimeout(c),i.removeEventListener("abort",l)}}}var XQ,QQ,ZQ,eZ,tZ,Y0,V0=T(()=>{"use strict";G0();J0();bk();Ri();Ni();XQ=3e4,QQ=12e4,ZQ=1e5,eZ=1e6,tZ=10;Y0=rZ()});import{existsSync as Q0,mkdirSync as oZ,readFileSync as iZ,renameSync as sZ,unlinkSync as aZ,writeFileSync as lZ}from"node:fs";import{dirname as X0,join as cZ}from"node:path";import{randomBytes as dZ}from"node:crypto";function cn(e){let t=e??mS();if(!Q0(t))return[];try{let n=iZ(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 Bi(e,t){let n=t??mS();oZ(X0(n),{recursive:!0});let r=cZ(X0(n),`.schedules.json.${process.pid}.${dZ(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{lZ(r,o,"utf-8"),sZ(r,n)}catch(i){try{Q0(r)&&aZ(r)}catch{}throw i}}function _f(e,t){let n=cn(t),r=n.map(l=>l.id),o=uZ(e.name),i=pZ(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),Bi(n,t),a}function If(e,t){let n=cn(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(Bi(o,t),!0)}function Td(e,t){return cn(t).find(n=>n.id===e)}function uZ(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function pZ(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function Z0(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 Pf=T(()=>{"use strict";G()});import{existsSync as mZ,readFileSync as fZ}from"node:fs";import{join as gZ}from"node:path";async function On(e,t,n){let r;try{let o=gZ(Kp("default"),"port");if(!mZ(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=fZ(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 vo,Ck=T(()=>{"use strict";G();vo="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 hZ}from"node:fs";import{readFile as yZ}from"node:fs/promises";var eO,tO,nO,rO,oO=T(()=>{"use strict";Pf();G();Ck();eO=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=_f({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 On("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 On("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:vo}})}},tO=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})))}},nO=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=qn();if(!hZ(i))return{content:JSON.stringify([])};let s;try{let c=await yZ(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
|
|
@@ -1198,7 +1198,11 @@ ${n}`;Gce(this.serverName,n);let o=!1;try{let{pushIfConfigured:i}=await Promise.
|
|
|
1198
1198
|
Open this URL to authorize:
|
|
1199
1199
|
${n}
|
|
1200
1200
|
Status written to: ${Fc()}
|
|
1201
|
-
`)}_readSlot(){let t=this.backend.read();if(!t)return{};try{return JSON.parse(t).mcpOAuth?.[this.serverName]??{}}catch{return{}}}_updateSlot(t){let n=this.backend.read(),r={};if(n)try{r=JSON.parse(n)}catch{}let o=r.mcpOAuth??{},i=o[this.serverName]??{};o[this.serverName]=t(i),r.mcpOAuth=o,this.backend.write(JSON.stringify(r))}}});G();Qp();import{config as ZC}from"dotenv";import{Command as hAe}from"commander";K();import ES from"chalk";function k_(){let e=k.FORCE_COLOR;if(e&&e.length>0)return;let t=k.NO_COLOR;if(t&&t.length>0){ES.level=0;return}let n=k.CI;if(n&&n.length>0){ES.level=0;return}process.stdout.isTTY||(ES.level=0)}K();import V from"chalk";var T_={brand:V.hex("#E67E4C"),mint:V.hex("#5FE3A1"),goblin:V.hex("#9CB04A"),user:V.cyan,caret:V.hex("#7AA2F7"),tool:V.hex("#DCDCAA"),chrome:V.hex("#B0B8C2"),syntaxString:V.italic.hex("#8AB07A"),toolArg:V.dim.white,thinking:V.italic.hex("#9B8FB5"),success:V.green,error:V.red,warning:V.yellow,plan:V.hex("#9F7CE0"),bypass:V.bold.hex("#FF6AC1"),meta:V.blackBright,info:V.hex("#5BA8FF"),fileRef:V.hex("#56B5A8"),heading:V.bold.white,label:V.dim,dim:V.dim,bold:V.bold,italic:V.italic,inverse:V.inverse,diffAdd:V.green,diffRemove:V.red,diffHunk:V.blackBright},H4={brand:V.hex("#C0562A"),mint:V.hex("#1B9E63"),goblin:V.hex("#6B7D2A"),user:V.hex("#0E7490"),caret:V.hex("#3B5BDB"),tool:V.hex("#7A6E00"),chrome:V.hex("#5A6470"),syntaxString:V.italic.hex("#3F7A3F"),toolArg:V.hex("#6B7280"),thinking:V.italic.hex("#6D5B8E"),success:V.hex("#2E7D32"),error:V.hex("#C62828"),warning:V.hex("#B8860B"),plan:V.hex("#7048C0"),bypass:V.bold.hex("#D6297F"),meta:V.hex("#6B7280"),info:V.hex("#1D6FD6"),fileRef:V.hex("#0F766E"),heading:V.bold.hex("#1F2937"),label:V.dim,dim:V.dim,bold:V.bold,italic:V.italic,inverse:V.inverse,diffAdd:V.hex("#2E7D32"),diffRemove:V.hex("#C62828"),diffHunk:V.hex("#6B7280")},W4={brand:V.hex("#FF9B5A"),mint:V.hex("#B4FCC3"),goblin:V.hex("#A5AC55"),user:V.hex("#42CBC8"),caret:V.hex("#9DBEFC"),tool:V.hex("#F7D179"),chrome:V.hex("#D3CDC5"),syntaxString:V.italic.hex("#96C182"),toolArg:V.dim.hex("#D3CDC5"),thinking:V.italic.hex("#B49EC4"),success:V.hex("#8AE49E"),error:V.hex("#EF7F74"),warning:V.hex("#D7AA32"),plan:V.hex("#AE93DE"),bypass:V.bold.hex("#FFACE9"),meta:V.hex("#AAA19B"),info:V.hex("#739EF0"),fileRef:V.hex("#80E5E2"),heading:V.bold.hex("#F9F6F2"),label:V.dim,dim:V.dim,bold:V.bold,italic:V.italic,inverse:V.inverse,diffAdd:V.hex("#8AE49E"),diffRemove:V.hex("#EF7F74"),diffHunk:V.hex("#AAA19B")},E_=T_,R_=H4,x_=W4,p={...T_};import K4 from"chalk";import{createEmphasize as G4,common as q4}from"emphasize";function A_(){return{keyword:p.brand,built_in:p.brand,literal:p.brand,tag:p.brand,string:p.syntaxString,regexp:p.syntaxString,attr:p.syntaxString,comment:p.meta,meta:p.meta,quote:p.meta,number:p.warning,function:p.tool,title:p.tool,class:p.tool,"selector-tag":p.tool}}var C_=G4(q4),z4=2048,J4=512,Y4=32,zn=new Map;function __(){zn.clear()}function V4(e){let t=zn.get(e);if(t!==void 0)return zn.delete(e),zn.set(e,t),t}function X4(e,t){if(zn.has(e)&&zn.delete(e),zn.set(e,t),zn.size>Y4){let n=zn.keys().next().value;n!==void 0&&zn.delete(n)}}function I_(e,t){if(K4.level===0||e.length>z4)return e;let n=e.length<J4,r=n?`${t} ${e}`:"";if(n){let i=V4(r);if(i!==void 0)return i}let o;try{if(!t||!C_.registered(t))o=e;else{let i=C_.highlight(t,e,A_());o=typeof i?.value=="string"?i.value:e}}catch{o=e}return n&&X4(r,o),o}K();var P_={dark:E_,light:R_,umber:x_},Zp=Object.keys(P_),M_="dark";function O_(){return M_}function no(e){Object.assign(p,P_[e]),__(),M_=e}function Gs(e){if(e==null)return;let t=e.trim().toLowerCase();return t==="auto"||Zp.includes(t)?t:void 0}function Q4(){let e=k.COLORFGBG;if(!e)return"dark";let t=e.split(";"),n=t[t.length-1]?.trim();if(!n)return"dark";let r=Number.parseInt(n,10);return Number.isInteger(r)&&(r===7||r>=9)?"light":"dark"}function ro(e){return e==="auto"?Q4():e!==void 0?e:"dark"}function em(e){let t=Gs(e);if(t!==void 0)return t;throw new Error(`Invalid --theme value: ${e}. Expected ${[...Zp,"auto"].join("|")}`)}function tm(e,t){if(e!==void 0)return e;let n=Gs(k.AFK_THEME);return n!==void 0?n:t}import cde from"ora";Fe();function $_(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("rate limit")||t.toLowerCase().includes("too many requests")}function D_(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("network")||t.toLowerCase().includes("connect")||t.toLowerCase().includes("timeout")}function zs(e){if(e instanceof oo)return{kind:"budget_exceeded",userMessage:`Session stopped: cost ceiling reached ($${e.runningCostUsd.toFixed(4)} of $${e.maxBudgetUsd.toFixed(4)} limit).`,exitCode:1,raw:e};if(e instanceof rm)return{kind:"unsupported_config",userMessage:`The "${e.provider}" provider does not support this configuration option.`,hint:`Option "${e.field}" is not available for provider "${e.provider}". Switch to a compatible provider or remove the option.`,exitCode:1,raw:e};if(e instanceof Re)return{kind:"hook_blocked",userMessage:`A hook blocked the operation (event: ${e.event}).`,...e.reason!==void 0?{hint:e.reason}:{},exitCode:1,raw:e};if(e instanceof ht){let i=Math.round(e.timeoutMs/1e3);return{kind:"timeout",userMessage:`The operation timed out after ${i} second${i!==1?"s":""}.`,hint:`Timeout: ${e.timeoutMs}ms (${i}s). Increase the timeout or retry.`,exitCode:124,raw:e}}let t=e,n=e instanceof Error?e.message:String(e),r=n.toLowerCase();return t.status===401||e instanceof Error&&e.name==="AuthenticationError"?{kind:"auth",userMessage:"Authentication failed. Check that your API key is valid and has not expired.",hint:"Verify the ANTHROPIC_API_KEY environment variable or run `afk login`.",exitCode:1,raw:e}:t.status===429||$_(e)?{kind:"rate_limit",userMessage:"Anthropic rate limit reached. The request was rejected (HTTP 429).",hint:"Wait a moment and retry, or reduce the request frequency.",exitCode:1,raw:e}:t.status===529||t.status===503?{kind:"overloaded",userMessage:`Anthropic API is temporarily overloaded (HTTP ${t.status}). All retry attempts were exhausted.`,hint:"Wait a minute and try again, or switch to a less loaded model (e.g. sonnet).",exitCode:1,raw:e}:n==="Not in a git repository."||r.includes("not in a git repository")?{kind:"not_git_repo",userMessage:"This command must be run from inside a git repository.",hint:"Run `git init` to initialise a repository, or change to a directory that is already a git repo.",exitCode:1,raw:e}:D_(e)||r.includes("econnrefused")||r.includes("etimedout")?{kind:"network",userMessage:"Network error: unable to reach the API endpoint.",hint:"Check your internet connection and try again.",exitCode:1,raw:e}:{kind:"unknown",userMessage:(e instanceof Error?e.message:String(e))||"An unexpected error occurred.",exitCode:1,raw:e}}import Z4 from"string-width";var RS=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,F_=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function $e(e){return e.replace(RS,"")}function ee(e){return Z4(e)}function Js(e){return e.length===0?[]:F_?Array.from(F_.segment(e),t=>t.segment):Array.from(e)}function e8(e){let t=[],n=0,r;for(RS.lastIndex=0;(r=RS.exec(e))!==null;){if(r.index>n)for(let o of Js(e.slice(n,r.index)))t.push({type:"text",value:o});t.push({type:"ansi",value:r[0]}),n=r.index+r[0].length}if(n<e.length)for(let o of Js(e.slice(n)))t.push({type:"text",value:o});return t}function tt(e,t){let n=Math.max(0,t-ee(e));return e+" ".repeat(n)}function t8(e,t){let n=Math.max(0,t-ee(e));return" ".repeat(n)+e}function xS(e,t,n="left"){let r=Math.max(0,t-ee(e));if(r===0)return e;if(n==="right")return t8(e,t);if(n==="center"){let o=Math.floor(r/2);return" ".repeat(o)+e+" ".repeat(r-o)}return tt(e,t)}var n8=/^\x1b\]8;[^;\x07\x1b]*;(.*?)(?:\x07|\x1b\\)$/s,r8="\x1B]8;;\x1B\\";function ce(e,t,n="\u2026"){if(t<=0)return"";if(ee(e)<=t)return e;let r=ee(n),o=Math.max(0,t-r),i=0,s="",a=!1,l=!1;for(let c of e8(e)){if(c.type==="ansi"){s+=c.value,a=!0;let u=n8.exec(c.value);u&&(l=(u[1]??"").length>0);continue}let d=i+ee(c.value);if(d>o)break;s+=c.value,i=d}return s+n+(l?r8:"")+(a?"\x1B[0m":"")}function L_(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function AS(e,t){let n=L_(t,e.length);if(n===0||e.length===0)return 0;let r=0;for(let o of Js(e)){let i=r+o.length;if(i>=n)return r;r=i}return r}function ci(e,t){let n=L_(t,e.length);if(n>=e.length||e.length===0)return e.length;let r=0;for(let o of Js(e)){let i=r+o.length;if(r>=n||n>r&&n<i)return i;r=i}return e.length}function ne(){let e=process.stdout.columns;return typeof e=="number"&&e>0?e:80}var om=new Set,im=new Set,Ys=!1,di=null;function o8(){for(let e of om)try{e()}catch{}}function i8(){for(let e of im)try{e()}catch{}}function s8(){di!==null&&clearTimeout(di),di=setTimeout(()=>{di=null,o8()},150)}function CS(){i8(),s8()}function a8(e){return om.add(e),Ys||(process.stdout.on("resize",CS),Ys=!0),()=>{om.delete(e),N_()}}function l8(e){return im.add(e),Ys||(process.stdout.on("resize",CS),Ys=!0),()=>{im.delete(e),N_()}}function N_(){om.size===0&&im.size===0&&(Ys&&(process.stdout.off("resize",CS),Ys=!1),di!==null&&(clearTimeout(di),di=null))}var Le={subscribe:a8,subscribeImmediate:l8};import B_ from"wrap-ansi";function we(e,t,n={}){if(!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY)return e;let r=Math.floor(t);return B_(e,r,{hard:n.breakLongWords??!1,trim:!1,wordWrap:!0})}function ui(e,t){return!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY?e:B_(e,Math.floor(t),{hard:!0,trim:!1,wordWrap:!1})}function Zt(){return Math.max(22,ne()-6)}function Tr(e,t){return ce(e,t)}function c8(e){switch(e){case"ok":return p.success("\u25CF");case"warn":return p.warning("\u25CF");case"error":return p.error("\u25CF");case"info":return p.info("\u25C6")}}function U_(e,t){let o=t.reduce((S,v)=>Math.max(S,ee(v.label)),0),i=t.reduce((S,v)=>Math.max(S,ee(v.value)),0),s=o+4+2+i,a=Math.min(ne()-4,100),l=Math.max(44,ee(e),s,a);l=Math.min(l,Zt());let c=l+4,d=p.dim,u=d("\u256D"+"\u2500".repeat(c)+"\u256E"),m=d("\u251C"+"\u2500".repeat(c)+"\u2524"),f=d("\u2570"+"\u2500".repeat(c)+"\u256F"),g=d("\u2502"),y=we(e,l).split(`
|
|
1201
|
+
`)}_readSlot(){let t=this.backend.read();if(!t)return{};try{return JSON.parse(t).mcpOAuth?.[this.serverName]??{}}catch{return{}}}_updateSlot(t){let n=this.backend.read(),r={};if(n)try{r=JSON.parse(n)}catch{}let o=r.mcpOAuth??{},i=o[this.serverName]??{};o[this.serverName]=t(i),r.mcpOAuth=o,this.backend.write(JSON.stringify(r))}}});G();Qp();import{config as ZC}from"dotenv";import{Command as hAe}from"commander";K();import ES from"chalk";function k_(){let e=k.FORCE_COLOR;if(e&&e.length>0)return;let t=k.NO_COLOR;if(t&&t.length>0){ES.level=0;return}let n=k.CI;if(n&&n.length>0){ES.level=0;return}process.stdout.isTTY||(ES.level=0)}K();import V from"chalk";var T_={brand:V.hex("#E67E4C"),mint:V.hex("#5FE3A1"),goblin:V.hex("#9CB04A"),user:V.cyan,caret:V.hex("#7AA2F7"),tool:V.hex("#DCDCAA"),chrome:V.hex("#B0B8C2"),syntaxString:V.italic.hex("#8AB07A"),toolArg:V.dim.white,thinking:V.italic.hex("#9B8FB5"),success:V.green,error:V.red,warning:V.yellow,plan:V.hex("#9F7CE0"),bypass:V.bold.hex("#FF6AC1"),meta:V.blackBright,info:V.hex("#5BA8FF"),fileRef:V.hex("#56B5A8"),heading:V.bold.white,label:V.dim,dim:V.dim,bold:V.bold,italic:V.italic,inverse:V.inverse,diffAdd:V.green,diffRemove:V.red,diffHunk:V.blackBright},H4={brand:V.hex("#C0562A"),mint:V.hex("#1B9E63"),goblin:V.hex("#6B7D2A"),user:V.hex("#0E7490"),caret:V.hex("#3B5BDB"),tool:V.hex("#7A6E00"),chrome:V.hex("#5A6470"),syntaxString:V.italic.hex("#3F7A3F"),toolArg:V.hex("#6B7280"),thinking:V.italic.hex("#6D5B8E"),success:V.hex("#2E7D32"),error:V.hex("#C62828"),warning:V.hex("#B8860B"),plan:V.hex("#7048C0"),bypass:V.bold.hex("#D6297F"),meta:V.hex("#6B7280"),info:V.hex("#1D6FD6"),fileRef:V.hex("#0F766E"),heading:V.bold.hex("#1F2937"),label:V.dim,dim:V.dim,bold:V.bold,italic:V.italic,inverse:V.inverse,diffAdd:V.hex("#2E7D32"),diffRemove:V.hex("#C62828"),diffHunk:V.hex("#6B7280")},W4={brand:V.hex("#FF9B5A"),mint:V.hex("#B4FCC3"),goblin:V.hex("#A5AC55"),user:V.hex("#42CBC8"),caret:V.hex("#9DBEFC"),tool:V.hex("#F7D179"),chrome:V.hex("#D3CDC5"),syntaxString:V.italic.hex("#96C182"),toolArg:V.dim.hex("#D3CDC5"),thinking:V.italic.hex("#B49EC4"),success:V.hex("#8AE49E"),error:V.hex("#EF7F74"),warning:V.hex("#D7AA32"),plan:V.hex("#AE93DE"),bypass:V.bold.hex("#FFACE9"),meta:V.hex("#AAA19B"),info:V.hex("#739EF0"),fileRef:V.hex("#80E5E2"),heading:V.bold.hex("#F9F6F2"),label:V.dim,dim:V.dim,bold:V.bold,italic:V.italic,inverse:V.inverse,diffAdd:V.hex("#8AE49E"),diffRemove:V.hex("#EF7F74"),diffHunk:V.hex("#AAA19B")},E_=T_,R_=H4,x_=W4,p={...T_};import K4 from"chalk";import{createEmphasize as G4,common as q4}from"emphasize";function A_(){return{keyword:p.brand,built_in:p.brand,literal:p.brand,tag:p.brand,string:p.syntaxString,regexp:p.syntaxString,attr:p.syntaxString,comment:p.meta,meta:p.meta,quote:p.meta,number:p.warning,function:p.tool,title:p.tool,class:p.tool,"selector-tag":p.tool}}var C_=G4(q4),z4=2048,J4=512,Y4=32,zn=new Map;function __(){zn.clear()}function V4(e){let t=zn.get(e);if(t!==void 0)return zn.delete(e),zn.set(e,t),t}function X4(e,t){if(zn.has(e)&&zn.delete(e),zn.set(e,t),zn.size>Y4){let n=zn.keys().next().value;n!==void 0&&zn.delete(n)}}function I_(e,t){if(K4.level===0||e.length>z4)return e;let n=e.length<J4,r=n?`${t} ${e}`:"";if(n){let i=V4(r);if(i!==void 0)return i}let o;try{if(!t||!C_.registered(t))o=e;else{let i=C_.highlight(t,e,A_());o=typeof i?.value=="string"?i.value:e}}catch{o=e}return n&&X4(r,o),o}K();var P_={dark:E_,light:R_,umber:x_},Zp=Object.keys(P_),M_="dark";function O_(){return M_}function no(e){Object.assign(p,P_[e]),__(),M_=e}function Gs(e){if(e==null)return;let t=e.trim().toLowerCase();return t==="auto"||Zp.includes(t)?t:void 0}function Q4(){let e=k.COLORFGBG;if(!e)return"dark";let t=e.split(";"),n=t[t.length-1]?.trim();if(!n)return"dark";let r=Number.parseInt(n,10);return Number.isInteger(r)&&(r===7||r>=9)?"light":"dark"}function ro(e){return e==="auto"?Q4():e!==void 0?e:"dark"}function em(e){let t=Gs(e);if(t!==void 0)return t;throw new Error(`Invalid --theme value: ${e}. Expected ${[...Zp,"auto"].join("|")}`)}function tm(e,t){if(e!==void 0)return e;let n=Gs(k.AFK_THEME);return n!==void 0?n:t}import cde from"ora";Fe();function $_(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("rate limit")||t.toLowerCase().includes("too many requests")}function D_(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("network")||t.toLowerCase().includes("connect")||t.toLowerCase().includes("timeout")}function zs(e){if(e instanceof oo)return{kind:"budget_exceeded",userMessage:`Session stopped: cost ceiling reached ($${e.runningCostUsd.toFixed(4)} of $${e.maxBudgetUsd.toFixed(4)} limit).`,exitCode:1,raw:e};if(e instanceof rm)return{kind:"unsupported_config",userMessage:`The "${e.provider}" provider does not support this configuration option.`,hint:`Option "${e.field}" is not available for provider "${e.provider}". Switch to a compatible provider or remove the option.`,exitCode:1,raw:e};if(e instanceof Re)return{kind:"hook_blocked",userMessage:`A hook blocked the operation (event: ${e.event}).`,...e.reason!==void 0?{hint:e.reason}:{},exitCode:1,raw:e};if(e instanceof ht){let i=Math.round(e.timeoutMs/1e3);return{kind:"timeout",userMessage:`The operation timed out after ${i} second${i!==1?"s":""}.`,hint:`Timeout: ${e.timeoutMs}ms (${i}s). Increase the timeout or retry.`,exitCode:124,raw:e}}let t=e,n=e instanceof Error?e.message:String(e),r=n.toLowerCase();return t.status===401||e instanceof Error&&e.name==="AuthenticationError"?{kind:"auth",userMessage:"Authentication failed. Check that your API key is valid and has not expired.",hint:"Verify the ANTHROPIC_API_KEY environment variable or run `afk login`.",exitCode:1,raw:e}:t.status===429||$_(e)?{kind:"rate_limit",userMessage:"Anthropic rate limit reached. The request was rejected (HTTP 429).",hint:"Wait a moment and retry, or reduce the request frequency.",exitCode:1,raw:e}:t.status===529||t.status===503?{kind:"overloaded",userMessage:`Anthropic API is temporarily overloaded (HTTP ${t.status}). All retry attempts were exhausted.`,hint:"Wait a minute and try again, or switch to a less loaded model (e.g. sonnet).",exitCode:1,raw:e}:n==="Not in a git repository."||r.includes("not in a git repository")?{kind:"not_git_repo",userMessage:"This command must be run from inside a git repository.",hint:"Run `git init` to initialise a repository, or change to a directory that is already a git repo.",exitCode:1,raw:e}:D_(e)||r.includes("econnrefused")||r.includes("etimedout")?{kind:"network",userMessage:"Network error: unable to reach the API endpoint.",hint:"Check your internet connection and try again.",exitCode:1,raw:e}:{kind:"unknown",userMessage:(e instanceof Error?e.message:String(e))||"An unexpected error occurred.",exitCode:1,raw:e}}import Z4 from"string-width";var RS=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,F_=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function $e(e){return e.replace(RS,"")}function ee(e){return Z4(e)}function Js(e){return e.length===0?[]:F_?Array.from(F_.segment(e),t=>t.segment):Array.from(e)}function e8(e){let t=[],n=0,r;for(RS.lastIndex=0;(r=RS.exec(e))!==null;){if(r.index>n)for(let o of Js(e.slice(n,r.index)))t.push({type:"text",value:o});t.push({type:"ansi",value:r[0]}),n=r.index+r[0].length}if(n<e.length)for(let o of Js(e.slice(n)))t.push({type:"text",value:o});return t}function tt(e,t){let n=Math.max(0,t-ee(e));return e+" ".repeat(n)}function t8(e,t){let n=Math.max(0,t-ee(e));return" ".repeat(n)+e}function xS(e,t,n="left"){let r=Math.max(0,t-ee(e));if(r===0)return e;if(n==="right")return t8(e,t);if(n==="center"){let o=Math.floor(r/2);return" ".repeat(o)+e+" ".repeat(r-o)}return tt(e,t)}var n8=/^\x1b\]8;[^;\x07\x1b]*;(.*?)(?:\x07|\x1b\\)$/s,r8="\x1B]8;;\x1B\\";function ce(e,t,n="\u2026"){if(t<=0)return"";if(ee(e)<=t)return e;let r=ee(n),o=Math.max(0,t-r),i=0,s="",a=!1,l=!1;for(let c of e8(e)){if(c.type==="ansi"){s+=c.value,a=!0;let u=n8.exec(c.value);u&&(l=(u[1]??"").length>0);continue}let d=i+ee(c.value);if(d>o)break;s+=c.value,i=d}return s+n+(l?r8:"")+(a?"\x1B[0m":"")}function L_(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function AS(e,t){let n=L_(t,e.length);if(n===0||e.length===0)return 0;let r=0;for(let o of Js(e)){let i=r+o.length;if(i>=n)return r;r=i}return r}function ci(e,t){let n=L_(t,e.length);if(n>=e.length||e.length===0)return e.length;let r=0;for(let o of Js(e)){let i=r+o.length;if(r>=n||n>r&&n<i)return i;r=i}return e.length}function ne(){let e=process.stdout.columns;return typeof e=="number"&&e>0?e:80}var om=new Set,im=new Set,Ys=!1,di=null;function o8(){for(let e of om)try{e()}catch{}}function i8(){for(let e of im)try{e()}catch{}}function s8(){di!==null&&clearTimeout(di),di=setTimeout(()=>{di=null,o8()},150)}function CS(){i8(),s8()}function a8(e){return om.add(e),Ys||(process.stdout.on("resize",CS),Ys=!0),()=>{om.delete(e),N_()}}function l8(e){return im.add(e),Ys||(process.stdout.on("resize",CS),Ys=!0),()=>{im.delete(e),N_()}}function N_(){om.size===0&&im.size===0&&(Ys&&(process.stdout.off("resize",CS),Ys=!1),di!==null&&(clearTimeout(di),di=null))}var Le={subscribe:a8,subscribeImmediate:l8};import B_ from"wrap-ansi";function we(e,t,n={}){if(!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY)return e;let r=Math.floor(t);return e.replaceAll(`\r
|
|
1202
|
+
`,`
|
|
1203
|
+
`).split(`
|
|
1204
|
+
`).map(o=>{let i=Array.from({length:256},(a,l)=>String.fromCodePoint(57344+l)).find(a=>!o.includes(a)),s=i?o.replace(/^((?:\x1B\[[0-9;]*m)*)( +)/,(a,l,c)=>l+i.repeat(c.length)):o;return B_(s,r,{hard:n.breakLongWords??!1,trim:!0,wordWrap:!0}).replaceAll(i??"\uE000"," ")}).join(`
|
|
1205
|
+
`)}function ui(e,t){return!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY?e:B_(e,Math.floor(t),{hard:!0,trim:!1,wordWrap:!1})}function Zt(){return Math.max(22,ne()-6)}function Tr(e,t){return ce(e,t)}function c8(e){switch(e){case"ok":return p.success("\u25CF");case"warn":return p.warning("\u25CF");case"error":return p.error("\u25CF");case"info":return p.info("\u25C6")}}function U_(e,t){let o=t.reduce((S,v)=>Math.max(S,ee(v.label)),0),i=t.reduce((S,v)=>Math.max(S,ee(v.value)),0),s=o+4+2+i,a=Math.min(ne()-4,100),l=Math.max(44,ee(e),s,a);l=Math.min(l,Zt());let c=l+4,d=p.dim,u=d("\u256D"+"\u2500".repeat(c)+"\u256E"),m=d("\u251C"+"\u2500".repeat(c)+"\u2524"),f=d("\u2570"+"\u2500".repeat(c)+"\u256F"),g=d("\u2502"),y=we(e,l).split(`
|
|
1202
1206
|
`).map(S=>g+" "+tt(S,l)+" "+g),b=Math.max(1,l-o-4-2),w=t.map(S=>{let v=S.kind?c8(S.kind)+" ":" ",E=p.dim(tt(Tr(S.label,o),o)),A=" ".repeat(4),$=Tr(S.value,b),_=tt($,b),x=E+A+v+_;return g+" "+x+" "+g});return[u,...y,m,...w,f].join(`
|
|
1203
1207
|
`)}import{sep as OS}from"node:path";import g8 from"chalk";K();K();import Vs from"chalk";var sm={".":null,D:[74,92,36],M:[139,166,63],L:[178,197,88],Y:[245,213,71],K:[13,18,9],W:[238,238,222],X:[42,42,26],B:[60,38,20],R:[200,60,40]},_S=["..............BBB..........","............BBBBB..........","..........BBBBBBB..........",".........BBBBBBBBB.........",".......BBBBBBBBBBBB........","......BBBBBBBBBBBBBB.......",".....BBBBBBBBBBBBBBBBB.....",".....KYYYYYYYYYYYYYYYK.....",".....KMMMMMMMMMMMMMMMK.....",".....KMMMMMMMMMMMMMMMK.....","....DKMMMMMMMMMMMMMMMKD....","...DDKMMMMMMMMMMMMMMMKDD...",".DDDDKMKKKKKMMMKKKKKMKDDDD.","DDDDDKMMKKKMMMMMKKKMMKDDDDD",".DDDDKMMYYYMMMMMYYYMMKDDDD.","..DDDKMMYKYMMLMMYKYMMKDDD..",".....KMMDDDMMLMMDDDMMK.....",".....KMDMMMMDLDMMMMDMK.....",".....KMDMMMMDDDMMMMDMK.....",".....KMMMMMMMMMMMMMMMK.....",".....KMMKKMMMMMMMKKMMK.....",".....KMMMKKKKKKKKKMMMK.....",".....KMMMMKKKKKKKMMMMK.....","......KMMMMMMMMMMMMMK......","........KMMMMMMMMMK........","..........KMMMMMK.........."],IS=27,j_=13,d8={"11,11":{char:"\u25BC",fg:"W",bg:"K"}};function u8(e){let t=sm[e.fg]??null,n=sm[e.bg]??null;return t&&n?Vs.bgRgb(n[0],n[1],n[2]).rgb(t[0],t[1],t[2])(e.char):t?Vs.rgb(t[0],t[1],t[2])(e.char):n?Vs.bgRgb(n[0],n[1],n[2])(e.char):e.char}function p8(e,t,n,r){if(e.length!==t.length)throw new Error(`pixel row width mismatch: top=${e.length}, bot=${t.length}`);let o="";for(let i=0;i<e.length;i++){let s=r[`${n},${i}`];if(s){o+=u8(s);continue}let a=sm[e[i]??"."]??null,l=sm[t[i]??"."]??null;!a&&!l?o+=" ":a&&!l?o+=Vs.rgb(a[0],a[1],a[2])("\u2580"):!a&&l?o+=Vs.rgb(l[0],l[1],l[2])("\u2584"):a&&l&&(o+=Vs.bgRgb(l[0],l[1],l[2]).rgb(a[0],a[1],a[2])("\u2580"))}return o}function PS(e,t={}){if(e.length%2!==0)throw new Error(`pixel grid must have an even row count, got ${e.length}`);let n=[];for(let r=0;r<e.length/2;r++){let o=e[r*2]??"",i=e[r*2+1]??"";n.push(p8(o,i,r,t))}return n}function m8(){if(_S.length!==j_*2)throw new Error(`GOBLIN_GRID has ${_S.length} pixel rows but MASCOT_HEIGHT*2 = ${j_*2}`);return PS(_S,d8)}function H_(e="idle"){return k.AFK_BANNER_PLAIN==="1"?[]:m8()}function Xs(){return k.AFK_BANNER_PLAIN==="1"}var f8={A:[" \u2588\u2588 ","\u2588 \u2588","\u2588\u2588\u2588\u2588","\u2588 \u2588","\u2588 \u2588"],G:[" \u2588\u2588\u2588","\u2588 ","\u2588 \u2588\u2588","\u2588 \u2588"," \u2588\u2588\u2588"],E:["\u2588\u2588\u2588\u2588","\u2588 ","\u2588\u2588\u2588 ","\u2588 ","\u2588\u2588\u2588\u2588"],N:["\u2588 \u2588","\u2588\u2588 \u2588","\u2588 \u2588\u2588","\u2588 \u2588","\u2588 \u2588"],T:["\u2588\u2588\u2588\u2588"," \u2588\u2588 "," \u2588\u2588 "," \u2588\u2588 "," \u2588\u2588 "],F:["\u2588\u2588\u2588\u2588","\u2588 ","\u2588\u2588\u2588 ","\u2588 ","\u2588 "],K:["\u2588 \u2588","\u2588 \u2588 ","\u2588\u2588 ","\u2588 \u2588 ","\u2588 \u2588"]," ":[" "," "," "," "," "]};function MS(e){let t=Array.from({length:5},()=>"");return[...e.toUpperCase()].forEach((r,o)=>{let i=f8[r];if(i===void 0)throw new Error(`ascii-wordmark: no glyph for character ${JSON.stringify(r)}`);let s=o===0?"":" ".repeat(1);for(let a=0;a<5;a++)t[a]+=s+(i[a]??"")}),t}function W_(e){return MS(e)[0]?.length??0}function q_(e){let t=e.model!==void 0||e.worktree!==void 0||e.cwd!==void 0||e.version!==void 0;return t&&!Xs()?v8(e):K_(t?h8(e):e)}function h8(e){let t=e.mode;e.model!==void 0&&e.model.length>0&&(t=`${e.model} \xB7 ${t}`),e.version!==void 0&&e.version.length>0&&(t=`${t} \xB7 ${z_(e.version)}`);let n=[];e.worktree!==void 0&&e.worktree.length>0&&n.push(`branch ${e.worktree}`),e.cwd!==void 0&&e.cwd.length>0&&n.push(J_(e.cwd));let r=n.join(" \xB7 "),o=e.metaLine!==void 0?e.metaLine:r.length>0?r:void 0,i={mode:t};return o!==void 0&&(i.metaLine=o),e.hintLine!==void 0&&(i.hintLine=e.hintLine),i}function K_(e){let t="Agent AFK",n=" \xB7 ",r=p.bold(t)+p.dim(n)+e.mode,o=t+n+e.mode,i=Math.min(ne()-4,120),s=Math.max(54,ee(o)+4,i);s=Math.min(s,Zt());let a=s+4,l=p.dim,c=l("\u256D"+"\u2500".repeat(a)+"\u256E"),u=we(r,s).split(`
|
|
1204
1208
|
`).map(g=>l("\u2502")+" "+tt(g,s)+" "+l("\u2502")),m=l("\u2570"+"\u2500".repeat(a)+"\u256F"),f=[c,...u,m];return e.metaLine!==void 0&&f.push(...we(p.dim(" "+e.metaLine),ne()).split(`
|
|
@@ -1793,7 +1797,7 @@ ${v}
|
|
|
1793
1797
|
${E}`})}return{fileBlocks:l,warnings:c}}async function Vq(e,t,n,r,o="summary",i,s){let a=HH(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0),Il(process.stdout,_u(process.cwd(),!0));let l="",c=0,d=!1,u=!1,m=!1,f=!1,g=!1,h,y=!1,b=!1,w={abort:null},S=0,v=3e3,E=[],A=new Map,$=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,_=()=>{let L=r.subagentControl;L?.hasPromotableForeground()&&L.promoteActiveForeground().then(W=>{for(let q of W)(i??{fn:console.log}).fn(p.dim(` \u2192 subagent backgrounded as ${q.jobId}: ${q.label}`))}).catch(()=>{})},x=r.getCompositor?r.getCompositor():null,C=()=>new ql({out:zl(i),thinkingMode:o,...$?{activeSkillName:$}:{},onCancel:()=>{t.interrupt().catch(L=>{Ne()&&console.error(" "+p.error("session.interrupt() failed:"),L)})},...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}:{}}),I=C(),N=async()=>{if(!f){f=!0;try{await I.dispose()}catch{}}},H=async()=>{await I.arm();let L=I.getCompositor();if(i&&L){let W=L;i.fn=q=>W.commitAbove(q),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.(L),r.setInterruptNotifier?.(W=>I.setInterrupting(W)),r.rearmStatus?.()};try{x?x.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{y=!0,I.setSoftStopping(!0),t.interrupt().catch(O=>{Ne()&&console.error(" "+p.error("soft-stop session.interrupt() failed:"),O)});let M=r.subagentControl;M?.hasActiveForeground()&&M.cancelActiveForeground().catch(O=>{Ne()&&console.error(" "+p.error("soft-stop cancelActiveForeground() failed:"),O)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{b=!0,t.interrupt().catch(M=>{Ne()&&console.error(" "+p.error("pause-interrupt session.interrupt() failed:"),M)})}),await H(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(_);let{fileBlocks:L,warnings:W}=Yq(e.text,{rootDir:process.cwd()});for(let M of W)(i??{fn:console.log}).fn(p.dim(` @-file: ${M}`));if(e.attachments.length>0&&(await t.waitForInitialization(),t.sessionId===void 0))throw new Error("CLI session initialized without a session id");let q=L.length>0||e.attachments.length>0?await Jq(e.text,e.attachments,void 0,L,t.sessionId):e.text,P=t.sendMessageStream(q);if(await ya((M,O)=>{I.process(M,O)},async()=>{for await(let M of P){if(y||b)break;if(M.type==="chunk"&&M.chunk.type==="content"?(l=d?qq(l,M.chunk.content):l+M.chunk.content,d=!1,u=!0):M.type==="message"&&!u&&(l=M.message.content),M.type==="stream_retry"&&(l=l.slice(0,c),d=l.length>0),M.type==="chunk"&&M.chunk.type==="tool_use_detail"){let O=M.chunk,U={toolName:O.toolName,toolUseId:O.toolUseId,input:O.toolInput,...O.toolInputRaw!==void 0&&{inputRaw:O.toolInputRaw}};A.set(O.toolUseId,U),E.push(U)}else if(M.type==="chunk"&&M.chunk.type==="tool_result"){let O=M.chunk;c=l.length,d=!0;let U=A.get(O.toolUseId);if(U&&(U.result=O.content,U.isError=O.isError,A.delete(O.toolUseId)),r.onContextProgress){let Q=Date.now();if(Q-S>=v){S=Q;try{let j=r.onContextProgress();j instanceof Promise&&await j}catch(j){Ne()&&console.error(" "+p.error("onContextProgress (status refresh) failed:"),j)}}}}if(M.type==="paused"){if(r.setPausedState?.(!0),await N(),x&&M.autoResume===!0){let O=new AbortController;w.abort=O;let U=M.resetsAt?M.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,Q=U?`Keep waiting \u2014 auto-resumes at ${U}`:"Keep waiting \u2014 auto-resume in progress",j="Switch model / provider (type /model after)",Z="Stop waiting",se=[p.warning(" \u23F3 Usage limit reached.")+(U?p.dim(` Auto-resumes at ${U}.`):""),p.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];kn(x,{header:se,options:[Q,j,Z],signal:O.signal,initialIndex:0}).then(z=>{if(w.abort=null,!z)return;let te=z[0];te===void 0||te===Q||(b=!0,te===j&&(i??{fn:console.log}).fn(p.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(ie=>{Ne()&&console.error(" "+p.error("picker pause-interrupt session.interrupt() failed:"),ie)}))}).catch(z=>{Ne()&&console.error(" "+p.error("picker promise rejected:"),z)})}else(i??{fn:console.log}).fn(Y_({reason:M.reason,...M.resetsAt!==void 0?{resetsAt:M.resetsAt}:{},...M.accountId!==void 0?{accountId:M.accountId}:{},...M.autoResume!==void 0?{autoResume:M.autoResume}:{}}));continue}if(M.type==="resumed"){r.setPausedState?.(!1),w.abort?.abort(),w.abort=null;let O=M.hotSwapped&&M.accountId?`\u25B6 Resumed on ${M.accountId}`:"\u25B6 Resumed";l="",c=0,d=!1,u=!1,E.length=0,A.clear(),g=!1,h=void 0,m=!1,I=C(),f=!1,await H(),(i??{fn:console.log}).fn(p.success(O));continue}if(M.type==="error"){await N(),ea(zs(M.error)),m=!0;continue}I.process(M),M.type==="done"&&(g=!0,h=M.metadata)}}),await N(),y){let M=i?i.fn:console.log,O=x?x.getPendingCount():0,U=O>0?` \xB7 ${O} queued`:"";M(p.warning(`\u23F8 Stopped${U} \u2014 work so far kept.`)+p.dim(" Send a message to continue.")),M("")}if(b){let M=i?i.fn:console.log;M(p.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),M("")}if(g&&!y&&!b){ss(n,a,l,h,E),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),_l(process.stdout),P1(process.stdout,"afk: turn complete");let M=U=>{i?i.fn(U):console.log(U)},O=pw(l);if(O){M(zq(O)),M("");let U=pG(E);if(r.onTerminalState)try{r.onTerminalState(O,{doneHasCorroboratingEvidence:U})}catch{}if(n.permissionMode==="autonomous"){let Q=O.kind==="done"&&sd().verifyDone===!0&&!U;fG(O,void 0,{unverified:Q})}}if(Ybe(h,n,M),r.onAfterTurn){let U=r.onAfterTurn();U instanceof Promise&&await U.catch(()=>{})}}}catch(L){await N(),m||ea(zs(L))}finally{await N(),Il(process.stdout,_u(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),w.abort?.abort(),w.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function Jbe(e,t){let n=Math.round(e*100),r=ge(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${ge(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 Ybe(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(xe(e.durationMs)),e.totalCostUsd!==void 0&&r.push(at(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(ge(o+i)+" tok"),r.length>0&&n(p.dim(" \u25E6 "+r.join(" \xB7 ")));let s=$x(t),a=zt(t.model),l=Jbe(s,a);if(l.text!==null){let d=l.tier==="over"||l.tier==="near"?p.error:l.tier==="caution"?p.warning:p.dim;n(d(l.text))}let c=Gq(fb(Mh()),new Date,{autoResume:TP()});if(c.text!==null){let d=c.tier==="over"||c.tier==="near"?p.error:c.tier==="caution"?p.warning:p.dim;n(d(c.text))}n("")}var Vbe=5e3,Xbe=3,Qbe="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function Zbe(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(p.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function Xq(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,mascotBar:d,verdictLedger:u,shellPassthrough:m,bgResultNotifier:f}=s,g=null,h=[];e.session.current.waitForInitialization().then(async _=>{Ne()&&(g=Ib(_)),await Xu(e.session.current),Ne()&&(h=Px())}).catch(()=>{});let y=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,b,w=!1,S=!1,v,E,A,$=0;for(f.onInjectable=()=>{$>=Xbe||!o.isAwaitingInput()||!o.bufferIsEmpty()||($++,_l(process.stdout),y={text:Qbe,attachments:[]},o.abortPendingRead())};;){if(g&&(e.replRenderer.writeLine(g),e.replRenderer.writeLine(""),g=null),h.length>0){for(let P of h)e.replRenderer.writeLine(P);e.replRenderer.writeLine(""),h=[]}let _=m.drainNotifications();for(let{job:P,result:D}of _){let M=D.errorReason===void 0?"\u2713":"\u2717",O=D.errorReason==="abort"?"killed":D.errorReason==="timeout"?"timed out":D.errorReason==="signal-killed"?"killed by signal":`exit ${D.exitCode??0}`,U=Math.max(0,Math.round(D.durationMs/100)/10);e.replRenderer.writeLine(p.dim(` ${M} [${P.id}] ${O} \xB7 ${U}s \xB7 `)+P.command)}let x=f.drainNotifications();for(let{job:P}of x){let D=P.status==="completed"?"\u2713":P.status==="failed"?"\u2717":"\u2298",M=P.endedAt!==void 0?Math.max(0,Math.round((P.endedAt-P.startedAt)/100)/10):0,O=P.label.length>60?`${P.label.slice(0,60)}\u2026`:P.label;e.replRenderer.writeLine(p.dim(` ${D} [${P.jobId}] subagent ${P.status} \xB7 ${M}s \xB7 `)+O)}let C=l.renderIfChanged(e.stats.sessionId);if(C.length>0){for(let P of C)e.replRenderer.writeLine(P);e.replRenderer.writeLine("")}let I,N;if(y===void 0){let P=await e.session.current.takePendingPlanExitSeed();P!==void 0&&(e.stats.permissionMode=P.mode,y={text:P.message,attachments:[]})}if(y!==void 0){let P=y;y=void 0;let D=tc(e.stats.permissionMode),M=us({buffer:P.text,promptText:D,isTTY:!!process.stdout.isTTY,attachmentSummary:Ll([...P.attachments])});e.replRenderer.writeLine(M),I=P.text.trim(),N=P.attachments}else{let P=b;b=void 0;let D=await o.readLine({promptFn:()=>tc(e.stats.permissionMode),...P!==void 0?{initialBuffer:P}:{},onSigint:r,onShiftTab:()=>{aw(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});I=D.text.trim(),N=D.attachments}if(!I&&N.length===0)continue;if(I.startsWith("!")){let P=/^(0|false|off|no)$/i.test(k.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!P&&(w||(w=!0,e.replRenderer.writeLine(p.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await m.dispatch(I))){e.statusLine.rearm();continue}}let H=!1;if(I.startsWith("/")){let P=await $1(I,e.slashCtx,N);if(P.handled){if(P.result==="exit"){await e.resolveWorktreeDisposition?.(!0),e.rl.close();return}if((I==="/clear"||I.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(p.dim(` transcript: ${t.path()}`)),u.reset(),v=void 0),P.result!==null&&typeof P.result=="object"&&"kind"in P.result&&P.result.kind==="submit"){y={text:P.result.message,attachments:N??[]},e.statusLine.rearm();continue}if(P.result!==null&&typeof P.result=="object"&&"kind"in P.result&&P.result.kind==="prefill"){b=P.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}H=!0}a.push(I),await Zbe(e,I);let L=I;if(H){let P=HR(I);if(P){let D=P.name.replace(/^\//,"").split(":").pop()??"";if(D&&Ax(D)){let M={skillName:D,rawArgs:P.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},O=e.session.current.sessionId,U=ks(O),Q=Date.now();B(`[afk trace] preflight.start commandName=${D}`);let j=!1,Z=await vs(M,{cwd:e.stats.cwd??process.cwd(),artifactDir:U},se=>{Ne()&&e.replRenderer.writeLine(p.warning(`\u26A0 preflight(${D}) failed: `)+(se instanceof Error?se.message:String(se)))});j=Z!==null,B(`[afk trace] preflight.end commandName=${D} durationMs=${Date.now()-Q} success=${j}`),L=_x(Z?.manifestBlock,I)}}}let W=m.drainInjections();W.length>0&&(L=W+L);let q=f.drainInjections();if(q.length>0&&(L=q+L),v!==void 0&&(L=v+`
|
|
1794
1798
|
|
|
1795
1799
|
`+L,v=void 0),e.hookRegistry)try{let P={event:"UserPromptSubmit",prompt:L,sessionId:e.stats.sessionId},D=await e.hookRegistry.dispatch(P);D.injectContext&&(L=D.injectContext+L)}catch(P){if(P instanceof Re){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+(P.reason?p.dim(`: ${Ir(P.reason)}`):"")),e.statusLine.rearm();continue}if(P instanceof er){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+p.dim(`: handler timed out after ${P.timeoutMs}ms`)),e.statusLine.rearm();continue}throw P}if(E=void 0,A=void 0,await Vq({text:L,attachments:N},e.session.current,e.stats,{setInFlight(P){n.turnInFlight=P},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(P){await t.appendUser(P)},async onTurnComplete(P,D){if(await t.appendTurn(P,D),e.stats.sessionId)try{jo(e.stats)}catch(M){S||(S=!0,e.replRenderer.writeLine(p.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(M instanceof Error?M.message:String(M))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await e.gitStatusSampler.refresh(),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:(P,D)=>{u?.push(P),E=P.kind,A=D?.doneHasCorroboratingEvidence},setActiveCompositor:P=>{n.activeCompositor=P},setInterruptNotifier:P=>{n.notifyInterrupting=P},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:P=>o.setBackgroundHandler(P),setSoftStopHandler:i,setPausedState:P=>o.setPausedState(P),setPauseInterruptHandler:P=>o.setPauseInterruptHandler(P),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(Hn(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:(P,D)=>{c.repaint(P),d?.onStage(P,D)}}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(tc(e.stats.permissionMode))),e.hookRegistry)try{let P=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...E!==void 0?{terminalState:E}:{},...A!==void 0?{doneHasCorroboratingEvidence:A}:{}},void 0,Vbe);P.injectContext&&P.injectContext.trim().length>0&&(v=P.injectContext)}catch(P){if(P instanceof ct)throw P;P instanceof er?(B("[stop hook] handler timed out"),e.completionWriter.fn(p.dim(" [stop hook] timed out"))):P instanceof Re?e.completionWriter.fn(p.dim(` [stop hook] blocked: ${Ir(P.reason??"no reason given")}`)):B("[stop hook] unexpected error: "+String(P))}}}function ewe(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 Qq(e,t,n,r){let o=await vq(),i=new sw({rl:e.rl,history:o,statusLine:e.statusLine}),s=ewe(k.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await xq(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar,getMascotBar:()=>a?.mascotBar});a=Wq(e,n),await Xq(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)}}Qc();Ca();import{execFile as twe}from"node:child_process";import{dirname as nwe,isAbsolute as rwe,resolve as owe}from"node:path";import{promisify as iwe}from"node:util";var Zq=iwe(twe),swe=3e3,awe=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function lwe(){let t=(await Zq("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=rwe(t)?t:owe(process.cwd(),t);return nwe(n)}async function ez(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await lwe()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),swe)});try{let o=un({execFile:Zq,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=>awe.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}fm();Qc();import{promises as cwe}from"node:fs";import{dirname as dwe,join as rz}from"node:path";import{randomBytes as uwe}from"node:crypto";var pwe=["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(`
|
|
1796
|
-
`),tz=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,FA=30,mwe=1024,fwe=8e3,gwe="haiku";async function hwe(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=Swe(n,mwe),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??fwe),s=t.signal?vwe([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await ia({token:t.token,model:t.model??gwe,system:pwe,user:r,maxTokens:32,signal:s})}catch(u){let m=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(i)}let l=ywe(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=dwe(t.worktreePath);return await bwe(l,c)}function ywe(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(tz.test(t)&&t.length<=FA)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>FA)break;o=s}return tz.test(o)?o:null}async function bwe(e,t){if(!await wwe(rz(t,e)))return e;let n=uwe(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,FA-5)}-${n}`}async function wwe(e){try{return await cwe.access(e),!0}catch{return!1}}function Swe(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 vwe(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 oz(e){let t,n,r=rz(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await hwe(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=`${$m(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return nz(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 nz(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 nz(e,t){e&&e.setCwd(t),kwe(t)}function kwe(e){try{process.chdir(e)}catch{}}bt();G();import{spawn as sz}from"child_process";import{existsSync as az,mkdirSync as Awe,readFileSync as lz,unlinkSync as iz,writeFileSync as cz}from"fs";import{get as Cwe}from"https";import{join as dz}from"path";import{readFileSync as Twe}from"fs";import{dirname as Ewe,join as Rwe}from"path";import{fileURLToPath as xwe}from"url";function hr(){try{return"5.95.
|
|
1800
|
+
`),tz=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,FA=30,mwe=1024,fwe=8e3,gwe="haiku";async function hwe(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=Swe(n,mwe),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??fwe),s=t.signal?vwe([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await ia({token:t.token,model:t.model??gwe,system:pwe,user:r,maxTokens:32,signal:s})}catch(u){let m=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(i)}let l=ywe(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=dwe(t.worktreePath);return await bwe(l,c)}function ywe(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(tz.test(t)&&t.length<=FA)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>FA)break;o=s}return tz.test(o)?o:null}async function bwe(e,t){if(!await wwe(rz(t,e)))return e;let n=uwe(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,FA-5)}-${n}`}async function wwe(e){try{return await cwe.access(e),!0}catch{return!1}}function Swe(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 vwe(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 oz(e){let t,n,r=rz(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await hwe(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=`${$m(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return nz(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 nz(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 nz(e,t){e&&e.setCwd(t),kwe(t)}function kwe(e){try{process.chdir(e)}catch{}}bt();G();import{spawn as sz}from"child_process";import{existsSync as az,mkdirSync as Awe,readFileSync as lz,unlinkSync as iz,writeFileSync as cz}from"fs";import{get as Cwe}from"https";import{join as dz}from"path";import{readFileSync as Twe}from"fs";import{dirname as Ewe,join as Rwe}from"path";import{fileURLToPath as xwe}from"url";function hr(){try{return"5.95.7"}catch{}try{let e=Ewe(xwe(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(Twe(Rwe(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}K();var _we=64*1024,Iwe=10800*1e3,Pwe=800,Mwe=3600*1e3,Owe="update-check.json",$we="pending-update.json";function LA(){return dz(Ks(),Owe)}function cp(){return dz(Ks(),$we)}function NA(){let e=Ks();az(e)||Awe(e,{recursive:!0})}function uz(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 pz(){try{let e=lz(LA(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function mz(){try{NA();let e=`
|
|
1797
1801
|
const https = require('https');
|
|
1798
1802
|
const fs = require('fs');
|
|
1799
1803
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var ZS=Object.defineProperty;var we=(t,e)=>()=>(t&&(e=t(t=0)),e);var jd=(t,e)=>{for(var n in e)ZS(t,n,{get:e[n],enumerable:!0})};function ho(t){return go.find(e=>e.name===t)}function Ea(t){return process.env[t]!==void 0}var go,b,P=we(()=>{"use strict";go=[{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_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. Falls back to provider default when unset.",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-request time-to-first-token timeout (ms) for the anthropic-direct streaming loop. Bounds how long a single model call 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. NOTE: a request whose FIRST token takes longer than the bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted, retried once, then surfaces as an error (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). 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_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:"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_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:"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_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:"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"}],b={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_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_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 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_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 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_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 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 go){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(b,e.name);n&&Object.defineProperty(b,e.name,{...n,enumerable:!1})}})()});function ev(){return b.AFK_DEBUG==="1"||b.DEBUG==="1"}function R(...t){ev()&&console.log(...t)}var Z=we(()=>{"use strict";P()});import{existsSync as Wd,mkdirSync as tv,renameSync as nv,cpSync as rv,rmSync as ov}from"fs";import{join as H,dirname as _a,basename as sv,isAbsolute as Ta}from"path";import{homedir as Gd}from"os";import{fileURLToPath as iv}from"url";function le(){let t=b.AFK_HOME;if(t!==void 0&&t!==""){if(!Ta(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return H(Gd(),".afk")}function Te(){let t=b.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!Ta(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return H(le(),"agent-framework")}function yo(){return H(Te(),"forge-telemetry.jsonl")}function qd(){return H(Te(),"briefs")}function zd(){return H(Te(),"facets")}function Hn(){return H(le(),"skills")}function Qt(){return H(le(),"plugins")}function Jd(t=process.cwd()){return H(t,".afk")}function Vd(t=process.cwd()){return H(Jd(t),"skills")}function Yd(t=process.cwd()){return H(Jd(t),"plugins")}function Xd(t=process.cwd()){return H(t,".afk","plans")}function bo(){return H(Qt(),".index.json")}function xa(){return H(jn(),"schedules.json")}function Qd(){let t=iv(import.meta.url),e=_a(t);return H(e,"bundled-plugins")}function jn(){return H(le(),"config")}function fe(){let t=b.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Ta(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return H(le(),"state")}function Se(){return H(fe(),"sessions")}function wo(){return H(fe(),"presence")}function So(){return H(fe(),"memory")}function vo(){return H(fe(),"session-grants.jsonl")}function Zd(){return H(le(),"farms")}function eu(t){return H(Zd(),t)}function ko(t){if(!av.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function Ao(t){return ko(t),H(fe(),"witness",t)}function tu(t){return H(Ao(t),"inbound-attachments")}function nu(t){return H(Ao(t),"prompts")}function Eo(t){return!t||t.startsWith("in-memory:")?null:sv(_a(t))}function ru(t="default"){return H(fe(),"daemon",`agent-afk@${t}`)}function ou(){return H(fe(),"worktree-sweep.lock")}function _o(){return H(fe(),"worktree-roots.json")}function Ra(){return H(jn(),"afk.env")}function Zt(){return H(jn(),"afk.config.json")}function To(){return H(Gd(),".afk.config.json")}function lv(){return H(le(),"sessions")}function cv(t,e){if(t!==e&&Wd(t)&&!Wd(e))try{tv(_a(e),{recursive:!0});try{nv(t,e)}catch(n){if(n.code==="EXDEV")try{rv(t,e,{recursive:!0}),ov(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 su(){cv(lv(),Se())}function Ia(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>Kd)throw new Error(`Invalid browser profile: exceeds ${Kd} chars`);if(!dv.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function uv(){return H(fe(),"browser")}function pv(t){return Ia(t),H(uv(),t)}function Ca(t){return H(pv(t),"storageState.json")}function Wn(t){return typeof t=="string"&&t.length>0&&t.length<=mv&&fv.test(t)}function Kn(t){if(!Wn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return H(Se(),t)}function xo(t){return H(Kn(t),"events.jsonl")}function iu(t){return H(Kn(t),"session.key")}var av,dv,Kd,fv,mv,F=we(()=>{"use strict";P();av=/^[a-zA-Z0-9_-]+$/;dv=/^[A-Za-z0-9_-]+$/,Kd=128;fv=/^[A-Za-z0-9_-]+$/,mv=128});import{readFileSync as QT}from"node:fs";import{join as ZT}from"path";function ex(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Zf(t,e){return ex(e).test(t)}function rx(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(tx.has(e))return!0;if(nx.has(e))return!1}return!1}function em(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function ox(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 tm(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Ia(e),e}function sx(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function ix(t){try{return QT(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function ax(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=tm(e.defaultProfile)),n}function nm(t){let e=t?.env??b,n=t?.readFileSync??ix,r=t?.surface??e.AGENT_SURFACE,o=rx(e.AFK_BROWSER_HEADLESS,r),s=em(e.AFK_BROWSER_ALLOWED_DOMAINS),i=em(e.AFK_BROWSER_BLOCKED_DOMAINS),a=sx(e.AFK_BROWSER_DOM_SNAPSHOTS),l=ox(e.AFK_BROWSER_BACKEND),c=tm(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():ZT(jn(),"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=ax(d,m);return g.configPath=p,g}function As(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(Zf(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Zf(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var tx,nx,Es=we(()=>{"use strict";P();F();tx=new Set(["daemon","subagent","telegram","afk"]),nx=new Set(["repl","interactive","cli"])});import{existsSync as lx,readFileSync as cx}from"node:fs";import{createRequire as dx}from"node:module";import{dirname as ux,join as px}from"node:path";function sm(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<mx&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function be(t){let e=sm(t);return om.some(n=>e.includes(n))}function gx(){try{let e=dx(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(cx(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=px(ux(e),o);return lx(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function kr(){return rm??=gx()??fx,rm}function $l(t){return t.includes("install chromium")}function Oe(t,e){let n=sm(t),r=e?.latched===!0?` ${hx}`:"";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 Bl(t,e,n=!1){if(!be(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
3
3
|
|
|
4
|
-
${Oe(t,{headless:e,latched:n})}`,{cause:t})}var om,fx,mx,rm,hx,Hl=we(()=>{"use strict";om=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],fx="pnpm exec playwright install chromium",mx=4;hx="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 jt from"node:fs";import _s from"node:path";import{randomBytes as yx}from"node:crypto";import{chromium as bx}from"playwright";function wx(){try{return"5.95.6"}catch{}try{let t=_s.resolve(import.meta.dirname,"../../../package.json"),e=jt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Sx,Ts,im=we(()=>{"use strict";Hl();F();Z();Sx=wx(),Ts=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=bx.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=Bl(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/${Sx}`}}loadStorageState(e){let n=Ca(e);try{if(!jt.existsSync(n))return;let r=JSON.parse(jt.readFileSync(n,"utf8"));return R("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){R("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Ca(e);if(!jt.existsSync(r))return;let o=await n.storageState(),s=_s.join(_s.dirname(r),`.${_s.basename(r)}.${process.pid}.${yx(4).toString("hex")}.tmp`);jt.writeFileSync(s,JSON.stringify(o),{mode:384}),jt.chmodSync(s,384),jt.renameSync(s,r),R("[browser/vault] saved session",{profile:e,file:r})}catch(r){R("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as vx}from"crypto";function am(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&kx.test(t.label))}function lm(t){return vx("sha256").update(t,"utf8").digest("hex").slice(0,8)}function cm(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var kx,xs=we(()=>{"use strict";kx=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Ax}from"node:crypto";function Ex(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function _x(t,e,n){return`el_${Ax("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Tx(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function dm(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function pm(t,e){let n=t.role??"",r=t.name??"";um.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])pm(s,e)}async function xx(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},fm).catch(()=>[])}async function Rx(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},fm).catch(()=>[])}function Ix(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Rs(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=Ix(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=xx(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,y=!1;u!==null?(h=[],pm(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await Rx(t)).filter(W=>um.has(W.role??"")));let w=new Map;for(let A of p){let W=dm(A.name),te=w.get(W);(!te||te.bbox.w===0&&A.bbox.w>0)&&w.set(W,A)}let v=h.map(A=>({ax:A,dom:w.get(dm(A.name??""))})),S=r?v:v.filter(A=>A.dom?A.dom.bbox.w>0||A.dom.bbox.h>0:!0);S.sort((A,W)=>{let te=A.dom?.bbox.y??0,O=W.dom?.bbox.y??0;if(te!==O)return te-O;let $=A.dom?.bbox.x??0,M=W.dom?.bbox.x??0;return $-M}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=S.slice(0,n).map((A,W)=>{let te=A.ax.role??"generic",O=A.ax.name??"",$=_x(te,O,W),M=A.dom?.bbox??{x:0,y:0,w:0,h:0},C=A.dom?.type??null,K=null;A.ax.value!==void 0&&A.ax.value!==null&&(K=String(A.ax.value)),A.ax.checked!==void 0&&(K=String(A.ax.checked)),am({role:te,kind:C})&&(K="[redacted]");let N={disabled:A.ax.disabled??!1};A.ax.checked!==void 0&&(N.checked=A.ax.checked===!0||A.ax.checked==="mixed"),A.ax.selected!==void 0&&(N.selected=A.ax.selected),A.ax.expanded!==void 0&&(N.expanded=A.ax.expanded);let z;A.dom?.testId?z=`[data-testid="${A.dom.testId}"]`:A.dom?.id&&(z=`#${A.dom.id}`);let X={id:$,role:te,label:Ex(O),kind:C,value:K,state:N,bbox:M};return z!==void 0&&(X.selector=z),X}),x="idle";try{let A=await t.evaluate(()=>document.readyState);A==="loading"?x="loading":A==="interactive"?x="navigating":x="idle"}catch{x="navigating"}x!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let L=Tx(f),_=`obs_${e.observationCounter.toString(36)}`,I=new Date().toISOString();return{observationId:_,url:m,title:g,textSummary:L,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:x,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:I}}var um,fm,mm=we(()=>{"use strict";xs();um=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);fm="a[href], button, input, select, textarea, [role], [tabindex], label"});async function gm(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 jl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>gm(t,s)))).filter(o=>o!==null)}async function Cx(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 Wl(t,e,n){switch(e.kind){case"element_id":return Px(t,e,n);case"selector":return Mx(t,e);case"semantic":return Ox(t,e)}}async function Px(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 jl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Mx(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 jl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Ox(t,e){return e.role!==void 0?Dx(t,e.text,e.role):Fx(t,e.text,e)}async function Dx(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 jl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Fx(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 Cx(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 y=await gm(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,v=0;for(let S=0;S<w.length;S++)v=v*31+w.charCodeAt(S)>>>0;f.push({...y,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var hm=we(()=>{"use strict"});async function Kl(t,e,n,r){let o=t.url();if(o===n)return null;let s=As(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 ym=we(()=>{"use strict";Es()});import{randomBytes as Lx}from"crypto";import{mkdir as Nx,stat as Ux,writeFile as $x}from"fs/promises";import{join as Gl}from"path";import{gzip as Bx}from"zlib";import{promisify as Hx}from"util";function jx(t){return Gl(Ao(t),"browser")}function Wx(t){return Gl(jx(t),"screenshots")}function Kx(){return new Date().toISOString().replace(/[:.]/g,"-")}function Gx(){return Lx(3).toString("hex")}async function ql(t,e,n){if(e.length>bm)throw new Error(`writeScreenshotSidecar: buffer exceeds ${bm} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=Wx(t);await Nx(r,{recursive:!0});let o=`${Kx()}-${Gx()}-${n}.png`,s=Gl(r,o);await $x(s,e);let{size:i}=await Ux(s);return{path:s,bytes:i}}var pW,bm,wm=we(()=>{"use strict";F();xs();pW=Hx(Bx);bm=5*1024*1024});var vm={};jd(vm,{PlaywrightProvider:()=>zl});function Sm(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 zl,km=we(()=>{"use strict";im();mm();hm();Es();ym();wm();zl=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Ts(e)}async open(e){let n=As(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 Kl(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 Rs(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 Rs(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 Wl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Sm(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 Kl(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 Rs(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 Wl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Sm(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 ql(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 ql(n,o,r);return s}catch{return null}}}});var Kt={};jd(Kt,{__resetBrowserRegistryForTests:()=>Yx,browserProviderActive:()=>Jx,closeBrowserProvider:()=>Jl,getBrowserProvider:()=>zx,peekBrowserProvider:()=>Vx});function Am(){Promise.resolve(Jl()).then(()=>{process.exit(130)})}function Em(){Promise.resolve(Jl()).then(()=>{process.exit(143)})}function _m(){Ge=null}function qx(){Is||(process.on("SIGINT",Am),process.on("SIGTERM",Em),process.on("exit",_m),Is=!0)}function Tm(){Is&&(process.removeListener("SIGINT",Am),process.removeListener("SIGTERM",Em),process.removeListener("exit",_m),Is=!1)}async function zx(t){return Ge!==null?Ge:(Wt!==null||(Wt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(km(),vm)),n=nm(t),r=new e(n);return qx(),Ge=r,Wt=null,r})()),Wt)}async function Jl(){if(Ge===null)return;let t=Ge;Ge=null,Wt=null,Tm(),await t.shutdown()}function Jx(){return Ge!==null}function Vx(){return Ge}function Yx(){Ge=null,Wt=null,Tm()}var Ge,Wt,Is,Gt=we(()=>{"use strict";Es();Ge=null,Wt=null,Is=!1});Z();P();F();Z();import{randomBytes as _v}from"node:crypto";import{mkdir as Tv,writeFile as xv}from"node:fs/promises";import{join as Rv}from"node:path";P();import{mkdirSync as gv,appendFileSync as hv,existsSync as yv}from"fs";import{resolve as bv}from"path";import{dirname as wv}from"path";var Sv=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
4
|
+
${Oe(t,{headless:e,latched:n})}`,{cause:t})}var om,fx,mx,rm,hx,Hl=we(()=>{"use strict";om=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],fx="pnpm exec playwright install chromium",mx=4;hx="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 jt from"node:fs";import _s from"node:path";import{randomBytes as yx}from"node:crypto";import{chromium as bx}from"playwright";function wx(){try{return"5.95.7"}catch{}try{let t=_s.resolve(import.meta.dirname,"../../../package.json"),e=jt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Sx,Ts,im=we(()=>{"use strict";Hl();F();Z();Sx=wx(),Ts=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=bx.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=Bl(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/${Sx}`}}loadStorageState(e){let n=Ca(e);try{if(!jt.existsSync(n))return;let r=JSON.parse(jt.readFileSync(n,"utf8"));return R("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){R("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Ca(e);if(!jt.existsSync(r))return;let o=await n.storageState(),s=_s.join(_s.dirname(r),`.${_s.basename(r)}.${process.pid}.${yx(4).toString("hex")}.tmp`);jt.writeFileSync(s,JSON.stringify(o),{mode:384}),jt.chmodSync(s,384),jt.renameSync(s,r),R("[browser/vault] saved session",{profile:e,file:r})}catch(r){R("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as vx}from"crypto";function am(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&kx.test(t.label))}function lm(t){return vx("sha256").update(t,"utf8").digest("hex").slice(0,8)}function cm(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var kx,xs=we(()=>{"use strict";kx=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Ax}from"node:crypto";function Ex(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function _x(t,e,n){return`el_${Ax("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Tx(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function dm(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function pm(t,e){let n=t.role??"",r=t.name??"";um.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])pm(s,e)}async function xx(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},fm).catch(()=>[])}async function Rx(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},fm).catch(()=>[])}function Ix(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Rs(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=Ix(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=xx(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,y=!1;u!==null?(h=[],pm(u,h)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,h=(await Rx(t)).filter(W=>um.has(W.role??"")));let w=new Map;for(let A of p){let W=dm(A.name),te=w.get(W);(!te||te.bbox.w===0&&A.bbox.w>0)&&w.set(W,A)}let v=h.map(A=>({ax:A,dom:w.get(dm(A.name??""))})),S=r?v:v.filter(A=>A.dom?A.dom.bbox.w>0||A.dom.bbox.h>0:!0);S.sort((A,W)=>{let te=A.dom?.bbox.y??0,O=W.dom?.bbox.y??0;if(te!==O)return te-O;let $=A.dom?.bbox.x??0,M=W.dom?.bbox.x??0;return $-M}),S.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=S.slice(0,n).map((A,W)=>{let te=A.ax.role??"generic",O=A.ax.name??"",$=_x(te,O,W),M=A.dom?.bbox??{x:0,y:0,w:0,h:0},C=A.dom?.type??null,K=null;A.ax.value!==void 0&&A.ax.value!==null&&(K=String(A.ax.value)),A.ax.checked!==void 0&&(K=String(A.ax.checked)),am({role:te,kind:C})&&(K="[redacted]");let N={disabled:A.ax.disabled??!1};A.ax.checked!==void 0&&(N.checked=A.ax.checked===!0||A.ax.checked==="mixed"),A.ax.selected!==void 0&&(N.selected=A.ax.selected),A.ax.expanded!==void 0&&(N.expanded=A.ax.expanded);let z;A.dom?.testId?z=`[data-testid="${A.dom.testId}"]`:A.dom?.id&&(z=`#${A.dom.id}`);let X={id:$,role:te,label:Ex(O),kind:C,value:K,state:N,bbox:M};return z!==void 0&&(X.selector=z),X}),x="idle";try{let A=await t.evaluate(()=>document.readyState);A==="loading"?x="loading":A==="interactive"?x="navigating":x="idle"}catch{x="navigating"}x!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let L=Tx(f),_=`obs_${e.observationCounter.toString(36)}`,I=new Date().toISOString();return{observationId:_,url:m,title:g,textSummary:L,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:x,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:I}}var um,fm,mm=we(()=>{"use strict";xs();um=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);fm="a[href], button, input, select, textarea, [role], [tabindex], label"});async function gm(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 jl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>gm(t,s)))).filter(o=>o!==null)}async function Cx(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 Wl(t,e,n){switch(e.kind){case"element_id":return Px(t,e,n);case"selector":return Mx(t,e);case"semantic":return Ox(t,e)}}async function Px(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 jl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Mx(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 jl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function Ox(t,e){return e.role!==void 0?Dx(t,e.text,e.role):Fx(t,e.text,e)}async function Dx(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 jl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Fx(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 Cx(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 y=await gm(h.locator,h.index);if(y!==null){let w=`${y.role}:${y.label}:${g}`,v=0;for(let S=0;S<w.length;S++)v=v*31+w.charCodeAt(S)>>>0;f.push({...y,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var hm=we(()=>{"use strict"});async function Kl(t,e,n,r){let o=t.url();if(o===n)return null;let s=As(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 ym=we(()=>{"use strict";Es()});import{randomBytes as Lx}from"crypto";import{mkdir as Nx,stat as Ux,writeFile as $x}from"fs/promises";import{join as Gl}from"path";import{gzip as Bx}from"zlib";import{promisify as Hx}from"util";function jx(t){return Gl(Ao(t),"browser")}function Wx(t){return Gl(jx(t),"screenshots")}function Kx(){return new Date().toISOString().replace(/[:.]/g,"-")}function Gx(){return Lx(3).toString("hex")}async function ql(t,e,n){if(e.length>bm)throw new Error(`writeScreenshotSidecar: buffer exceeds ${bm} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=Wx(t);await Nx(r,{recursive:!0});let o=`${Kx()}-${Gx()}-${n}.png`,s=Gl(r,o);await $x(s,e);let{size:i}=await Ux(s);return{path:s,bytes:i}}var pW,bm,wm=we(()=>{"use strict";F();xs();pW=Hx(Bx);bm=5*1024*1024});var vm={};jd(vm,{PlaywrightProvider:()=>zl});function Sm(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 zl,km=we(()=>{"use strict";im();mm();hm();Es();ym();wm();zl=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Ts(e)}async open(e){let n=As(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 Kl(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 Rs(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 Rs(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 Wl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Sm(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 Kl(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 Rs(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 Wl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Sm(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 ql(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 ql(n,o,r);return s}catch{return null}}}});var Kt={};jd(Kt,{__resetBrowserRegistryForTests:()=>Yx,browserProviderActive:()=>Jx,closeBrowserProvider:()=>Jl,getBrowserProvider:()=>zx,peekBrowserProvider:()=>Vx});function Am(){Promise.resolve(Jl()).then(()=>{process.exit(130)})}function Em(){Promise.resolve(Jl()).then(()=>{process.exit(143)})}function _m(){Ge=null}function qx(){Is||(process.on("SIGINT",Am),process.on("SIGTERM",Em),process.on("exit",_m),Is=!0)}function Tm(){Is&&(process.removeListener("SIGINT",Am),process.removeListener("SIGTERM",Em),process.removeListener("exit",_m),Is=!1)}async function zx(t){return Ge!==null?Ge:(Wt!==null||(Wt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(km(),vm)),n=nm(t),r=new e(n);return qx(),Ge=r,Wt=null,r})()),Wt)}async function Jl(){if(Ge===null)return;let t=Ge;Ge=null,Wt=null,Tm(),await t.shutdown()}function Jx(){return Ge!==null}function Vx(){return Ge}function Yx(){Ge=null,Wt=null,Tm()}var Ge,Wt,Is,Gt=we(()=>{"use strict";Es();Ge=null,Wt=null,Is=!1});Z();P();F();Z();import{randomBytes as _v}from"node:crypto";import{mkdir as Tv,writeFile as xv}from"node:fs/promises";import{join as Rv}from"node:path";P();import{mkdirSync as gv,appendFileSync as hv,existsSync as yv}from"fs";import{resolve as bv}from"path";import{dirname as wv}from"path";var Sv=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
5
5
|
`,vv=/key|token|secret|password|credential|auth/i,kv=[[/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,t=>`${t[1]}=<REDACTED length=${t[2].length}>`],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,t=>`${t[1]}=<REDACTED length=${t[2].length}>`]];function Ma(t){let e=t;for(let[n,r]of kv)e=e.replace(n,(...o)=>{let s=o.slice(0,o.length-2);return r(s)});return e}function Pa(t){return typeof t=="string"?Ma(t):Array.isArray(t)?t.map(Pa):t}function Av(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))vv.test(s)&&typeof i=="string"?o[s]=`<REDACTED length=${i.length}>`:o[s]=i;n.env=o}return"system"in e&&(n.system=Pa(e.system)),"systemPrompt"in e&&(n.systemPrompt=Pa(e.systemPrompt)),n}function Ev(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 au(t){let e=b.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=Ev(r),s={timestamp:new Date().toISOString(),prompt:t.prompt,options:Av(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=bv(e),a=wv(i);try{gv(a,{recursive:!0});let c=(!yv(i)?Sv:"")+JSON.stringify(s)+`
|
package/dist/telegram.mjs
CHANGED
|
@@ -878,7 +878,7 @@ Retrying it verbatim will fail the same way. Fix the underlying cause, change th
|
|
|
878
878
|
|
|
879
879
|
`).trim()}function rN(t){return(t?.textContent??"").replace(/\s+/g," ").trim().length}async function NS(t,e){let{JSDOM:n,Readability:r,turndown:o}=await nN(),i=new n(t,{url:e}).window.document,a=(i.title??"").trim(),l=(()=>{try{let p=i.cloneNode(!0);return new r(p).parse()}catch{return null}})();if(l&&typeof l.content=="string"&&l.content.trim().length>0){let p=LS(o.turndown(l.content)),f=(l.title??"").trim()||a,m=typeof l.length=="number"&&l.length>0?l.length:(l.textContent??"").replace(/\s+/g," ").trim().length;return{title:f,markdown:p,textLength:m,usedFallback:!1}}let c=i.body,d=c?.innerHTML??"",u=LS(o.turndown(d));return{title:a,markdown:u,textLength:rN(c),usedFallback:!0}}var Tp,$S=h(()=>{"use strict";Tp=null});function sN(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 US(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function iN(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 BS(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??sN,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(!oN.has(u.status)||d===o)return u;let p=iN(u,i)??US(d,s,i);D("[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=US(d,s,i);D("[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 oN,HS=h(()=>{"use strict";ce();oN=new Set([429,502,503,504])});import{BlockList as aN,isIP as Rp}from"node:net";import{lookup as lN}from"node:dns/promises";import{Agent as cN}from"undici";function WS(){let t=E.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return t==="1"||t==="true"}function fN(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function xp(t){let e=Rp(t);return e===0?!1:pN.check(t,e===4?"ipv4":"ipv6")}async function KS(t){return lN(t,{all:!0,verbatim:!0})}async function Cp(t,e={}){if(e.allowPrivateHosts??WS())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=fN(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(Rp(r)!==0)return xp(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let s=e.lookupFn??KS,i;try{i=await s(r)}catch{return{allowed:!0}}for(let a of i)if(xp(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Jo(t,e={}){let n=await Cp(t,e);if(!n.allowed)throw new ut(n.reason)}async function za(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<=jS;i++){await Jo(s,o);let a={...n,redirect:"manual",...t===globalThis.fetch&&!(r.allowPrivateHosts??WS())?{dispatcher:mN}:{}},l=await BS(t,s,a,r.retry??{});if(!gN.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 ut(`too many redirects (>${jS}) starting from ${e}`)}var dN,uN,pN,ut,mN,jS,gN,Ip=h(()=>{"use strict";$();HS();dN=[["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]],uN=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],pN=(()=>{let t=new aN;for(let[e,n]of dN)t.addSubnet(e,n,"ipv4");for(let[e,n]of uN)t.addSubnet(e,n,"ipv6");return t})(),ut=class extends Error{constructor(e){super(e),this.name="EgressBlockedError"}};mN=new cN({connect:{lookup(t,e,n){KS(t).then(r=>{let o=r.find(i=>xp(i.address));if(o!==void 0){n(new ut(`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,Rp(s.address))},r=>n(r,"",0))}}});jS=20,gN=new Set([301,302,303,307,308])});import{readFileSync as hN}from"node:fs";import{join as yN}from"path";function bN(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function GS(t,e){return bN(e).test(t)}function vN(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(wN.has(e))return!0;if(SN.has(e))return!1}return!1}function qS(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function kN(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 zS(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Pd(e),e}function EN(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function AN(t){try{return hN(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function _N(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=zS(e.defaultProfile)),n}function JS(t){let e=t?.env??E,n=t?.readFileSync??AN,r=t?.surface??e.AGENT_SURFACE,o=vN(e.AFK_BROWSER_HEADLESS,r),s=qS(e.AFK_BROWSER_ALLOWED_DOMAINS),i=qS(e.AFK_BROWSER_BLOCKED_DOMAINS),a=EN(e.AFK_BROWSER_DOM_SNAPSHOTS),l=kN(e.AFK_BROWSER_BACKEND),c=zS(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():yN(Ct(),"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=_N(d,m);return g.configPath=p,g}function Ja(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(GS(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>GS(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var wN,SN,Va=h(()=>{"use strict";$();H();wN=new Set(["daemon","subagent","telegram","afk"]),SN=new Set(["repl","interactive","cli"])});import{existsSync as TN,readFileSync as xN}from"node:fs";import{createRequire as RN}from"node:module";import{dirname as CN,join as IN}from"node:path";function XS(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<MN&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function Oe(t){let e=XS(t);return YS.some(n=>e.includes(n))}function ON(){try{let e=RN(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(xN(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=IN(CN(e),o);return TN(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function Vo(){return VS??=ON()??PN,VS}function Pp(t){return t.includes("install chromium")}function tt(t,e){let n=XS(t),r=e?.latched===!0?` ${DN}`:"";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: ${Vo()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Vo()}). Or pick a different tool.${r}`}function Mp(t,e,n=!1){if(!Oe(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
880
880
|
|
|
881
|
-
${tt(t,{headless:e,latched:n})}`,{cause:t})}var YS,PN,MN,VS,DN,Op=h(()=>{"use strict";YS=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],PN="pnpm exec playwright install chromium",MN=4;DN="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 Un from"node:fs";import Ya from"node:path";import{randomBytes as FN}from"node:crypto";import{chromium as LN}from"playwright";function NN(){try{return"5.95.6"}catch{}try{let t=Ya.resolve(import.meta.dirname,"../../../package.json"),e=Un.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var $N,Xa,QS=h(()=>{"use strict";Op();H();ce();$N=NN(),Xa=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=LN.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=Mp(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/${$N}`}}loadStorageState(e){let n=Md(e);try{if(!Un.existsSync(n))return;let r=JSON.parse(Un.readFileSync(n,"utf8"));return D("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){D("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Md(e);if(!Un.existsSync(r))return;let o=await n.storageState(),s=Ya.join(Ya.dirname(r),`.${Ya.basename(r)}.${process.pid}.${FN(4).toString("hex")}.tmp`);Un.writeFileSync(s,JSON.stringify(o),{mode:384}),Un.chmodSync(s,384),Un.renameSync(s,r),D("[browser/vault] saved session",{profile:e,file:r})}catch(r){D("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as UN}from"crypto";function ZS(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&BN.test(t.label))}function ev(t){return UN("sha256").update(t,"utf8").digest("hex").slice(0,8)}function tv(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var BN,Qa=h(()=>{"use strict";BN=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as HN}from"node:crypto";function jN(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function WN(t,e,n){return`el_${HN("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function KN(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function nv(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ov(t,e){let n=t.role??"",r=t.name??"";rv.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])ov(s,e)}async function GN(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},sv).catch(()=>[])}async function qN(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},sv).catch(()=>[])}function zN(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Za(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=zN(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=GN(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=[],ov(u,y)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,y=(await qN(t)).filter(B=>rv.has(B.role??"")));let v=new Map;for(let I of p){let B=nv(I.name),j=v.get(B);(!j||j.bbox.w===0&&I.bbox.w>0)&&v.set(B,I)}let A=y.map(I=>({ax:I,dom:v.get(nv(I.name??""))})),k=r?A:A.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,B)=>{let j=I.dom?.bbox.y??0,L=B.dom?.bbox.y??0;if(j!==L)return j-L;let U=I.dom?.bbox.x??0,N=B.dom?.bbox.x??0;return U-N}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((I,B)=>{let j=I.ax.role??"generic",L=I.ax.name??"",U=WN(j,L,B),N=I.dom?.bbox??{x:0,y:0,w:0,h:0},P=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)),ZS({role:j,kind:P})&&(F="[redacted]");let W={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(W.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(W.selected=I.ax.selected),I.ax.expanded!==void 0&&(W.expanded=I.ax.expanded);let J;I.dom?.testId?J=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(J=`#${I.dom.id}`);let Z={id:U,role:j,label:jN(L),kind:P,value:F,state:W,bbox:N};return J!==void 0&&(Z.selector=J),Z}),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=KN(f),S=`obs_${e.observationCounter.toString(36)}`,R=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:R}}var rv,sv,iv=h(()=>{"use strict";Qa();rv=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);sv="a[href], button, input, select, textarea, [role], [tabindex], label"});async function av(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 Dp(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>av(t,s)))).filter(o=>o!==null)}async function JN(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 Fp(t,e,n){switch(e.kind){case"element_id":return VN(t,e,n);case"selector":return YN(t,e);case"semantic":return XN(t,e)}}async function VN(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 Dp(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function YN(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 Dp(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function XN(t,e){return e.role!==void 0?QN(t,e.text,e.role):ZN(t,e.text,e)}async function QN(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 Dp(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function ZN(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 JN(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 av(y.locator,y.index);if(w!==null){let v=`${w.role}:${w.label}:${g}`,A=0;for(let k=0;k<v.length;k++)A=A*31+v.charCodeAt(k)>>>0;f.push({...w,id:`el_${A.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var lv=h(()=>{"use strict"});async function Lp(t,e,n,r){let o=t.url();if(o===n)return null;let s=Ja(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 cv=h(()=>{"use strict";Va()});import{randomBytes as e$}from"crypto";import{mkdir as t$,stat as n$,writeFile as r$}from"fs/promises";import{join as Np}from"path";import{gzip as o$}from"zlib";import{promisify as s$}from"util";function i$(t){return Np(tr(t),"browser")}function a$(t){return Np(i$(t),"screenshots")}function l$(){return new Date().toISOString().replace(/[:.]/g,"-")}function c$(){return e$(3).toString("hex")}async function $p(t,e,n){if(e.length>dv)throw new Error(`writeScreenshotSidecar: buffer exceeds ${dv} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=a$(t);await t$(r,{recursive:!0});let o=`${l$()}-${c$()}-${n}.png`,s=Np(r,o);await r$(s,e);let{size:i}=await n$(s);return{path:s,bytes:i}}var T9,dv,uv=h(()=>{"use strict";H();Qa();T9=s$(o$);dv=5*1024*1024});var fv={};Ed(fv,{PlaywrightProvider:()=>Up});function pv(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 Up,mv=h(()=>{"use strict";QS();iv();lv();Va();cv();uv();Up=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Xa(e)}async open(e){let n=Ja(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 Lp(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 Za(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 Za(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 Fp(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${pv(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 Lp(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 Za(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 Fp(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${pv(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 $p(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 $p(n,o,r);return s}catch{return null}}}});var Hn={};Ed(Hn,{__resetBrowserRegistryForTests:()=>m$,browserProviderActive:()=>p$,closeBrowserProvider:()=>Bp,getBrowserProvider:()=>u$,peekBrowserProvider:()=>f$});function gv(){Promise.resolve(Bp()).then(()=>{process.exit(130)})}function hv(){Promise.resolve(Bp()).then(()=>{process.exit(143)})}function yv(){At=null}function d$(){el||(process.on("SIGINT",gv),process.on("SIGTERM",hv),process.on("exit",yv),el=!0)}function bv(){el&&(process.removeListener("SIGINT",gv),process.removeListener("SIGTERM",hv),process.removeListener("exit",yv),el=!1)}async function u$(t){return At!==null?At:(Bn!==null||(Bn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(mv(),fv)),n=JS(t),r=new e(n);return d$(),At=r,Bn=null,r})()),Bn)}async function Bp(){if(At===null)return;let t=At;At=null,Bn=null,bv(),await t.shutdown()}function p$(){return At!==null}function f$(){return At}function m$(){At=null,Bn=null,bv()}var At,Bn,el,jn=h(()=>{"use strict";Va();At=null,Bn=null,el=!1});async function wv(t,e){try{return await NS(t,e)}catch(n){return D("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function S$(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(jn(),Hn));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}async function Sv(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??S$,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i=t,a=null,l=null;try{let d=await za(n,t,{headers:w$,signal:e.signal},o);a=d.status,i=d.url||t;let u=d.headers.get("content-type")??"";if(d.ok){if(b$.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let p=await d.text();if(y$.test(u)&&!h$.test(u))return{title:"",markdown:p.trim(),finalUrl:i,usedRender:!1};if(s=await wv(p,i),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(d){if(e.signal.aborted||d instanceof ut||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;l=d}if(!(s===null||s.textLength<200)&&s!==null)return{title:s.title,markdown:s.markdown,finalUrl:i,usedRender:!1};try{await Jo(t,o);let d=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:p=>Jo(p,o)});d.finalUrl!==t&&/^https?:\/\//i.test(d.finalUrl)&&await Jo(d.finalUrl,o);let u=await wv(d.html,d.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||u.textLength>=s.textLength)return{title:u.title,markdown:u.markdown,finalUrl:d.finalUrl,usedRender:!0}}catch(d){if(e.signal.aborted||d instanceof ut)throw d;if(s===null){let u=d instanceof Error?d.message:String(d),p=l instanceof Error?l.message:`HTTP ${a??"error"}`,f=new Error(`web_scrape could not retrieve ${t}: fetch failed (${p}) and render failed (${u}).`);throw f.cause=d,f}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:i,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${a??"error"}).`)}var h$,y$,b$,w$,vv=h(()=>{"use strict";$S();Ip();ce();h$=/(text\/html|application\/xhtml\+xml)/i,y$=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,b$=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,w$={"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 E$(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(v$,{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),k$),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=vr(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 kv(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?E$({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 Ev(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
881
|
+
${tt(t,{headless:e,latched:n})}`,{cause:t})}var YS,PN,MN,VS,DN,Op=h(()=>{"use strict";YS=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],PN="pnpm exec playwright install chromium",MN=4;DN="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 Un from"node:fs";import Ya from"node:path";import{randomBytes as FN}from"node:crypto";import{chromium as LN}from"playwright";function NN(){try{return"5.95.7"}catch{}try{let t=Ya.resolve(import.meta.dirname,"../../../package.json"),e=Un.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var $N,Xa,QS=h(()=>{"use strict";Op();H();ce();$N=NN(),Xa=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=LN.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=Mp(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/${$N}`}}loadStorageState(e){let n=Md(e);try{if(!Un.existsSync(n))return;let r=JSON.parse(Un.readFileSync(n,"utf8"));return D("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){D("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Md(e);if(!Un.existsSync(r))return;let o=await n.storageState(),s=Ya.join(Ya.dirname(r),`.${Ya.basename(r)}.${process.pid}.${FN(4).toString("hex")}.tmp`);Un.writeFileSync(s,JSON.stringify(o),{mode:384}),Un.chmodSync(s,384),Un.renameSync(s,r),D("[browser/vault] saved session",{profile:e,file:r})}catch(r){D("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as UN}from"crypto";function ZS(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&BN.test(t.label))}function ev(t){return UN("sha256").update(t,"utf8").digest("hex").slice(0,8)}function tv(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var BN,Qa=h(()=>{"use strict";BN=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as HN}from"node:crypto";function jN(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function WN(t,e,n){return`el_${HN("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function KN(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function nv(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ov(t,e){let n=t.role??"",r=t.name??"";rv.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])ov(s,e)}async function GN(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},sv).catch(()=>[])}async function qN(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},sv).catch(()=>[])}function zN(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Za(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=zN(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=GN(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=[],ov(u,y)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,y=(await qN(t)).filter(B=>rv.has(B.role??"")));let v=new Map;for(let I of p){let B=nv(I.name),j=v.get(B);(!j||j.bbox.w===0&&I.bbox.w>0)&&v.set(B,I)}let A=y.map(I=>({ax:I,dom:v.get(nv(I.name??""))})),k=r?A:A.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,B)=>{let j=I.dom?.bbox.y??0,L=B.dom?.bbox.y??0;if(j!==L)return j-L;let U=I.dom?.bbox.x??0,N=B.dom?.bbox.x??0;return U-N}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((I,B)=>{let j=I.ax.role??"generic",L=I.ax.name??"",U=WN(j,L,B),N=I.dom?.bbox??{x:0,y:0,w:0,h:0},P=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)),ZS({role:j,kind:P})&&(F="[redacted]");let W={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(W.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(W.selected=I.ax.selected),I.ax.expanded!==void 0&&(W.expanded=I.ax.expanded);let J;I.dom?.testId?J=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(J=`#${I.dom.id}`);let Z={id:U,role:j,label:jN(L),kind:P,value:F,state:W,bbox:N};return J!==void 0&&(Z.selector=J),Z}),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=KN(f),S=`obs_${e.observationCounter.toString(36)}`,R=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:R}}var rv,sv,iv=h(()=>{"use strict";Qa();rv=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);sv="a[href], button, input, select, textarea, [role], [tabindex], label"});async function av(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 Dp(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>av(t,s)))).filter(o=>o!==null)}async function JN(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 Fp(t,e,n){switch(e.kind){case"element_id":return VN(t,e,n);case"selector":return YN(t,e);case"semantic":return XN(t,e)}}async function VN(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 Dp(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function YN(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 Dp(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function XN(t,e){return e.role!==void 0?QN(t,e.text,e.role):ZN(t,e.text,e)}async function QN(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 Dp(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function ZN(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 JN(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 av(y.locator,y.index);if(w!==null){let v=`${w.role}:${w.label}:${g}`,A=0;for(let k=0;k<v.length;k++)A=A*31+v.charCodeAt(k)>>>0;f.push({...w,id:`el_${A.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var lv=h(()=>{"use strict"});async function Lp(t,e,n,r){let o=t.url();if(o===n)return null;let s=Ja(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 cv=h(()=>{"use strict";Va()});import{randomBytes as e$}from"crypto";import{mkdir as t$,stat as n$,writeFile as r$}from"fs/promises";import{join as Np}from"path";import{gzip as o$}from"zlib";import{promisify as s$}from"util";function i$(t){return Np(tr(t),"browser")}function a$(t){return Np(i$(t),"screenshots")}function l$(){return new Date().toISOString().replace(/[:.]/g,"-")}function c$(){return e$(3).toString("hex")}async function $p(t,e,n){if(e.length>dv)throw new Error(`writeScreenshotSidecar: buffer exceeds ${dv} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=a$(t);await t$(r,{recursive:!0});let o=`${l$()}-${c$()}-${n}.png`,s=Np(r,o);await r$(s,e);let{size:i}=await n$(s);return{path:s,bytes:i}}var T9,dv,uv=h(()=>{"use strict";H();Qa();T9=s$(o$);dv=5*1024*1024});var fv={};Ed(fv,{PlaywrightProvider:()=>Up});function pv(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 Up,mv=h(()=>{"use strict";QS();iv();lv();Va();cv();uv();Up=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Xa(e)}async open(e){let n=Ja(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 Lp(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 Za(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 Za(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 Fp(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${pv(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 Lp(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 Za(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 Fp(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${pv(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 $p(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 $p(n,o,r);return s}catch{return null}}}});var Hn={};Ed(Hn,{__resetBrowserRegistryForTests:()=>m$,browserProviderActive:()=>p$,closeBrowserProvider:()=>Bp,getBrowserProvider:()=>u$,peekBrowserProvider:()=>f$});function gv(){Promise.resolve(Bp()).then(()=>{process.exit(130)})}function hv(){Promise.resolve(Bp()).then(()=>{process.exit(143)})}function yv(){At=null}function d$(){el||(process.on("SIGINT",gv),process.on("SIGTERM",hv),process.on("exit",yv),el=!0)}function bv(){el&&(process.removeListener("SIGINT",gv),process.removeListener("SIGTERM",hv),process.removeListener("exit",yv),el=!1)}async function u$(t){return At!==null?At:(Bn!==null||(Bn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(mv(),fv)),n=JS(t),r=new e(n);return d$(),At=r,Bn=null,r})()),Bn)}async function Bp(){if(At===null)return;let t=At;At=null,Bn=null,bv(),await t.shutdown()}function p$(){return At!==null}function f$(){return At}function m$(){At=null,Bn=null,bv()}var At,Bn,el,jn=h(()=>{"use strict";Va();At=null,Bn=null,el=!1});async function wv(t,e){try{return await NS(t,e)}catch(n){return D("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function S$(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(jn(),Hn));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}async function Sv(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??S$,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i=t,a=null,l=null;try{let d=await za(n,t,{headers:w$,signal:e.signal},o);a=d.status,i=d.url||t;let u=d.headers.get("content-type")??"";if(d.ok){if(b$.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let p=await d.text();if(y$.test(u)&&!h$.test(u))return{title:"",markdown:p.trim(),finalUrl:i,usedRender:!1};if(s=await wv(p,i),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(d){if(e.signal.aborted||d instanceof ut||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;l=d}if(!(s===null||s.textLength<200)&&s!==null)return{title:s.title,markdown:s.markdown,finalUrl:i,usedRender:!1};try{await Jo(t,o);let d=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:p=>Jo(p,o)});d.finalUrl!==t&&/^https?:\/\//i.test(d.finalUrl)&&await Jo(d.finalUrl,o);let u=await wv(d.html,d.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||u.textLength>=s.textLength)return{title:u.title,markdown:u.markdown,finalUrl:d.finalUrl,usedRender:!0}}catch(d){if(e.signal.aborted||d instanceof ut)throw d;if(s===null){let u=d instanceof Error?d.message:String(d),p=l instanceof Error?l.message:`HTTP ${a??"error"}`,f=new Error(`web_scrape could not retrieve ${t}: fetch failed (${p}) and render failed (${u}).`);throw f.cause=d,f}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:i,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${a??"error"}).`)}var h$,y$,b$,w$,vv=h(()=>{"use strict";$S();Ip();ce();h$=/(text\/html|application\/xhtml\+xml)/i,y$=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,b$=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,w$={"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 E$(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(v$,{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),k$),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=vr(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 kv(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?E$({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 Ev(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
882
882
|
|
|
883
883
|
(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(`
|
|
884
884
|
`).trimEnd()}var v$,k$,Av=h(()=>{"use strict";xn();v$="https://api.exa.ai/search",k$=10});function tl(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 Wn=h(()=>{"use strict";Op()});function C$(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=A$;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,_$)}let a=T$;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,x$)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Hp(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:Lt(t,e),truncated:!0}}function I$(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=C$(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 Cp(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 za(e,i.url,g,r)}catch(g){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:g instanceof ut?{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=Hp(f,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let p=await Sv(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=Hp(p.markdown,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 ut)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),m=Oe(p)&&!Pp(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Vo()}\`)`:"";return{content:`web_scrape markdown error: ${f}${m}`,isError:!0}}let u=kv({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:R$,timeoutMs:i.timeoutMs,signal:a.signal}),f=Hp(Ev(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 A$,_$,T$,x$,R$,_v,Tv=h(()=>{"use strict";vv();Av();Ip();On();Wn();A$=3e4,_$=12e4,T$=1e5,x$=1e6,R$=10;_v=I$()});import{existsSync as Rv,mkdirSync as P$,readFileSync as M$,renameSync as O$,unlinkSync as D$,writeFileSync as F$}from"node:fs";import{dirname as xv,join as L$}from"node:path";import{randomBytes as N$}from"node:crypto";function Ir(t){let e=t??Rd();if(!Rv(e))return[];try{let n=M$(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 nl(t,e){let n=e??Rd();P$(xv(n),{recursive:!0});let r=L$(xv(n),`.schedules.json.${process.pid}.${N$(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{F$(r,o,"utf-8"),O$(r,n)}catch(s){try{Rv(r)&&D$(r)}catch{}throw s}}function Cv(t,e){let n=Ir(e),r=n.map(l=>l.id),o=$$(t.name),s=U$(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),nl(n,e),a}function Iv(t,e){let n=Ir(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(nl(o,e),!0)}function Pv(t,e){return Ir(e).find(n=>n.id===t)}function $$(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function U$(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}var Mv=h(()=>{"use strict";H()});import{existsSync as B$,readFileSync as H$}from"node:fs";import{join as j$}from"node:path";async function Yo(t,e,n){let r;try{let o=j$(sh("default"),"port");if(!B$(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let s=H$(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 jp,Ov=h(()=>{"use strict";H();jp="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 W$}from"node:fs";import{readFile as K$}from"node:fs/promises";var Dv,Fv,Lv,Nv,$v=h(()=>{"use strict";Mv();H();Ov();Dv=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=Cv({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 Yo("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 Yo("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:jp}})}},Fv=async(t,e)=>{let n=Ir();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})))}},Lv=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=ai();if(!W$(s))return{content:JSON.stringify([])};let i;try{let c=await K$(s);i=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-afk",
|
|
3
|
-
"version": "5.95.
|
|
3
|
+
"version": "5.95.7",
|
|
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",
|