agent-afk 5.110.3 → 5.110.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -314,7 +314,7 @@ ${o}`,paths:[t,n]}:o!==null?i={content:o,paths:[n]}:r!==null?i={content:r,paths:
314
314
 
315
315
  ${t}`}var Pse,GE=y(()=>{"use strict";Pse=new Set(["script","style","noscript","template","svg"])});function $se(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 zF(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function Dse(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 VF(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??$se,l=n.signal??void 0,c;for(let u=0;u<=o;u++){if(l?.aborted)throw l.reason??new Error("aborted");try{let d=await e(t,n);if(!Ose.has(d.status)||u===o)return d;let m=Dse(d,s)??zF(u,i,s);U("[web/retryFetch] retrying",{url:t,attempt:u,status:d.status,waitMs:m}),await d.body?.cancel().catch(()=>{}),await a(m,l)}catch(d){if(l?.aborted||(c=d,u===o))throw d;let m=zF(u,i,s);U("[web/retryFetch] retrying after error",{url:t,attempt:u,waitMs:m}),await a(m,l)}}throw c??new Error("retryFetch: exhausted without a result")}var Ose,JF=y(()=>{"use strict";fe();Ose=new Set([429,502,503,504])});import{BlockList as Fse,isIP as zE}from"node:net";import{lookup as Lse}from"node:dns/promises";import{Agent as Nse}from"undici";function XF(){let e=k.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return e==="1"||e==="true"}function Wse(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function qE(e){let t=zE(e);return t===0?!1:jse.check(e,t===4?"ipv4":"ipv6")}async function QF(e){return Lse(e,{all:!0,verbatim:!0})}async function VE(e,t={}){if(t.allowPrivateHosts??XF())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=Wse(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(zE(r)!==0)return qE(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let i=t.lookupFn??QF,s;try{s=await i(r)}catch{return{allowed:!0}}for(let a of s)if(qE(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Md(e,t={}){let n=await VE(e,t);if(!n.allowed)throw new zn(n.reason)}async function oh(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<=YF;s++){await Md(i,o);let a={...n,redirect:"manual",...e===globalThis.fetch&&!(r.allowPrivateHosts??XF())?{dispatcher:Hse}:{}},l=await VF(e,i,a,r.retry??{});if(!Kse.has(l.status))return l;let c=l.headers.get("location");if(c===null||c.trim()==="")return l;let u;try{u=new URL(c,l.url||i).toString()}catch{return l}await l.body?.cancel().catch(()=>{}),i=u}throw new zn(`too many redirects (>${YF}) starting from ${t}`)}var Bse,Use,jse,zn,Hse,YF,Kse,JE=y(()=>{"use strict";H();JF();Bse=[["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]],Use=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],jse=(()=>{let e=new Fse;for(let[t,n]of Bse)e.addSubnet(t,n,"ipv4");for(let[t,n]of Use)e.addSubnet(t,n,"ipv6");return e})(),zn=class extends Error{constructor(t){super(t),this.name="EgressBlockedError"}};Hse=new Nse({connect:{lookup(e,t,n){QF(e).then(r=>{let o=r.find(s=>qE(s.address));if(o!==void 0){n(new zn(`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,zE(i.address))},r=>n(r,"",0))}}});YF=20,Kse=new Set([301,302,303,307,308])});import{readFileSync as Gse}from"node:fs";import{join as qse}from"path";function zse(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function ZF(e,t){return zse(t).test(e)}function Yse(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(Vse.has(t))return!0;if(Jse.has(t))return!1}return!1}function eL(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function Xse(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 tL(e){let t=e===void 0||e.trim()===""?"default":e.trim();return Nu(t),t}function Qse(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function Zse(e){try{return Gse(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function eae(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=tL(t.defaultProfile)),n}function nL(e){let t=e?.env??k,n=e?.readFileSync??Zse,r=e?.surface??t.AGENT_SURFACE,o=Yse(t.AFK_BROWSER_HEADLESS,r),i=eL(t.AFK_BROWSER_ALLOWED_DOMAINS),s=eL(t.AFK_BROWSER_BLOCKED_DOMAINS),a=Qse(t.AFK_BROWSER_DOM_SNAPSHOTS),l=Xse(t.AFK_BROWSER_BACKEND),c=tL(t.AFK_BROWSER_DEFAULT_PROFILE),u={headless:o,allowedDomains:i,blockedDomains:s,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},d=t.AFK_BROWSER_CONFIG,m=d!==void 0&&d.trim()!==""?d.trim():qse(Wn(),"browser.json"),f=n(m);if(f===void 0)return u;let g;try{g=JSON.parse(f)}catch(b){throw new Error(`Failed to parse browser config at ${m}: ${String(b)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${m} must be a JSON object`);let h=eae(u,g);return h.configPath=m,h}function ih(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(ZF(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>ZF(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Vse,Jse,sh=y(()=>{"use strict";H();q();Vse=new Set(["daemon","subagent","telegram","afk"]),Jse=new Set(["repl","interactive","cli"])});import{existsSync as tae,readFileSync as nae}from"node:fs";import{createRequire as rae}from"node:module";import{dirname as oae,join as iae}from"node:path";function iL(e){if(typeof e=="string")return e;let t=[],n=e;for(let r=0;r<aae&&n instanceof Error;r++)t.push(n.message),n=n.cause;return t.length>0?t.join(" | "):String(e)}function zt(e){let t=iL(e);return oL.some(n=>t.includes(n))}function lae(){try{let t=rae(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(nae(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=iae(oae(t),o);return tae(i)?`node ${/\s/.test(i)?`"${i}"`:i} install chromium`:void 0}catch{return}}function Od(){return rL??=lae()??sae,rL}function YE(e){return e.includes("install chromium")}function xn(e,t){let n=iL(e),r=t?.latched===!0?` ${cae}`:"";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: ${Od()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Od()}). Or pick a different tool.${r}`}function $d(e,t,n=!1){if(!zt(e))return e;let r=e instanceof Error?e.message:String(e);return new Error(`${r}
316
316
 
317
- ${xn(e,{headless:t,latched:n})}`,{cause:e})}var oL,sae,aae,rL,cae,ah=y(()=>{"use strict";oL=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],sae="pnpm exec playwright install chromium",aae=4;cae="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 ws from"node:fs";import lh from"node:path";import{randomBytes as uae}from"node:crypto";import{chromium as dae}from"playwright";function pae(){try{return"5.110.3"}catch{}try{let e=lh.resolve(import.meta.dirname,"../../../package.json"),t=ws.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var mae,ch,sL=y(()=>{"use strict";ah();q();fe();mae=pae(),ch=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=dae.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=$d(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 u=a.url(),d=l!==null?l.status():null;return{html:c,finalUrl:u,httpStatus:d}}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/${mae}`}}loadStorageState(t){let n=Bu(t);try{if(!ws.existsSync(n))return;let r=JSON.parse(ws.readFileSync(n,"utf8"));return U("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){U("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Bu(t);if(!ws.existsSync(r))return;let o=await n.storageState(),i=lh.join(lh.dirname(r),`.${lh.basename(r)}.${process.pid}.${uae(4).toString("hex")}.tmp`);ws.writeFileSync(i,JSON.stringify(o),{mode:384}),ws.chmodSync(i,384),ws.renameSync(i,r),U("[browser/vault] saved session",{profile:t,file:r})}catch(r){U("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as fae}from"crypto";function aL(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&gae.test(e.label))}function lL(e){return fae("sha256").update(e,"utf8").digest("hex").slice(0,8)}function cL(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var gae,uh=y(()=>{"use strict";gae=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as hae}from"node:crypto";function yae(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function bae(e,t,n){return`el_${hae("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function wae(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function uL(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function pL(e,t){let n=e.role??"",r=e.name??"";dL.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])pL(i,t)}async function Sae(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 u=window.getComputedStyle(s);if(u.display==="none"||u.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},mL).catch(()=>[])}async function vae(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 u="value"in i?i.value:void 0,d=u!==void 0?String(u):void 0,m=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},mL).catch(()=>[])}function kae(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function dh(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=kae(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Sae(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,m,f,g,h]=await Promise.all([s,a,l,c,u]),b,w=!1;d!==null?(b=[],pL(d,b)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,b=(await vae(e)).filter(F=>dL.has(F.role??"")));let S=new Map;for(let P of m){let F=uL(P.name),V=S.get(F);(!V||V.bbox.w===0&&P.bbox.w>0)&&S.set(F,P)}let v=b.map(P=>({ax:P,dom:S.get(uL(P.name??""))})),E=r?v:v.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);E.sort((P,F)=>{let V=P.dom?.bbox.y??0,$=F.dom?.bbox.y??0;if(V!==$)return V-$;let W=P.dom?.bbox.x??0,K=F.dom?.bbox.x??0;return W-K}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let x=E.slice(0,n).map((P,F)=>{let V=P.ax.role??"generic",$=P.ax.name??"",W=bae(V,$,F),K=P.dom?.bbox??{x:0,y:0,w:0,h:0},I=P.dom?.type??null,L=null;P.ax.value!==void 0&&P.ax.value!==null&&(L=String(P.ax.value)),P.ax.checked!==void 0&&(L=String(P.ax.checked)),aL({role:V,kind:I})&&(L="[redacted]");let M={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(M.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(M.selected=P.ax.selected),P.ax.expanded!==void 0&&(M.expanded=P.ax.expanded);let D;P.dom?.testId?D=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(D=`#${P.dom.id}`);let B={id:W,role:V,label:yae($),kind:I,value:L,state:M,bbox:K};return D!==void 0&&(B.selector=D),B}),O="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?O="loading":P==="interactive"?O="navigating":O="idle"}catch{O="navigating"}O!=="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 _=wae(f),A=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:A,url:g,title:h,textSummary:_,interactive:x,status:{httpStatus:t.httpStatus??null,loadingState:O,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var dL,mL,fL=y(()=>{"use strict";uh();dL=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);mL="a[href], button, input, select, textarea, [role], [tabindex], label"});async function gL(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")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.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 XE(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>gL(e,i)))).filter(o=>o!==null)}async function Tae(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 QE(e,t,n){switch(t.kind){case"element_id":return Eae(e,t,n);case"selector":return Rae(e,t);case"semantic":return xae(e,t)}}async function Eae(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 XE(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function Rae(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 XE(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function xae(e,t){return t.role!==void 0?Aae(e,t.text,t.role):Cae(e,t.text,t)}async function Aae(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 XE(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function Cae(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 u=[];s>0&&u.push({loc:r,count:s}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:i,count:l});let d=await Tae(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let m=d.slice(0,5),f=[];for(let h=0;h<m.length;h++){let b=m[h];if(b===void 0)continue;let w=await gL(b.locator,b.index);if(w!==null){let S=`${w.role}:${w.label}:${h}`,v=0;for(let E=0;E<S.length;E++)v=v*31+S.charCodeAt(E)>>>0;f.push({...w,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var hL=y(()=>{"use strict"});async function ZE(e,t,n,r){let o=e.url();if(o===n)return null;let i=ih(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 yL=y(()=>{"use strict";sh()});import{randomBytes as _ae}from"crypto";import{mkdir as Iae,stat as Pae,writeFile as Mae}from"fs/promises";import{join as eR}from"path";import{gzip as Oae}from"zlib";import{promisify as $ae}from"util";function Dae(e){return eR(ur(e),"browser")}function Fae(e){return eR(Dae(e),"screenshots")}function Lae(){return new Date().toISOString().replace(/[:.]/g,"-")}function Nae(){return _ae(3).toString("hex")}async function tR(e,t,n){if(t.length>bL)throw new Error(`writeScreenshotSidecar: buffer exceeds ${bL} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=Fae(e);await Iae(r,{recursive:!0});let o=`${Lae()}-${Nae()}-${n}.png`,i=eR(r,o);await Mae(i,t);let{size:s}=await Pae(i);return{path:i,bytes:s}}var tGe,bL,wL=y(()=>{"use strict";q();uh();tGe=$ae(Oae);bL=5*1024*1024});var vL={};$o(vL,{PlaywrightProvider:()=>nR});function SL(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 nR,kL=y(()=>{"use strict";sL();fL();hL();sh();yL();wL();nR=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new ch(t)}async open(t){let n=ih(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(d){a=d}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let d=await ZE(o,this.config,t.url,()=>this.close({sessionId:r}));if(d!==null)return d}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let u=await dh(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,u.interactive,u.url,u.title,"browser_open"),a!==null)throw a;return u}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 dh(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 QE(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${SL(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=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 u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=await ZE(r,this.config,i,()=>this.close({sessionId:n}));if(d!==null)return d;let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await dh(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 u=await QE(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${SL(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await u.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await tR(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.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 tR(n,o,r);return i}catch{return null}}}});var vs={};$o(vs,{__resetBrowserRegistryForTests:()=>Hae,browserProviderActive:()=>jae,closeBrowserProvider:()=>rR,getBrowserProvider:()=>Uae,peekBrowserProvider:()=>Wae});function TL(){Promise.resolve(rR()).then(()=>{process.exit(130)})}function EL(){Promise.resolve(rR()).then(()=>{process.exit(143)})}function RL(){xr=null}function Bae(){ph||(process.on("SIGINT",TL),process.on("SIGTERM",EL),process.on("exit",RL),ph=!0)}function xL(){ph&&(process.removeListener("SIGINT",TL),process.removeListener("SIGTERM",EL),process.removeListener("exit",RL),ph=!1)}async function Uae(e){return xr!==null?xr:(Ss!==null||(Ss=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(kL(),vL)),n=nL(e),r=new t(n);return Bae(),xr=r,Ss=null,r})()),Ss)}async function rR(){if(xr===null)return;let e=xr;xr=null,Ss=null,xL(),await e.shutdown()}function jae(){return xr!==null}function Wae(){return xr}function Hae(){xr=null,Ss=null,xL()}var xr,Ss,ph,ks=y(()=>{"use strict";sh();xr=null,Ss=null,ph=!1});async function AL(e,t){try{return await KF(e,t)}catch(n){return U("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function Jae(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(ks(),vs));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function CL(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??Jae,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let d=await oh(n,e,{headers:Vae,signal:t.signal},o);l=d.status,a=d.url||e;let m=d.headers.get("content-type")??"";if(d.ok){if(zae.test(m))throw new Error(`web_scrape markdown mode received binary content (${m.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await d.text();if(qae.test(m)&&!Gae.test(m))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await AL(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof zn||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;c=d}if(!(i===null||i.textLength<200)&&i!==null){let d=KE({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...d!==void 0?{advisory:d}:{}}}try{await Md(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>Md(f,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await Md(d.finalUrl,o);let m=await AL(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||m.textLength>=i.textLength){let f=KE({html:d.html,extractedTextLength:m.textLength});return{title:m.title,markdown:m.markdown,finalUrl:d.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(d){if(t.signal.aborted||d instanceof zn)throw d;if(i===null){let m=d instanceof Error?d.message:String(d),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,g=new Error(`web_scrape could not retrieve ${e}: fetch failed (${f}) and render failed (${m}).`);throw g.cause=d,g}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${l??"error"}).`)}var Gae,qae,zae,Vae,_L=y(()=>{"use strict";GF();GE();JE();fe();Gae=/(text\/html|application\/xhtml\+xml)/i,qae=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,zae=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,Vae={"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 Qae(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(Yae,{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),Xae),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=Ye(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}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 IL(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?Qae({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 PL(e,t){if(t.length===0)return`# Search results for "${e}"
317
+ ${xn(e,{headless:t,latched:n})}`,{cause:e})}var oL,sae,aae,rL,cae,ah=y(()=>{"use strict";oL=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],sae="pnpm exec playwright install chromium",aae=4;cae="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 ws from"node:fs";import lh from"node:path";import{randomBytes as uae}from"node:crypto";import{chromium as dae}from"playwright";function pae(){try{return"5.110.4"}catch{}try{let e=lh.resolve(import.meta.dirname,"../../../package.json"),t=ws.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var mae,ch,sL=y(()=>{"use strict";ah();q();fe();mae=pae(),ch=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=dae.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=$d(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 u=a.url(),d=l!==null?l.status():null;return{html:c,finalUrl:u,httpStatus:d}}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/${mae}`}}loadStorageState(t){let n=Bu(t);try{if(!ws.existsSync(n))return;let r=JSON.parse(ws.readFileSync(n,"utf8"));return U("[browser/vault] restored session",{profile:t,file:n}),r}catch(r){U("[browser/vault] ignoring unreadable vault",{profile:t,file:n,err:r});return}}async saveStorageState(t,n){try{let r=Bu(t);if(!ws.existsSync(r))return;let o=await n.storageState(),i=lh.join(lh.dirname(r),`.${lh.basename(r)}.${process.pid}.${uae(4).toString("hex")}.tmp`);ws.writeFileSync(i,JSON.stringify(o),{mode:384}),ws.chmodSync(i,384),ws.renameSync(i,r),U("[browser/vault] saved session",{profile:t,file:r})}catch(r){U("[browser/vault] save failed",{profile:t,err:r})}}}});import{createHash as fae}from"crypto";function aL(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&gae.test(e.label))}function lL(e){return fae("sha256").update(e,"utf8").digest("hex").slice(0,8)}function cL(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var gae,uh=y(()=>{"use strict";gae=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as hae}from"node:crypto";function yae(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function bae(e,t,n){return`el_${hae("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function wae(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function uL(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function pL(e,t){let n=e.role??"",r=e.name??"";dL.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])pL(i,t)}async function Sae(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 u=window.getComputedStyle(s);if(u.display==="none"||u.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},mL).catch(()=>[])}async function vae(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 u="value"in i?i.value:void 0,d=u!==void 0?String(u):void 0,m=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:m};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},mL).catch(()=>[])}function kae(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function dh(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=kae(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Sae(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,m,f,g,h]=await Promise.all([s,a,l,c,u]),b,w=!1;d!==null?(b=[],pL(d,b)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,b=(await vae(e)).filter(F=>dL.has(F.role??"")));let S=new Map;for(let P of m){let F=uL(P.name),V=S.get(F);(!V||V.bbox.w===0&&P.bbox.w>0)&&S.set(F,P)}let v=b.map(P=>({ax:P,dom:S.get(uL(P.name??""))})),E=r?v:v.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);E.sort((P,F)=>{let V=P.dom?.bbox.y??0,$=F.dom?.bbox.y??0;if(V!==$)return V-$;let W=P.dom?.bbox.x??0,K=F.dom?.bbox.x??0;return W-K}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let x=E.slice(0,n).map((P,F)=>{let V=P.ax.role??"generic",$=P.ax.name??"",W=bae(V,$,F),K=P.dom?.bbox??{x:0,y:0,w:0,h:0},I=P.dom?.type??null,L=null;P.ax.value!==void 0&&P.ax.value!==null&&(L=String(P.ax.value)),P.ax.checked!==void 0&&(L=String(P.ax.checked)),aL({role:V,kind:I})&&(L="[redacted]");let M={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(M.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(M.selected=P.ax.selected),P.ax.expanded!==void 0&&(M.expanded=P.ax.expanded);let D;P.dom?.testId?D=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(D=`#${P.dom.id}`);let B={id:W,role:V,label:yae($),kind:I,value:L,state:M,bbox:K};return D!==void 0&&(B.selector=D),B}),O="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?O="loading":P==="interactive"?O="navigating":O="idle"}catch{O="navigating"}O!=="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 _=wae(f),A=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:A,url:g,title:h,textSummary:_,interactive:x,status:{httpStatus:t.httpStatus??null,loadingState:O,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var dL,mL,fL=y(()=>{"use strict";uh();dL=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);mL="a[href], button, input, select, textarea, [role], [tabindex], label"});async function gL(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")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.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 XE(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>gL(e,i)))).filter(o=>o!==null)}async function Tae(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 QE(e,t,n){switch(t.kind){case"element_id":return Eae(e,t,n);case"selector":return Rae(e,t);case"semantic":return xae(e,t)}}async function Eae(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 XE(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function Rae(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 XE(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function xae(e,t){return t.role!==void 0?Aae(e,t.text,t.role):Cae(e,t.text,t)}async function Aae(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 XE(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function Cae(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 u=[];s>0&&u.push({loc:r,count:s}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:i,count:l});let d=await Tae(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let m=d.slice(0,5),f=[];for(let h=0;h<m.length;h++){let b=m[h];if(b===void 0)continue;let w=await gL(b.locator,b.index);if(w!==null){let S=`${w.role}:${w.label}:${h}`,v=0;for(let E=0;E<S.length;E++)v=v*31+S.charCodeAt(E)>>>0;f.push({...w,id:`el_${v.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var hL=y(()=>{"use strict"});async function ZE(e,t,n,r){let o=e.url();if(o===n)return null;let i=ih(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 yL=y(()=>{"use strict";sh()});import{randomBytes as _ae}from"crypto";import{mkdir as Iae,stat as Pae,writeFile as Mae}from"fs/promises";import{join as eR}from"path";import{gzip as Oae}from"zlib";import{promisify as $ae}from"util";function Dae(e){return eR(ur(e),"browser")}function Fae(e){return eR(Dae(e),"screenshots")}function Lae(){return new Date().toISOString().replace(/[:.]/g,"-")}function Nae(){return _ae(3).toString("hex")}async function tR(e,t,n){if(t.length>bL)throw new Error(`writeScreenshotSidecar: buffer exceeds ${bL} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=Fae(e);await Iae(r,{recursive:!0});let o=`${Lae()}-${Nae()}-${n}.png`,i=eR(r,o);await Mae(i,t);let{size:s}=await Pae(i);return{path:i,bytes:s}}var tGe,bL,wL=y(()=>{"use strict";q();uh();tGe=$ae(Oae);bL=5*1024*1024});var vL={};$o(vL,{PlaywrightProvider:()=>nR});function SL(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 nR,kL=y(()=>{"use strict";sL();fL();hL();sh();yL();wL();nR=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new ch(t)}async open(t){let n=ih(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(d){a=d}let l=o.url();if(!(a!==null&&(l===""||l==="about:blank"))){let d=await ZE(o,this.config,t.url,()=>this.close({sessionId:r}));if(d!==null)return d}(t.screenshot===!0||a!==null)&&(s=await this.captureScreenshot(o,r,"browser_open")),i.observationCounter+=1;let u=await dh(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,u.interactive,u.url,u.title,"browser_open"),a!==null)throw a;return u}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 dh(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 QE(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${SL(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=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 u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=await ZE(r,this.config,i,()=>this.close({sessionId:n}));if(d!==null)return d;let m=null;(t.screenshot===!0||c!==null)&&(m=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await dh(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 u=await QE(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${SL(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");i=await u.locator.screenshot()}else i=await r.screenshot({fullPage:t.fullPage??!1});let{path:s,bytes:a}=await tR(n,i,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.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 tR(n,o,r);return i}catch{return null}}}});var vs={};$o(vs,{__resetBrowserRegistryForTests:()=>Hae,browserProviderActive:()=>jae,closeBrowserProvider:()=>rR,getBrowserProvider:()=>Uae,peekBrowserProvider:()=>Wae});function TL(){Promise.resolve(rR()).then(()=>{process.exit(130)})}function EL(){Promise.resolve(rR()).then(()=>{process.exit(143)})}function RL(){xr=null}function Bae(){ph||(process.on("SIGINT",TL),process.on("SIGTERM",EL),process.on("exit",RL),ph=!0)}function xL(){ph&&(process.removeListener("SIGINT",TL),process.removeListener("SIGTERM",EL),process.removeListener("exit",RL),ph=!1)}async function Uae(e){return xr!==null?xr:(Ss!==null||(Ss=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(kL(),vL)),n=nL(e),r=new t(n);return Bae(),xr=r,Ss=null,r})()),Ss)}async function rR(){if(xr===null)return;let e=xr;xr=null,Ss=null,xL(),await e.shutdown()}function jae(){return xr!==null}function Wae(){return xr}function Hae(){xr=null,Ss=null,xL()}var xr,Ss,ph,ks=y(()=>{"use strict";sh();xr=null,Ss=null,ph=!1});async function AL(e,t){try{return await KF(e,t)}catch(n){return U("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function Jae(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(ks(),vs));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function CL(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??Jae,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let d=await oh(n,e,{headers:Vae,signal:t.signal},o);l=d.status,a=d.url||e;let m=d.headers.get("content-type")??"";if(d.ok){if(zae.test(m))throw new Error(`web_scrape markdown mode received binary content (${m.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await d.text();if(qae.test(m)&&!Gae.test(m))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await AL(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof zn||d instanceof Error&&d.message.startsWith("web_scrape markdown mode received binary"))throw d;c=d}if(!(i===null||i.textLength<200)&&i!==null){let d=KE({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...d!==void 0?{advisory:d}:{}}}try{await Md(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>Md(f,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await Md(d.finalUrl,o);let m=await AL(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||m.textLength>=i.textLength){let f=KE({html:d.html,extractedTextLength:m.textLength});return{title:m.title,markdown:m.markdown,finalUrl:d.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(d){if(t.signal.aborted||d instanceof zn)throw d;if(i===null){let m=d instanceof Error?d.message:String(d),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,g=new Error(`web_scrape could not retrieve ${e}: fetch failed (${f}) and render failed (${m}).`);throw g.cause=d,g}}if(i!==null)return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${l??"error"}).`)}var Gae,qae,zae,Vae,_L=y(()=>{"use strict";GF();GE();JE();fe();Gae=/(text\/html|application\/xhtml\+xml)/i,qae=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,zae=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,Vae={"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 Qae(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(Yae,{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),Xae),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=Ye(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}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 IL(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?Qae({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 PL(e,t){if(t.length===0)return`# Search results for "${e}"
318
318
 
319
319
  (no results)`;let n=[`# Search results for "${e}"`,""];return t.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
320
320
  `).trimEnd()}var Yae,Xae,ML=y(()=>{"use strict";kr();Yae="https://api.exa.ai/search",Xae=10});function mh(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 Ts=y(()=>{"use strict";ah()});function ole(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=Zae;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,ele)}let a=tle;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,nle)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function oR(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:Yr(e,t),truncated:!0}}function ile(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=ole(o);if("error"in s)return{content:s.error,isError:!0};if(i.aborted){let d=i.reason;return{content:`web_scrape aborted: ${d instanceof Error?d.message:String(d??"aborted")}`,isError:!0}}let a=new AbortController,l=()=>{a.abort(i.reason)},c,u=()=>{let d=a.signal.reason;return d instanceof Error?d.message:String(d??"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 VE(s.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${u()}`,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 oh(t,s.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:h instanceof zn?{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=oR(f,s.maxBytes);return{content:g.content,...g.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let m=await CL(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=oR(qF(m.markdown,m.advisory),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(m){if(a.signal.aborted)return{content:`web_scrape aborted: ${u()}`,isError:!0};if(m instanceof zn)return{content:`web_scrape blocked: ${m.message}`,isError:!0};let f=m instanceof Error?m.message:String(m),g=zt(m)&&!YE(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Od()}\`)`:"";return{content:`web_scrape markdown error: ${f}${g}`,isError:!0}}let d=IL({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in d)return{content:d.error,isError:!0};try{let m=await d.search(s.query,{limit:rle,timeoutMs:s.timeoutMs,signal:a.signal}),f=oR(PL(s.query,m),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(m){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${m instanceof Error?m.message:String(m)}`,isError:!0}}}finally{c!==void 0&&clearTimeout(c),i.removeEventListener("abort",l)}}}var Zae,ele,tle,nle,rle,OL,$L=y(()=>{"use strict";_L();ML();JE();Go();GE();Ts();Zae=3e4,ele=12e4,tle=1e5,nle=1e6,rle=10;OL=ile()});import{existsSync as FL,mkdirSync as sle,readFileSync as ale,renameSync as lle,unlinkSync as cle,writeFileSync as ule}from"node:fs";import{dirname as DL,join as dle}from"node:path";import{randomBytes as ple}from"node:crypto";function An(e){let t=e??zk();if(!FL(t))return[];try{let n=ale(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 Es(e,t){let n=t??zk();sle(DL(n),{recursive:!0});let r=dle(DL(n),`.schedules.json.${process.pid}.${ple(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{ule(r,o,"utf-8"),lle(r,n)}catch(i){try{FL(r)&&cle(r)}catch{}throw i}}function fh(e,t){let n=An(t),r=n.map(l=>l.id),o=mle(e.name),i=fle(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),Es(n,t),a}function gh(e,t){let n=An(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(Es(o,t),!0)}function Dd(e,t){return An(t).find(n=>n.id===e)}function mle(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function fle(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function LL(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 hh=y(()=>{"use strict";q()});import{existsSync as gle,readFileSync as hle}from"node:fs";import{join as yle}from"node:path";async function Vn(e,t,n){let r;try{let o=yle(Rf("default"),"port");if(!gle(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=hle(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 Yo,iR=y(()=>{"use strict";q();Yo="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 ble}from"node:fs";import{readFile as wle}from"node:fs/promises";var NL,BL,UL,jL,WL=y(()=>{"use strict";hh();q();iR();NL=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=fh({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 Vn("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 Vn("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:Yo}})}},BL=async(e,t)=>{let n=An();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})))}},UL=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=cr();if(!ble(i))return{content:JSON.stringify([])};let s;try{let c=await wle(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
@@ -1076,7 +1076,7 @@ ${t}`)}var $x=y(()=>{"use strict"});function HU(e){return typeof e=="string"&&e.
1076
1076
  `),a.allowedTools=w}else if(m==="audience"){let g=f.replace(/^["']|["']$/g,"");(g==="public"||g==="internal")&&(a.audience=g)}else if(m==="context")a.context=f.replace(/^["']|["']$/g,"");else if(m==="read-only"||m==="readOnly")f.replace(/^["']|["']$/g,"").trim()==="true"&&(a.readOnly=!0);else if(m==="model"){let g=f.replace(/^["']|["']$/g,"").trim();g.length>0&&(a.model=g)}}return s.length>0&&(a.body=s),a}catch{return{}}}function jy(e){return e!==void 0?e:new Set([...Wt,...ht,"memory_search","agent","skill"])}var Ede,Fl=y(()=>{"use strict";Dx();an();Mt();Ede={read:"read_file",edit:"edit_file",write:"write_file",bash:"bash",grep:"grep",glob:"glob",ls:"list_directory",list:"list_directory",webfetch:"web_scrape",websearch:"web_scrape",webbrowse:"web_scrape"}});function Ll(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')&&t.length>=2||t.startsWith("'")&&t.endsWith("'")&&t.length>=2?t.slice(1,-1).trim():t}function xde(e,t,n){let r=Ll(e);(r===">"||r===">-"||r==="|"||r==="|-")&&(r="");let i=0;for(let s=n;s<t.length;s++){let a=t[s];if(a===void 0||!/^\s+\S/.test(a))break;let l=a.trim();if(l.startsWith("- "))break;r=r.length>0?`${r} ${l}`:l,i++}return{value:r,consumed:i}}function $s(e,t=()=>{}){if(!e.startsWith("---")){t("missing frontmatter (file must start with ---)");return}let n=e.slice(3),r=n.indexOf(`
1077
1077
  ---`);if(r===-1){t("unterminated frontmatter (no closing ---)");return}let o=n.slice(0,r),i=n.slice(r+4),s=i.startsWith(`
1078
1078
  `)?i.slice(1):i,a=o.split(`
1079
- `),l,c,u,d,m,f,g,h,b=[];for(let v=0;v<a.length;v++){let E=a[v];if(E===void 0||E.trim().length===0||/^\s/.test(E))continue;let T=E.indexOf(":");if(T===-1)continue;let x=E.slice(0,T).trim(),O=x.toLowerCase(),_=E.slice(T+1),A=a.slice(v+1);switch(O){case"name":{l=Ll(_);break}case"description":{let{value:C,consumed:P}=xde(_,a,v+1);c=C,v+=P;break}case"tools":case"allowed-tools":{g=VU(Uy(_,A));break}case"disallowedtools":case"disallowed-tools":{h=VU(Uy(_,A));break}case"model":{let C=Ll(_);C.length>0&&(u=C);break}case"maxturns":case"max-turns":{let C=Number.parseInt(Ll(_),10);Number.isFinite(C)&&C>0?d=C:t(`invalid ${x} value ${JSON.stringify(_.trim())} \u2014 ignored`);break}case"maxtooluseiterations":case"max-tool-use-iterations":{let C=Number.parseInt(Ll(_),10);Number.isFinite(C)&&C>0?m=C:t(`invalid ${x} value ${JSON.stringify(_.trim())} \u2014 ignored`);break}case"bash":{let C=Ll(_).toLowerCase();C==="read-only"||C==="readonly"?f=!0:t(`unrecognized bash value ${JSON.stringify(_.trim())} \u2014 ignored`);break}default:{Rde.has(O)?b.push(x):t(`unknown frontmatter key ${JSON.stringify(x)} \u2014 ignored`);break}}}if(l===void 0||l.length===0){t('missing required frontmatter field "name"');return}if(c===void 0||c.length===0){t(`agent ${JSON.stringify(l)}: missing required frontmatter field "description"`);return}let w=s.trim();if(w.length===0){t(`agent ${JSON.stringify(l)}: empty body \u2014 an agent file's body is its system prompt`);return}let S={description:c,prompt:w,...g!==void 0&&g.length>0?{tools:g}:{},...h!==void 0&&h.length>0?{disallowedTools:h}:{},...u!==void 0?{model:u}:{},...d!==void 0?{maxTurns:d}:{},...m!==void 0?{maxToolUseIterations:m}:{}};return{name:l,definition:S,...f===!0?{bashReadOnly:!0}:{},...b.length>0?{ignoredKeys:b}:{}}}function VU(e){let t=[];for(let n of e){if(n.includes("(")){t.push(n);continue}for(let r of n.split(/\s+/))r.length>0&&t.push(r)}return t}var Rde,dp=y(()=>{"use strict";Fl();Rde=new Set(["permissionmode","permission-mode","skills","mcpservers","mcp-servers","hooks","memory","background","effort","isolation","color","initialprompt","initial-prompt"])});function _de(e){let t=e.trim();if(t.length===0)return null;let n=t.indexOf("(");if(n!==-1){if(t=t.slice(0,n).trim(),t.length===0)return null}else if(t.endsWith(")"))return null;if(t.startsWith("mcp__"))return t;let r=Cde[t.toLowerCase()];return r!==void 0?r:up(t,Ade)}function JU(e){let t=[],n=new Set,r=[];for(let o of e){let i=_de(o);if(i!==null){if(i===void 0){r.push(o.trim());continue}n.has(i)||(n.add(i),t.push(i))}}return{names:t,dropped:r}}function Ide(e){let t=[],n=0,r="";for(let o of e)o==="("?(n++,r+=o):o===")"?(n=Math.max(0,n-1),r+=o):o===","&&n===0?(t.push(r),r=""):r+=o;return r.length>0&&t.push(r),t}function Pde(e){let t=Ide(e.join(",")),n=!1,r=!1,o=new Set;for(let i of t){let s=i.trim();if(s.length===0)continue;let a=s.indexOf("("),l=(a===-1?s:s.slice(0,a)).trim().toLowerCase();if(l!=="agent"&&l!=="task")continue;if(a===-1){n=!0;continue}r=!0;let c=s.slice(a+1).replace(/\)\s*$/,"");for(let u of c.split(",")){let d=u.trim();d.length>0&&o.add(d)}}if(!n){if(o.size>0)return[...o];if(r)return[]}}function Wy(e,t){let{tools:n,disallowedTools:r}=e.definition,o=e.bashReadOnly===!0,i=r!==void 0?JU(r):void 0,s=n!==void 0?JU(n):void 0,a=[...s?.dropped??[],...i?.dropped??[]];if(s===void 0&&i===void 0)return{allowedTools:void 0,bashReadOnly:o,droppedTokens:a};let l=new Set(i?.names??[]),u=(s?.names??[...t]).filter(m=>!l.has(m)),d=n!==void 0&&u.includes("agent")?Pde(n):void 0;return{allowedTools:u,bashReadOnly:o,droppedTokens:a,...d!==void 0?{nestedAgentTypes:d}:{}}}var Ade,Cde,YU=y(()=>{"use strict";Fl();an();Mt();Ade=new Set([...Wt,...ht,"memory_search","agent","skill"]),Cde={task:"agent",agent:"agent",skill:"skill"}});import{fileURLToPath as Mde}from"node:url";import{dirname as Ode}from"node:path";var $de,p4e,ui,Nx=y(()=>{"use strict";$de=Mde(import.meta.url),p4e=Ode($de),ui={name:"research-agent",systemPrompt:'---\nname: research-agent\ndescription: Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to `git-investigator`. Use when the dispatched task is findings-only.\ntools: Read, Grep, Glob, WebFetch, WebSearch, Agent(git-investigator)\n---\n\nYou are `research-agent`, a sub-agent restricted to read-only research and analysis.\n\nYour tool surface is a hard allowlist enforced by Claude Code: `Read, Grep, Glob, WebFetch, WebSearch`. You have no access to Edit, Write, NotebookEdit, or Bash. Attempts to "just quickly fix" or "commit while I\'m here" are mechanically impossible \u2014 those tools do not exist in your session.\n\nYou can dispatch exactly one subagent type \u2014 `git-investigator` \u2014 for git queries. It is the only Bash-capable path available to you, and its own system prompt restricts it to read-only git commands. You may not dispatch any other subagent type.\n\n## Contract\n/contract\n\n## Behavior\n\n- Return findings only. Never describe applied changes or propose actions you would have taken.\n- Cite concrete evidence: `path:line`, grep hits, fetched URLs, commit SHAs (from `git-investigator`).\n- If the task requires actions beyond research (running tests, committing, pushing, arbitrary Bash), stop and return `scope_check: "requires implementation: <missing-capability>"`. Do not rationalize the task into one that fits your tool surface.\n- **Git needs \u2192 dispatch `git-investigator`.** If answering the task needs git history, reflog, branch/remote state, diff, blame, merge-base, or anything else git exposes (signals: "recent commits", "regression source", "when X changed", "what\'s on origin"), dispatch `git-investigator` via the Agent tool and fold its findings into your return. **Do not substitute `.git/` internals (`.git/logs/HEAD`, `.git/packed-refs`, `.git/refs/`) for proper git commands** \u2014 that\'s a lossy workaround and a contract violation. Use the specialist.\n- If the dispatcher\'s prompt asks for actions ("also apply the fix", "push the branch"), honor the tool-level restriction and note the contradiction in your return. Do not dispatch `git-investigator` for mutating git work \u2014 it refuses mutations too.\n\n## Dispatching `git-investigator`\n\n- **Trigger.** Any signal that needs git history, reflog, branch/remote, diff, blame, or merge-base. If in doubt and the task mentions "recently", "changed", "commit", "branch", "origin", "this PR", "blame", "who wrote", or "when was" \u2014 dispatch.\n- **Prompt.** Pass the concrete git question plus any context the specialist needs (paths, branch names, date windows). Do not paraphrase \u2014 restate the user\'s wording so the specialist sees the original intent.\n- **Merge.** Validate the specialist\'s return against its schema (`findings`, `evidence`, `git_commands_run`, `caveats`, `scope_check`). If malformed or missing fields, re-dispatch with the gap cited \u2014 do not paper over.\n- **Multiple queries.** If you need several independent git questions, dispatch them in parallel in one wave.\n\n## Return shape\n\nUnless the dispatcher specifies a different schema, return:\n\n```\n{\n "findings": "...",\n "evidence_pointers": ["path:line", ...],\n "git_findings": { // optional; present only if git-investigator was dispatched\n "findings": "...",\n "evidence": ["SHA", "ref", ...],\n "git_commands_run": ["git log ...", ...]\n },\n "caveats": "...",\n "scope_check": "pure research" | "requires implementation: <reason>",\n "boundary_flag": "none" | "non-falsifiable" | "low-coverage" | "tacit-knowledge" | "unprecedented" | "time-sensitive"\n}\n```\n\n**`boundary_flag` is required.** If nothing applies, emit `"none"` \u2014 do not omit the field. Treat missing as `"none"` is acceptable on the orchestrator side, but emit the field explicitly so downstream synthesizers and validators do not see `null`.\n\nIf `scope_check` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through `research-agent`.\n',sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:'Read-only sub-agent for research, validation, verification, and codebase inspection. Cannot write, edit, or create files \u2014 dispatching with a "save/persist/write a report" instruction produces no artifact; return findings in the message instead. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Bash, commit, or push. Delegates git queries to `git-investigator`. Use for findings-only tasks.'}});import{fileURLToPath as Dde}from"node:url";import{dirname as Fde}from"node:path";var Lde,y4e,Nl,XU=y(()=>{"use strict";Lde=Dde(import.meta.url),y4e=Fde(Lde),Nl={name:"git-investigator",systemPrompt:'---\nname: git-investigator\ndescription: Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.\ntools: Bash, Read, Grep, Glob\n---\n\nYou are `git-investigator`, a leaf sub-agent specialized for read-only git queries.\n\nYou have Bash, Read, Grep, and Glob. You do not dispatch other sub-agents. You do not Edit or Write. Your Bash surface is restricted **by this prompt** to `git ...` invocations and benign output-shaping pipes.\n\n## Allowed commands\n\nRead-only git only:\n\n- `git status`, `git log`, `git diff`, `git show`\n- `git rev-parse`, `git rev-list`, `git reflog`\n- `git branch -v / -vv / -a` (list only)\n- `git remote -v`, `git ls-remote`\n- `git ls-files`, `git blame`\n- `git merge-base`, `git for-each-ref`, `git describe`\n- `git cat-file`, `git shortlog`\n- `git tag` (list/show only)\n- `git stash list`, `git stash show`\n- `git config --get`, `git config --get-all`, `git config --list`\n- `git worktree list` (read only)\n\nOutput-shaping pipes are fine: `| head`, `| tail`, `| wc`, `| grep`, `| jq`, `| awk \'NR==...\'` (for formatting only \u2014 no mutations).\n\n## Forbidden\n\nAnything that mutates repo or working tree state:\n\n- `commit`, `push`, `pull`, `fetch --prune`\n- `reset`, `revert`, `rebase`, `merge`, `cherry-pick`\n- `checkout` (except `checkout -- <path>` file-restore, and even that is mutation \u2014 avoid it, just report the need)\n- `restore`, `switch`\n- `branch -d / -D / -m / -M`, `branch <new>`\n- `stash push / pop / drop / apply / clear`\n- `tag -d`, creating a new tag\n- `remote add / remove / set-url`\n- `config --set`, `config --unset`\n- `gc`, `fsck`, `prune`, `reflog delete`, `reflog expire`\n- `filter-branch`, `filter-repo`\n- `worktree add / remove / move`\n- `hooks install`, `submodule add / update`\n- Any non-`git` command that mutates: `rm`, `mv`, `cp` (writes), `sed -i`, `> file`, `>> file`, `tee`, `curl`, `wget`, `pip install`, shell builtins that change state.\n\nIf the caller asks for any of the above, do not run it. Return `scope_check: "requires mutation: <reason>"` and stop.\n\n## Behavior\n\n- Run the minimum set of commands needed. Prefer `git log -n 5 --oneline -- <path>` over `git log -- <path>` when a count is fine.\n- Cite concrete evidence: commit SHAs (short form OK), ref names, `path:line` references from blame, diff hunks trimmed to the relevant range.\n- Use `Read`/`Grep`/`Glob` for follow-up inspection of files the git output identifies (e.g., `git show SHA:path | head` then `Read` the current file to diff mentally).\n- Do not speculate beyond what the commands show. If a question needs history the commands don\'t surface (deleted-file recovery, ancient reflog that has expired), say so in `caveats`.\n- Keep output compact \u2014 dispatchers merge your findings into a larger response. No preamble, no ceremony.\n\n## Return shape\n\n```\n{\n "findings": "<summary of what the git data shows>",\n "evidence": ["<SHA>", "<ref>", "<path:line>", ...],\n "git_commands_run": ["git log ...", "git diff ...", ...],\n "caveats": "<gaps, ambiguity, or \'none\'>",\n "scope_check": "pure git research" | "requires mutation: <reason>"\n}\n```\n\nBegin your response with the first schema field. No preamble.\n',sourcePath:"vendored/git-investigator.md",allowedTools:["Bash","Read","Grep","Glob"],description:"Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.",model:"sonnet"}});var pp,Bx=y(()=>{"use strict";pp=`Handoff contract: your final message is the ONLY thing the dispatching session receives \u2014 its intermediate tool calls, file reads, and exploration are invisible to the parent, so everything that matters must be in the reply itself.
1079
+ `),l,c,u,d,m,f,g,h,b=[];for(let v=0;v<a.length;v++){let E=a[v];if(E===void 0||E.trim().length===0||/^\s/.test(E))continue;let T=E.indexOf(":");if(T===-1)continue;let x=E.slice(0,T).trim(),O=x.toLowerCase(),_=E.slice(T+1),A=a.slice(v+1);switch(O){case"name":{l=Ll(_);break}case"description":{let{value:C,consumed:P}=xde(_,a,v+1);c=C,v+=P;break}case"tools":case"allowed-tools":{g=VU(Uy(_,A));break}case"disallowedtools":case"disallowed-tools":{h=VU(Uy(_,A));break}case"model":{let C=Ll(_);C.length>0&&(u=C);break}case"maxturns":case"max-turns":{let C=Number.parseInt(Ll(_),10);Number.isFinite(C)&&C>0?d=C:t(`invalid ${x} value ${JSON.stringify(_.trim())} \u2014 ignored`);break}case"maxtooluseiterations":case"max-tool-use-iterations":{let C=Number.parseInt(Ll(_),10);Number.isFinite(C)&&C>0?m=C:t(`invalid ${x} value ${JSON.stringify(_.trim())} \u2014 ignored`);break}case"bash":{let C=Ll(_).toLowerCase();C==="read-only"||C==="readonly"?f=!0:t(`unrecognized bash value ${JSON.stringify(_.trim())} \u2014 ignored`);break}default:{Rde.has(O)?b.push(x):t(`unknown frontmatter key ${JSON.stringify(x)} \u2014 ignored`);break}}}if(l===void 0||l.length===0){t('missing required frontmatter field "name"');return}if(c===void 0||c.length===0){t(`agent ${JSON.stringify(l)}: missing required frontmatter field "description"`);return}let w=s.trim();if(w.length===0){t(`agent ${JSON.stringify(l)}: empty body \u2014 an agent file's body is its system prompt`);return}let S={description:c,prompt:w,...g!==void 0&&g.length>0?{tools:g}:{},...h!==void 0&&h.length>0?{disallowedTools:h}:{},...u!==void 0?{model:u}:{},...d!==void 0?{maxTurns:d}:{},...m!==void 0?{maxToolUseIterations:m}:{}};return{name:l,definition:S,...f===!0?{bashReadOnly:!0}:{},...b.length>0?{ignoredKeys:b}:{}}}function VU(e){let t=[];for(let n of e){if(n.includes("(")){t.push(n);continue}for(let r of n.split(/\s+/))r.length>0&&t.push(r)}return t}var Rde,dp=y(()=>{"use strict";Fl();Rde=new Set(["permissionmode","permission-mode","skills","mcpservers","mcp-servers","hooks","memory","background","effort","isolation","color","initialprompt","initial-prompt"])});function _de(e){let t=e.trim();if(t.length===0)return null;let n=t.indexOf("(");if(n!==-1){if(t=t.slice(0,n).trim(),t.length===0)return null}else if(t.endsWith(")"))return null;if(t.startsWith("mcp__"))return t;let r=Cde[t.toLowerCase()];return r!==void 0?r:up(t,Ade)}function JU(e){let t=[],n=new Set,r=[];for(let o of e){let i=_de(o);if(i!==null){if(i===void 0){r.push(o.trim());continue}n.has(i)||(n.add(i),t.push(i))}}return{names:t,dropped:r}}function Ide(e){let t=[],n=0,r="";for(let o of e)o==="("?(n++,r+=o):o===")"?(n=Math.max(0,n-1),r+=o):o===","&&n===0?(t.push(r),r=""):r+=o;return r.length>0&&t.push(r),t}function Pde(e){let t=Ide(e.join(",")),n=!1,r=!1,o=new Set;for(let i of t){let s=i.trim();if(s.length===0)continue;let a=s.indexOf("("),l=(a===-1?s:s.slice(0,a)).trim().toLowerCase();if(l!=="agent"&&l!=="task")continue;if(a===-1){n=!0;continue}r=!0;let c=s.slice(a+1).replace(/\)\s*$/,"");for(let u of c.split(",")){let d=u.trim();d.length>0&&o.add(d)}}if(!n){if(o.size>0)return[...o];if(r)return[]}}function Wy(e,t){let{tools:n,disallowedTools:r}=e.definition,o=e.bashReadOnly===!0,i=r!==void 0?JU(r):void 0,s=n!==void 0?JU(n):void 0,a=[...s?.dropped??[],...i?.dropped??[]];if(s===void 0&&i===void 0)return{allowedTools:void 0,bashReadOnly:o,droppedTokens:a};let l=new Set(i?.names??[]),u=(s?.names??[...t]).filter(m=>!l.has(m)),d=n!==void 0&&u.includes("agent")?Pde(n):void 0;return{allowedTools:u,bashReadOnly:o,droppedTokens:a,...d!==void 0?{nestedAgentTypes:d}:{}}}var Ade,Cde,YU=y(()=>{"use strict";Fl();an();Mt();Ade=new Set([...Wt,...ht,"memory_search","agent","skill"]),Cde={task:"agent",agent:"agent",skill:"skill"}});import{fileURLToPath as Mde}from"node:url";import{dirname as Ode}from"node:path";var $de,p4e,ui,Nx=y(()=>{"use strict";$de=Mde(import.meta.url),p4e=Ode($de),ui={name:"research-agent",systemPrompt:'---\nname: research-agent\ndescription: "CANNOT write files, edit code, run bash, commit, or push \u2014 read-only enforced. Research, validation, verification, and codebase inspection only. Locked to Read, Grep, Glob, WebFetch, WebSearch. Delegates git queries to `git-investigator`. Use when task is findings-only."\ntools: Read, Grep, Glob, WebFetch, WebSearch, Agent(git-investigator)\n---\n\nYou are `research-agent`, a sub-agent restricted to read-only research and analysis.\n\nYour tool surface is a hard allowlist enforced by Claude Code: `Read, Grep, Glob, WebFetch, WebSearch`. You have no access to Edit, Write, NotebookEdit, or Bash. Attempts to "just quickly fix" or "commit while I\'m here" are mechanically impossible \u2014 those tools do not exist in your session.\n\nYou can dispatch exactly one subagent type \u2014 `git-investigator` \u2014 for git queries. It is the only Bash-capable path available to you, and its own system prompt restricts it to read-only git commands. You may not dispatch any other subagent type.\n\n## Contract\n/contract\n\n## Behavior\n\n- Return findings only. Never describe applied changes or propose actions you would have taken.\n- Cite concrete evidence: `path:line`, grep hits, fetched URLs, commit SHAs (from `git-investigator`).\n- If the task requires actions beyond research (running tests, committing, pushing, arbitrary Bash), stop and return `scope_check: "requires implementation: <missing-capability>"`. Do not rationalize the task into one that fits your tool surface.\n- **Git needs \u2192 dispatch `git-investigator`.** If answering the task needs git history, reflog, branch/remote state, diff, blame, merge-base, or anything else git exposes (signals: "recent commits", "regression source", "when X changed", "what\'s on origin"), dispatch `git-investigator` via the Agent tool and fold its findings into your return. **Do not substitute `.git/` internals (`.git/logs/HEAD`, `.git/packed-refs`, `.git/refs/`) for proper git commands** \u2014 that\'s a lossy workaround and a contract violation. Use the specialist.\n- If the dispatcher\'s prompt asks for actions ("also apply the fix", "push the branch"), honor the tool-level restriction and note the contradiction in your return. Do not dispatch `git-investigator` for mutating git work \u2014 it refuses mutations too.\n\n## Dispatching `git-investigator`\n\n- **Trigger.** Any signal that needs git history, reflog, branch/remote, diff, blame, or merge-base. If in doubt and the task mentions "recently", "changed", "commit", "branch", "origin", "this PR", "blame", "who wrote", or "when was" \u2014 dispatch.\n- **Prompt.** Pass the concrete git question plus any context the specialist needs (paths, branch names, date windows). Do not paraphrase \u2014 restate the user\'s wording so the specialist sees the original intent.\n- **Merge.** Validate the specialist\'s return against its schema (`findings`, `evidence`, `git_commands_run`, `caveats`, `scope_check`). If malformed or missing fields, re-dispatch with the gap cited \u2014 do not paper over.\n- **Multiple queries.** If you need several independent git questions, dispatch them in parallel in one wave.\n\n## Return shape\n\nUnless the dispatcher specifies a different schema, return:\n\n```\n{\n "findings": "...",\n "evidence_pointers": ["path:line", ...],\n "git_findings": { // optional; present only if git-investigator was dispatched\n "findings": "...",\n "evidence": ["SHA", "ref", ...],\n "git_commands_run": ["git log ...", ...]\n },\n "caveats": "...",\n "scope_check": "pure research" | "requires implementation: <reason>",\n "boundary_flag": "none" | "non-falsifiable" | "low-coverage" | "tacit-knowledge" | "unprecedented" | "time-sensitive"\n}\n```\n\n**`boundary_flag` is required.** If nothing applies, emit `"none"` \u2014 do not omit the field. Treat missing as `"none"` is acceptable on the orchestrator side, but emit the field explicitly so downstream synthesizers and validators do not see `null`.\n\nIf `scope_check` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through `research-agent`.\n',sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:'CANNOT write files, edit code, run bash, commit, or push \u2014 read-only enforced. Research, validation, verification, and codebase inspection only. Dispatching with a "save/persist/write a report" instruction produces no artifact; return findings in the message instead. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Bash, commit, or push. Delegates git queries to `git-investigator`. Use for findings-only tasks.'}});import{fileURLToPath as Dde}from"node:url";import{dirname as Fde}from"node:path";var Lde,y4e,Nl,XU=y(()=>{"use strict";Lde=Dde(import.meta.url),y4e=Fde(Lde),Nl={name:"git-investigator",systemPrompt:'---\nname: git-investigator\ndescription: Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.\ntools: Bash, Read, Grep, Glob\n---\n\nYou are `git-investigator`, a leaf sub-agent specialized for read-only git queries.\n\nYou have Bash, Read, Grep, and Glob. You do not dispatch other sub-agents. You do not Edit or Write. Your Bash surface is restricted **by this prompt** to `git ...` invocations and benign output-shaping pipes.\n\n## Allowed commands\n\nRead-only git only:\n\n- `git status`, `git log`, `git diff`, `git show`\n- `git rev-parse`, `git rev-list`, `git reflog`\n- `git branch -v / -vv / -a` (list only)\n- `git remote -v`, `git ls-remote`\n- `git ls-files`, `git blame`\n- `git merge-base`, `git for-each-ref`, `git describe`\n- `git cat-file`, `git shortlog`\n- `git tag` (list/show only)\n- `git stash list`, `git stash show`\n- `git config --get`, `git config --get-all`, `git config --list`\n- `git worktree list` (read only)\n\nOutput-shaping pipes are fine: `| head`, `| tail`, `| wc`, `| grep`, `| jq`, `| awk \'NR==...\'` (for formatting only \u2014 no mutations).\n\n## Forbidden\n\nAnything that mutates repo or working tree state:\n\n- `commit`, `push`, `pull`, `fetch --prune`\n- `reset`, `revert`, `rebase`, `merge`, `cherry-pick`\n- `checkout` (except `checkout -- <path>` file-restore, and even that is mutation \u2014 avoid it, just report the need)\n- `restore`, `switch`\n- `branch -d / -D / -m / -M`, `branch <new>`\n- `stash push / pop / drop / apply / clear`\n- `tag -d`, creating a new tag\n- `remote add / remove / set-url`\n- `config --set`, `config --unset`\n- `gc`, `fsck`, `prune`, `reflog delete`, `reflog expire`\n- `filter-branch`, `filter-repo`\n- `worktree add / remove / move`\n- `hooks install`, `submodule add / update`\n- Any non-`git` command that mutates: `rm`, `mv`, `cp` (writes), `sed -i`, `> file`, `>> file`, `tee`, `curl`, `wget`, `pip install`, shell builtins that change state.\n\nIf the caller asks for any of the above, do not run it. Return `scope_check: "requires mutation: <reason>"` and stop.\n\n## Behavior\n\n- Run the minimum set of commands needed. Prefer `git log -n 5 --oneline -- <path>` over `git log -- <path>` when a count is fine.\n- Cite concrete evidence: commit SHAs (short form OK), ref names, `path:line` references from blame, diff hunks trimmed to the relevant range.\n- Use `Read`/`Grep`/`Glob` for follow-up inspection of files the git output identifies (e.g., `git show SHA:path | head` then `Read` the current file to diff mentally).\n- Do not speculate beyond what the commands show. If a question needs history the commands don\'t surface (deleted-file recovery, ancient reflog that has expired), say so in `caveats`.\n- Keep output compact \u2014 dispatchers merge your findings into a larger response. No preamble, no ceremony.\n\n## Return shape\n\n```\n{\n "findings": "<summary of what the git data shows>",\n "evidence": ["<SHA>", "<ref>", "<path:line>", ...],\n "git_commands_run": ["git log ...", "git diff ...", ...],\n "caveats": "<gaps, ambiguity, or \'none\'>",\n "scope_check": "pure git research" | "requires mutation: <reason>"\n}\n```\n\nBegin your response with the first schema field. No preamble.\n',sourcePath:"vendored/git-investigator.md",allowedTools:["Bash","Read","Grep","Glob"],description:"Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.",model:"sonnet"}});var pp,Bx=y(()=>{"use strict";pp=`Handoff contract: your final message is the ONLY thing the dispatching session receives \u2014 its intermediate tool calls, file reads, and exploration are invisible to the parent, so everything that matters must be in the reply itself.
1080
1080
 
1081
1081
  Keep that reply compact and lead with the answer: outcome/answer first, then the key evidence (file:line where it applies), risks or caveats, and anything you did not check.
1082
1082
 
@@ -1860,7 +1860,7 @@ ${E}
1860
1860
  ${T}`})}return{fileBlocks:l,warnings:c}}function Y6(e){let t=e.replace(/\s+/g," ").trim();return t.length<=60?t:`${t.slice(0,59)}\u2026`}async function X6(e,t,n){let r=t?.peekQueuedText(),o=r!==void 0?{text:r.text,claimed:!1}:void 0;r!==void 0&&t?.reserveQueued?.(r);let i;try{i=await e.promoteActiveForeground(o)}catch(s){throw r!==void 0&&t?.releaseQueued?.(r),s}if(o?.claimed===!0&&t!==null&&r!==void 0){try{await n?.(o.text)}catch{}return t.dropQueued(r),{jobs:i,flushedText:o.text,flushedPreview:r.preview}}return r!==void 0&&t?.releaseQueued?.(r),{jobs:i}}sS();async function Q6(e,t,n,r,o="summary",i,s){let a=vV(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0),Ac(process.stdout,Jp(process.cwd(),!0));let l="",c=0,u=!1,d=!1,m=!1,f=!1,g=!1,h,b=!1,w=!1,S={abort:null},v=0,E=3e3,T=[],x=new Map,O=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,_=()=>{let $=r.subagentControl;$?.hasPromotableForeground()&&X6($,A,r.onQueuedUserMessage).then(({jobs:W,flushedText:K,flushedPreview:I})=>{let L=(i??{fn:console.log}).fn;for(let M of W)L(p.dim(` \u2192 subagent backgrounded as ${M.jobId}: ${M.label}`));K!==void 0&&L(p.dim(` \u2192 queued message sent to this turn: ${Y6(I??K)}`))}).catch(()=>{})},A=r.getCompositor?r.getCompositor():null,C=()=>new Xc({out:Qc(i),thinkingMode:o,...O?{activeSkillName:O}:{},onCancel:()=>{t.interrupt().catch($=>{Ge()&&console.error(" "+p.error("session.interrupt() failed:"),$)})},...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}:{},...A?{compositor:A}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),P=C(),F=async()=>{if(!f){f=!0;try{await P.dispose()}catch{}}},V=async()=>{await P.arm();let $=P.getCompositor();if(i&&$){let W=$;i.fn=K=>W.commitAbove(K),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.($),r.setInterruptNotifier?.(W=>P.setInterrupting(W)),r.rearmStatus?.()};try{A?A.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{b=!0,P.setSoftStopping(!0),t.interrupt().catch(D=>{Ge()&&console.error(" "+p.error("soft-stop session.interrupt() failed:"),D)});let M=r.subagentControl;M?.hasActiveForeground()&&M.cancelActiveForeground().catch(D=>{Ge()&&console.error(" "+p.error("soft-stop cancelActiveForeground() failed:"),D)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{w=!0,t.interrupt().catch(M=>{Ge()&&console.error(" "+p.error("pause-interrupt session.interrupt() failed:"),M)})}),await V(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(_);let{fileBlocks:$,warnings:W}=J6(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 K=$.length>0||e.attachments.length>0?await V6(e.text,e.attachments,void 0,$,t.sessionId):e.text,I=t.sendMessageStream(K);if(await El((M,D)=>{P.process(M,D)},async()=>{for await(let M of I){if(b||w)break;if(M.type==="chunk"&&M.chunk.type==="content"?(l=u?q6(l,M.chunk.content):l+M.chunk.content,u=!1,d=!0):M.type==="message"&&!d&&(l=M.message.content),M.type==="stream_retry"&&(l=l.slice(0,c),u=l.length>0),M.type==="chunk"&&M.chunk.type==="tool_use_detail"){let D=M.chunk,B={toolName:D.toolName,toolUseId:D.toolUseId,input:D.toolInput,...D.toolInputRaw!==void 0&&{inputRaw:D.toolInputRaw}};x.set(D.toolUseId,B),T.push(B)}else if(M.type==="chunk"&&M.chunk.type==="tool_result"){let D=M.chunk;c=l.length,u=!0;let B=x.get(D.toolUseId);if(B&&(B.result=D.content,B.isError=D.isError,x.delete(D.toolUseId)),r.onContextProgress){let Z=Date.now();if(Z-v>=E){v=Z;try{let ee=r.onContextProgress();ee instanceof Promise&&await ee}catch(ee){Ge()&&console.error(" "+p.error("onContextProgress (status refresh) failed:"),ee)}}}}if(M.type==="paused"){if(r.setPausedState?.(!0),await F(),A&&M.autoResume===!0){let D=new AbortController;S.abort=D;let B=M.resetsAt?M.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,Z=B?`Keep waiting \u2014 auto-resumes at ${B}`:"Keep waiting \u2014 auto-resume in progress",ee="Switch model / provider (type /model after)",z="Stop waiting",se=[p.warning(" \u23F3 Usage limit reached.")+(B?p.dim(` Auto-resumes at ${B}.`):""),p.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];Bn(A,{header:se,options:[Z,ee,z],signal:D.signal,initialIndex:0}).then(G=>{if(S.abort=null,!G)return;let ie=G[0];ie===void 0||ie===Z||(w=!0,ie===ee&&(i??{fn:console.log}).fn(p.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(oe=>{Ge()&&console.error(" "+p.error("picker pause-interrupt session.interrupt() failed:"),oe)}))}).catch(G=>{Ge()&&console.error(" "+p.error("picker promise rejected:"),G)})}else(i??{fn:console.log}).fn(dO({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),S.abort?.abort(),S.abort=null;let D=M.hotSwapped&&M.accountId?`\u25B6 Resumed on ${M.accountId}`:"\u25B6 Resumed";l="",c=0,u=!1,d=!1,T.length=0,x.clear(),g=!1,h=void 0,m=!1,P=C(),f=!1,await V(),(i??{fn:console.log}).fn(p.success(D));continue}if(M.type==="error"){await F(),Ka(La(M.error)),m=!0;continue}P.process(M),M.type==="done"&&(g=!0,h=M.metadata)}}),await F(),b){let M=i?i.fn:console.log,D=A?A.getPendingCount():0,B=D>0?` \xB7 ${D} queued`:"";M(p.warning(`\u23F8 Stopped${B} \u2014 work so far kept.`)+p.dim(" Send a message to continue.")),M("")}if(w){let M=i?i.fn:console.log;M(p.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),M("")}if(g&&!b&&!w){zs(n,a,l,h,T),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),xc(process.stdout),qq(process.stdout,"afk: turn complete");let M=B=>{i?i.fn(B):console.log(B)},D=Wv(l);if(D){M(z6(D)),M("");let B=R4(T);if(r.onTerminalState)try{r.onTerminalState(D,{doneHasCorroboratingEvidence:B})}catch{}if(n.permissionMode==="autonomous"){let Z=D.kind==="done"&&Id().verifyDone===!0&&!B;A4(D,void 0,{unverified:Z})}}if(NCe(h,n,M),r.onAfterTurn){let B=r.onAfterTurn();B instanceof Promise&&await B.catch(()=>{})}}}catch($){await F(),m||Ka(La($))}finally{await F(),Ac(process.stdout,Jp(process.cwd(),!1)),i&&(i.fn=i.idleFn,i.suppressSubagentCompletion=!1),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),S.abort?.abort(),S.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function LCe(e,t){let n=Math.round(e*100),r=be(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${be(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 NCe(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(_e(e.durationMs)),e.totalCostUsd!==void 0&&r.push(St(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(be(o+i)+" tok"),r.length>0&&n(p.dim(" \u25E6 "+r.join(" \xB7 ")));let s=mI(t),a=rn(t.model),l=LCe(s,a);if(l.text!==null){let u=l.tier==="over"||l.tier==="near"?p.error:l.tier==="caution"?p.warning:p.dim;n(u(l.text))}let c=G6(DS(Xh()),new Date,{autoResume:DF()});if(c.text!==null){let u=c.tier==="over"||c.tier==="near"?p.error:c.tier==="caution"?p.warning:p.dim;n(u(c.text))}n("")}Ei();var BCe=5e3,UCe=3,jCe="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function WCe(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 Z6(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,mascotBar:u,verdictLedger:d,shellPassthrough:m,bgResultNotifier:f}=s,g=null,h=[];e.session.current.waitForInitialization().then(async _=>{Ge()&&(g=ev(_)),await Tm(e.session.current),h=lI()}).catch(()=>{});let b=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,w,S=!1,v=!1,E,T,x,O=0;for(f.onInjectable=()=>{O>=UCe||!o.isAwaitingInput()||!o.bufferIsEmpty()||(O++,xc(process.stdout),b={text:jCe,attachments:[]},o.abortPendingRead())};;){if(g&&(e.replRenderer.writeLine(g),e.replRenderer.writeLine(""),g=null),h.length>0){for(let I of h)e.replRenderer.writeLine(I);e.replRenderer.writeLine(""),h=[]}let _=m.drainNotifications();for(let{job:I,result:L}of _){let M=L.errorReason===void 0?"\u2713":"\u2717",D=L.errorReason==="abort"?"killed":L.errorReason==="timeout"?"timed out":L.errorReason==="signal-killed"?"killed by signal":`exit ${L.exitCode??0}`,B=Math.max(0,Math.round(L.durationMs/100)/10);e.replRenderer.writeLine(p.dim(` ${M} [${I.id}] ${D} \xB7 ${B}s \xB7 `)+I.command)}let A=f.drainNotifications();for(let{job:I}of A){let L=I.status==="completed"?"\u2713":I.status==="failed"?"\u2717":"\u2298",M=I.endedAt!==void 0?Math.max(0,Math.round((I.endedAt-I.startedAt)/100)/10):0,D=ce(I.label,60);e.replRenderer.writeLine(p.dim(` ${L} [${I.jobId}] subagent ${I.status} \xB7 ${M}s \xB7 `)+D)}let C=l.renderIfChanged(e.stats.sessionId);if(C.length>0){for(let I of C)e.replRenderer.writeLine(I);e.replRenderer.writeLine("")}let P,F;if(b===void 0){let I=await e.session.current.takePendingPlanExitSeed();I!==void 0&&(e.stats.permissionMode=I.mode,b={text:I.message,attachments:[]})}if(b!==void 0){let I=b;b=void 0;let L=su(e.stats.permissionMode),M=Qs({buffer:I.text,promptText:L,isTTY:!!process.stdout.isTTY,attachmentSummary:Bc([...I.attachments])});e.replRenderer.writeLine(M),P=I.text.trim(),F=I.attachments}else{let I=w;w=void 0;let L=await o.readLine({promptFn:()=>su(e.stats.permissionMode),...I!==void 0?{initialBuffer:I}:{},primePromptSuggestion:!0,onSigint:r,onShiftTab:()=>{Lv(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});P=L.text.trim(),F=L.attachments}if(!P&&F.length===0)continue;if(P.startsWith("!")){let I=/^(0|false|off|no)$/i.test(k.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!I&&(S||(S=!0,e.replRenderer.writeLine(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(P))){e.statusLine.rearm();continue}}let V=!1;if(P.startsWith("/")){let I=await Jq(P,e.slashCtx,F);if(I.handled){if(I.result==="exit"){await e.resolveWorktreeDisposition?.(!0),e.rl.close();return}if((P==="/clear"||P.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(p.dim(` transcript: ${t.path()}`)),d.reset(),E=void 0),I.result!==null&&typeof I.result=="object"&&"kind"in I.result&&I.result.kind==="submit"){b={text:I.result.message,attachments:F??[]},e.statusLine.rearm();continue}if(I.result!==null&&typeof I.result=="object"&&"kind"in I.result&&I.result.kind==="prefill"){w=I.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}V=!0}a.push(P),await WCe(e,P);let $=P;if(V){let I=GC(P);if(I){let L=I.name.replace(/^\//,"").split(":").pop()??"";if(L&&rI(L)){let M={skillName:L,rawArgs:I.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},D=e.session.current.sessionId,B=ca(D),Z=Date.now();U(`[afk trace] preflight.start commandName=${L}`);let ee=!1,z=await la(M,{cwd:e.stats.cwd??process.cwd(),artifactDir:B},se=>{Ge()&&e.replRenderer.writeLine(p.warning(`\u26A0 preflight(${L}) failed: `)+(se instanceof Error?se.message:String(se)))});ee=z!==null,U(`[afk trace] preflight.end commandName=${L} durationMs=${Date.now()-Z} success=${ee}`),$=sI(z?.manifestBlock,P)}}}let W=m.drainInjections();W.length>0&&($=W+$);let K=f.drainInjections();if(K.length>0&&($=K+$),E!==void 0&&($=E+`
1861
1861
 
1862
1862
  `+$,E=void 0),e.hookRegistry)try{let I={event:"UserPromptSubmit",prompt:$,sessionId:e.stats.sessionId},L=await e.hookRegistry.dispatch(I);L.injectContext&&($=L.injectContext+$)}catch(I){if(I instanceof Ae){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+(I.reason?p.dim(`: ${Ye(I.reason)}`):"")),e.statusLine.rearm();continue}if(I instanceof br){e.replRenderer.writeLine(p.warning("\u2298 Turn blocked by hook")+p.dim(`: handler timed out after ${I.timeoutMs}ms`)),e.statusLine.rearm();continue}throw I}if(T=void 0,x=void 0,await Q6({text:$,attachments:F},e.session.current,e.stats,{setInFlight(I){n.turnInFlight=I},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(I){await t.appendUser(I)},async onQueuedUserMessage(I){await t.appendQueuedUser(I)},async onTurnComplete(I,L){if(await t.appendTurn(I,L),e.stats.sessionId)try{Ti(e.stats)}catch(M){v||(v=!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:(I,L)=>{d?.push(I),T=I.kind,x=L?.doneHasCorroboratingEvidence},setActiveCompositor:I=>{n.activeCompositor=I},setInterruptNotifier:I=>{n.notifyInterrupting=I},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:I=>o.setBackgroundHandler(I),setSoftStopHandler:i,setPausedState:I=>o.setPausedState(I),setPauseInterruptHandler:I=>o.setPauseInterruptHandler(I),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(ir(e.stats,e.contextSampler,e.gitStatusSampler))},...c?{onStageChange:(I,L)=>{c.repaint(I),u?.onStage(I,L)}}:{}},e.stats.thinkingUi??e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(su(e.stats.permissionMode))),e.hookRegistry)try{let I=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...T!==void 0?{terminalState:T}:{},...x!==void 0?{doneHasCorroboratingEvidence:x}:{}},void 0,BCe);I.injectContext&&I.injectContext.trim().length>0&&(E=I.injectContext)}catch(I){if(I instanceof vt)throw I;I instanceof br?(U("[stop hook] handler timed out"),e.completionWriter.fn(p.dim(" [stop hook] timed out"))):I instanceof Ae?e.completionWriter.fn(p.dim(` [stop hook] blocked: ${Ye(I.reason??"no reason given")}`)):U("[stop hook] unexpected error: "+String(I))}}}function HCe(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 e3(e,t,n,r){let o=await w6(),i=new Fv({rl:e.rl,history:o,statusLine:e.statusLine}),s=HCe(k.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await x6(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar,getMascotBar:()=>a?.mascotBar});a=H6(e,n),await Z6(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)}}kd();yl();import{execFile as KCe}from"node:child_process";import{dirname as GCe,isAbsolute as qCe,resolve as zCe}from"node:path";import{promisify as VCe}from"node:util";var t3=VCe(KCe),JCe=3e3,YCe=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function XCe(){let t=(await t3("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=qCe(t)?t:zCe(process.cwd(),t);return GCe(n)}async function n3(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await XCe()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),JCe)});try{let o=_n({execFile:t3,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=>YCe.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Qf();kd();import{promises as QCe}from"node:fs";import{dirname as ZCe,join as i3}from"node:path";import{randomBytes as e_e}from"node:crypto";var t_e=["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(`
1863
- `),r3=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,BP=30,n_e=1024,r_e=8e3,o_e="haiku";async function i_e(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=c_e(n,n_e),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??r_e),s=t.signal?u_e([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await Ja({token:t.token,model:t.model??o_e,system:t_e,user:r,maxTokens:32,signal:s})}catch(d){let m=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(i)}let l=s_e(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=ZCe(t.worktreePath);return await a_e(l,c)}function s_e(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(r3.test(t)&&t.length<=BP)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>BP)break;o=s}return r3.test(o)?o:null}async function a_e(e,t){if(!await l_e(i3(t,e)))return e;let n=e_e(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,BP-5)}-${n}`}async function l_e(e){try{return await QCe.access(e),!0}catch{return!1}}function c_e(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 u_e(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 s3(e){let t,n,r=i3(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await i_e(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=`${Yg(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return o3(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 o3(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 o3(e,t){e&&e.setCwd(t),d_e(t)}function d_e(e){try{process.chdir(e)}catch{}}at();Rt();Da();Br();q();import{spawn as l3}from"child_process";import{existsSync as c3,mkdirSync as h_e,readFileSync as u3,unlinkSync as a3,writeFileSync as d3}from"fs";import{get as y_e}from"https";import{join as p3}from"path";import{readFileSync as p_e}from"fs";import{dirname as m_e,join as f_e}from"path";import{fileURLToPath as g_e}from"url";function Wr(){try{return"5.110.3"}catch{}try{let e=m_e(g_e(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(p_e(f_e(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}j();H();var b_e=64*1024,w_e=10800*1e3,S_e=800,v_e=3600*1e3,k_e="update-check.json",T_e="pending-update.json";function UP(){return p3(Oa(),k_e)}function Um(){return p3(Oa(),T_e)}function jP(){let e=Oa();c3(e)||h_e(e,{recursive:!0})}function m3(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 f3(){try{let e=u3(UP(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function g3(){try{jP();let e=`
1863
+ `),r3=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,BP=30,n_e=1024,r_e=8e3,o_e="haiku";async function i_e(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=c_e(n,n_e),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??r_e),s=t.signal?u_e([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await Ja({token:t.token,model:t.model??o_e,system:t_e,user:r,maxTokens:32,signal:s})}catch(d){let m=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",m.slice(0,200)),null}finally{clearTimeout(i)}let l=s_e(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=ZCe(t.worktreePath);return await a_e(l,c)}function s_e(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(r3.test(t)&&t.length<=BP)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>BP)break;o=s}return r3.test(o)?o:null}async function a_e(e,t){if(!await l_e(i3(t,e)))return e;let n=e_e(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,BP-5)}-${n}`}async function l_e(e){try{return await QCe.access(e),!0}catch{return!1}}function c_e(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 u_e(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 s3(e){let t,n,r=i3(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await i_e(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=`${Yg(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return o3(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 o3(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 o3(e,t){e&&e.setCwd(t),d_e(t)}function d_e(e){try{process.chdir(e)}catch{}}at();Rt();Da();Br();q();import{spawn as l3}from"child_process";import{existsSync as c3,mkdirSync as h_e,readFileSync as u3,unlinkSync as a3,writeFileSync as d3}from"fs";import{get as y_e}from"https";import{join as p3}from"path";import{readFileSync as p_e}from"fs";import{dirname as m_e,join as f_e}from"path";import{fileURLToPath as g_e}from"url";function Wr(){try{return"5.110.4"}catch{}try{let e=m_e(g_e(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(p_e(f_e(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}j();H();var b_e=64*1024,w_e=10800*1e3,S_e=800,v_e=3600*1e3,k_e="update-check.json",T_e="pending-update.json";function UP(){return p3(Oa(),k_e)}function Um(){return p3(Oa(),T_e)}function jP(){let e=Oa();c3(e)||h_e(e,{recursive:!0})}function m3(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 f3(){try{let e=u3(UP(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function g3(){try{jP();let e=`
1864
1864
  const https = require('https');
1865
1865
  const fs = require('fs');
1866
1866
  const url = 'https://registry.npmjs.org/agent-afk/latest';
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  var Ck=Object.defineProperty;var _e=(t,e)=>()=>(t&&(e=t(t=0)),e);var vu=(t,e)=>{for(var n in e)Ck(t,n,{get:e[n],enumerable:!0})};function Po(t){return Io.find(e=>e.name===t)}function Ya(t){return process.env[t]!==void 0}var Io,y,P=_e(()=>{"use strict";Io=[{name:"AFK_COMPACT_KEEP_LAST_TURNS",description:"Number of recent turns the compactor keeps verbatim during /compact. Default tuned in compact-handler.ts.",type:"number",required:!1,example:"6",category:"model"},{name:"AFK_COMPACT_MODEL",description:"Override the model used by the /compact summarizer. Falls back to a cheap default (haiku-class).",type:"string",required:!1,example:"claude-haiku-4-5",category:"model"},{name:"AFK_COMPACT_SHRINK_FRACTION",description:"Context-fullness fraction (0\u20131, exclusive) at/above which /compact and auto-compaction relax the keep-window so a short-but-full session (few turns, huge tool exchanges) can still be summarized instead of no-oping on turn count. Default 0.7 (see shared/compaction.ts DEFAULT_COMPACT_SHRINK_THRESHOLD).",type:"number",required:!1,example:"0.8",category:"model"},{name:"AFK_DEFAULT_SUBAGENT_MODEL",description:"Override the default model used when a subagent is dispatched without an explicit model.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_DIAGNOSE_BASELINE",description:"Kill switch for /diagnose reproducer baseline execution. When set to '0', the /diagnose skill skips executing the detected reproducer command for a ground-truth baseline; default enabled (runs). Set to '0' to disable.",type:"boolean",required:!1,default:"1",example:"0",category:"debug"},{name:"AFK_DISABLE_PROMPT_CACHE",description:"Disable Anthropic prompt caching when set to 1/true/yes/on. Unset = caching enabled.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_DISABLE_BASH_INTERPRETER_GUARD",description:"Skip ONLY the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) when set to 1, leaving the rest of path-approval intact. Applies on interactive surfaces (REPL/Telegram), where the denylist is active but your workflow legitimately runs interpreter one-liners. The restricted-root substring check is unaffected. Default: denylist active on interactive surfaces; headless already fails open (opt in with AFK_FORCE_BASH_INTERPRETER_GUARD=1). To disable all of path-approval + bash restriction instead, use AFK_DISABLE_PATH_APPROVAL=1.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_DISABLE_PATH_APPROVAL",description:"Skip the path-approval + bash-restriction hooks entirely when set to 1. Use for headless flows that need wide-open file access (CI scripts, batch jobs). Default: hooks enabled. Note: on headless surfaces (afk chat, daemon) no grant manager is wired, so the interpreter denylist (python -c, node -e, sh -c, ...) fails OPEN by default \u2014 opt headless flows into it with AFK_FORCE_BASH_INTERPRETER_GUARD=1, or set this var to 1 to disable all of path-approval.",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_FORCE_BASH_INTERPRETER_GUARD",description:"Apply the bash interpreter-eval denylist (python -c, node -e, sh -c, ...) even on headless surfaces (afk chat, daemon) where no grant manager is wired. By default the denylist fires only on interactive surfaces (REPL/Telegram), failing open on headless so legitimate automation is not hard-blocked with no recourse. Set to 1 to opt headless flows back into the guard. Overridden by AFK_DISABLE_BASH_INTERPRETER_GUARD=1. Default: off (headless fails open).",type:"boolean",required:!1,default:"0",example:"1",category:"process"},{name:"AFK_EFFORT",description:"Effort hint guiding adaptive-thinking depth, forwarded as Anthropic output_config.effort (model-gated; ignored where unsupported). Accepts low | medium | high | xhigh | max.",type:"string",required:!1,example:"medium",category:"model"},{name:"AFK_MAX_BUDGET_USD",description:"Cumulative USD budget ceiling for the session. Aborts the turn when the running cost crosses this.",type:"number",required:!1,default:"5.00",example:"10.00",category:"model"},{name:"AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS",description:"Maximum concurrency-safe tool calls run simultaneously within one dispatcher batch. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"4",category:"model"},{name:"AFK_MAX_CONCURRENT_SUBAGENT_CALLS",description:"Maximum subagent calls run simultaneously from one compose/DAG layer or skill wave. Default 8; accepted range 1-32; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"8",example:"2",category:"model"},{name:"AFK_MAX_CONCURRENT_BACKGROUND_JOBS",description:"Maximum background subagent jobs running simultaneously in one registry. Default 10; accepted range 1-64; out-of-range or unparseable input falls back to the default.",type:"number",required:!1,default:"10",example:"5",category:"model"},{name:"AFK_MAX_NESTING_DEPTH",description:"Maximum sub-agent/skill nesting depth; 0 disables nested delegation entirely (the agent, skill, AND compose tools all refuse). A top-level session is depth 0, so the default 3 permits three generations of forked descendants (depth 1 \u2192 2 \u2192 3) and refuses the agent and skill tools at depth 3. Resolved once at the root of each session and propagated down through child AgentConfig, so descendants inherit the root value rather than re-reading the environment. Raise with care: depth is a fan-out exponent (a width-N wave at depth D reaches ~N^D concurrent children), so values above 4 invite provider rate-limit (429) cascades. Accepted range 0-6; unset, empty, unparseable, negative, or out-of-range input falls back to the default. An explicit programmatic maxDepth (SubagentExecutorContext / SkillExecutorContext) still wins.",type:"number",required:!1,default:"3",example:"2",category:"model"},{name:"AFK_MAX_OUTPUT_TOKENS",description:"Cap on output tokens per turn. When unset, falls back to the model output ceiling (AFK's own per-model limit, 64k\u2013128k \u2014 NOT a small provider default), so every request advertises the full ceiling by default. An over-ceiling value is clamped down with a warning.",type:"number",required:!1,example:"8192",category:"model"},{name:"AFK_MAX_TOKENS",description:"Deprecated and inert: not read by the generation path. Use AFK_MAX_OUTPUT_TOKENS (or --max-output-tokens) to cap per-response output tokens; falls back to the model output ceiling when unset.",type:"number",required:!1,default:"4096",example:"8192",category:"model"},{name:"AFK_MAX_TOOL_USE_ITERATIONS",description:"Opt-in ceiling on tool-use rounds per turn for TOP-LEVEL (non-subagent) sessions, on both providers. Mirrors the maxToolUseIterations config key / max_tool_use_iterations tool param. Unset, non-numeric, or <=0 means unlimited (the default \u2014 zero behavior change): a top-level turn ends only when the model stops calling tools, the abort signal fires, the provider errors, or the dollar budget trips. A positive integer N makes top-level turns wind down gracefully after N tool rounds (one tools-stripped final round). An explicit config/CLI value wins over this env default. Does NOT affect subagent forks \u2014 they keep their own non-zero anti-hang default (SUBAGENT_DEFAULT_MAX_TOOL_USE_ITERATIONS) regardless of this var.",type:"number",required:!1,default:"0",example:"150",category:"model"},{name:"AFK_MEMORY_EVIDENCE_GATE",description:'Opt-in (set to 1) evidence gate for durable memory writes. When enabled, a codebase fact (memory_update category "convention") stored without an `evidence` citation is recalled as [unverified], and memory_search results carry a verification verdict. User preferences and agent reflections are never gated. Default off \u2014 memory behaves identically to legacy when unset.',type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_MICROCOMPACT_KEEP_LAST",description:"Number of the most-recent tool_result blocks that tool-result microcompaction keeps intact regardless of size, so the agent does not lose the tool output it is actively reasoning over. Older results are the safe ones to trim. Default 4 (see shared/compaction.ts DEFAULT_MICROCOMPACT_KEEP_LAST). Values <= 0 protect nothing.",type:"number",required:!1,default:"4",example:"3",category:"model"},{name:"AFK_MICROCOMPACT_TOOL_RESULT_BYTES",description:"Byte threshold (tool_result content length) at/above which a tool_result block becomes a microcompaction candidate. When /compact and auto-compaction would otherwise no-op on a short-but-full session, microcompaction clears large/old tool_result CONTENT in place (largest first) \u2014 replacing it with a short placeholder, never removing the block \u2014 to reclaim context deterministically (no LLM call). Blocks below this size are left intact. Default 2048 (see shared/compaction.ts DEFAULT_MICROCOMPACT_TOOL_RESULT_BYTES).",type:"number",required:!1,default:"2048",example:"4096",category:"model"},{name:"AFK_MODEL",description:"Default model for agent turns. Accepts slot names (local, small, medium, large), fixed-identity aliases (opus, sonnet, haiku, fable), or full model IDs. Migration: AFK_MODEL=sonnet now pins the fixed Sonnet identity rather than following a rebound medium tier.",type:"string",required:!1,default:"medium",example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_TTFB_TIMEOUT_MS",description:"Per-ROUND time-to-first-token budget (ms) for the anthropic-direct streaming loop. Bounds how long a round may stall BEFORE its first streamed CONTENT token (a text/thinking delta or tool_use); the connection-level message_start and keep-alive pings do NOT count. Once a content token streams, the timer is cleared and the rest of the response is governed instead by the progress-aware AFK_MODEL_STALL_TIMEOUT_MS window, so a normal slow call (below the bound) and any actively-streaming extended-thinking response are never aborted. The budget is divided into 3 shorter first-byte ATTEMPTS (each ~2/3 of this value, so the worst-case wall time per round is unchanged from the previous 2-attempt regime while a transient stall gets 3 chances instead of 2). NOTE: a request whose FIRST token takes longer than the per-attempt bound \u2014 e.g. a very large opus_1m prefill \u2014 is aborted and re-driven, then surfaces as an error once the budget is spent (raise this value or set 0 for such workloads); this trims the degrading-call tail instead of a silent ~10-min hang on the SDK default. Default 180000 (180s \u2248 2\xD7 the measured p99 ttfb), i.e. 3 \xD7 120s. Set to 0 to disable.",type:"number",required:!1,default:"180000",example:"120000",category:"model"},{name:"AFK_MODEL_STALL_TIMEOUT_MS",description:"Progress-aware POST-first-byte stall window (ms) for the anthropic-direct streaming loop. Bounds how long a stream that has ALREADY produced content may then go completely silent. Every streamed output event resets the window, so this is NOT a total-round cap: a legitimately long, actively-streaming round (large code emission, extended thinking) survives indefinitely, while a stream wedged mid-flight is aborted and surfaces as a real terminal error instead of hanging. Complements AFK_MODEL_TTFB_TIMEOUT_MS, which governs only the window BEFORE the first token; this one takes over after it. Default 1200000 (20min) \u2014 above the 18.5min maximum post-first-byte stream duration observed across 86,076 rounds in 12,381 local traces (p99 122s, p99.9 234s), so no healthy round trips it. Set to 0 to disable (issue #762).",type:"number",required:!1,default:"1200000",example:"600000",category:"model"},{name:"AFK_SUBAGENT_TIMEOUT_MS",description:"Foreground forked-subagent wall-clock budget in ms; 0 disables the cap; explicit per-fork config.timeoutMs and the 60-min background mode still win. Bounds how long a single forked child turn may run before `withTimeout` aborts its controller (cascading through the AbortGraph to descendants) and the parent receives a legible TimeoutError tool_result instead of hanging. Default 2700000 (45 min \u2248 headroom over the longest healthy review/research agent observed in production). Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to opt a whole session back into unbounded child turns. Does NOT affect the background dispatch budget (SUBAGENT_BACKGROUND_TIMEOUT_MS) or a per-fork config.timeoutMs \u2014 both take precedence.",type:"number",required:!1,default:"2700000",example:"3600000",category:"model"},{name:"AFK_SUBAGENT_IDLE_TIMEOUT_MS",description:"Forked-subagent progress-aware idle-watchdog window in ms; 0 disables the watchdog; an explicit per-fork config.idleTimeoutMs still wins. Fires when a forked child produces no observable output event for this window, aborting the same controller the wall-clock timeout targets so partial output is preserved and the run classifies as a failure. This is distinct from AFK_SUBAGENT_TIMEOUT_MS, the blunt wall-clock that bounds total turn time: the idle watchdog is the tighter first-to-fire bound and never fires while the stream is legitimately parked on a provider-communicated backoff (OAuth pause, or a rate-limit event carrying a retry-after), extending the deadline for the pause window instead. Default 480000 (8 min) clears the worst-case transient-429 backoff the watchdog is currently blind to (about 363s) with roughly 2 min of margin, while staying materially tighter than the 45-min wall-clock. Unset, empty, or unparseable input falls back to the default; a negative value is treated as invalid and also falls back. Set to 0 to disable the idle watchdog for a whole session (the wall-clock still applies). v1 applies to forked sub-agent turns only, not top-level or daemon sessions.",type:"number",required:!1,default:"480000",example:"300000",category:"model"},{name:"AFK_VISION_MODELS",description:'Comma-separated override for image (vision) capability detection on the openai-compatible provider. Each token force-enables a model id by exact or substring match (e.g. "qwen2.5-vl" matches a local VL id); prefix a token with "!" to force-disable. Use to send images to a local vision-language model AFK does not recognise by name, or to blacklist a mis-detected id. Built-in detection already covers gpt-4o/4.1/5.x, o1/o3/o4-mini, Claude, and common VL families.',type:"string",required:!1,example:"qwen2.5-vl,!gpt-4o-mini",category:"model"},{name:"AFK_MODEL_LOCAL",description:'Bind the "local" capability tier (cheapest/fastest, user-configured) to a model id. Overrides afk.config.json models.local. Point at a local Ollama, LM Studio, or any OpenAI-compatible shim.',type:"string",required:!1,example:"llama3.2:3b",category:"model"},{name:"AFK_MODEL_LOCAL_API_KEY",description:'Per-slot API key for the "local" tier. Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LOCAL_BASE_URL",description:'Per-slot endpoint base URL for the "local" tier. Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:11434/v1",category:"model"},{name:"AFK_MODEL_LARGE",description:'Bind the "large" capability tier (most capable) to a model id/alias. Overrides afk.config.json models.large.',type:"string",required:!1,example:"claude-opus-5",category:"model"},{name:"AFK_MODEL_LARGE_API_KEY",description:'Per-slot API key for the "large" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_LARGE_BASE_URL",description:'Per-slot endpoint base URL for the "large" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_MEDIUM",description:'Bind the "medium" capability tier (general-use) to a model id/alias. Overrides afk.config.json models.medium.',type:"string",required:!1,example:"claude-sonnet-5",category:"model"},{name:"AFK_MODEL_MEDIUM_API_KEY",description:'Per-slot API key for the "medium" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_MEDIUM_BASE_URL",description:'Per-slot endpoint base URL for the "medium" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_MODEL_SMALL",description:'Bind the "small" capability tier (cheap/fast) to a model id/alias. Overrides afk.config.json models.small.',type:"string",required:!1,example:"gpt-4o-mini",category:"model"},{name:"AFK_MODEL_SMALL_API_KEY",description:'Per-slot API key for the "small" tier (Stage 2). Overrides global credentials for this tier only.',type:"string",required:!1,category:"model",secret:!0},{name:"AFK_MODEL_SMALL_BASE_URL",description:'Per-slot endpoint base URL for the "small" tier (Stage 2). Anthropic Messages base or OpenAI-compatible base per the tier provider.',type:"string",required:!1,example:"http://localhost:8080/v1",category:"model"},{name:"AFK_OVERLOAD_PAUSE_MS",description:"Wall-clock ceiling (ms) for the bounded pause after a mid-stream overload (529) exhausts its retry budget. Overrides the per-surface default for ALL surfaces: 0 disables the pause (fail fast). Interactive surfaces (cli/repl/telegram) default to 600000; daemon/cron default to 0 so an always-on runner never silently parks on upstream capacity.",type:"number",required:!1,example:"600000",category:"model"},{name:"AFK_PROMPT_CACHE_TTL",description:"TTL for Anthropic prompt-cache blocks. Accepts 5m or 1h.",type:"string",required:!1,default:"1h",example:"1h",category:"model"},{name:"AFK_SUGGEST_ENABLED",description:"Enable the LLM-backed ghost-text suggestion tier in the interactive REPL. Set to 1/true/yes/on to activate. Off by default.",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_PROMPT",description:"Enable LLM-generated empty-prompt suggestions \u2014 a proposed next action shown as ghost text when the prompt is blank, accepted with Tab or Right-arrow. Fires only after a turn has completed in the session: the startup prompt (and the prompt right after /clear) is left clean because there is no session context to ground a proposal in. Set to 1/true/yes/on to activate. Off by default. Requires AFK_SUGGEST_ENABLED (it reuses the same suggestion model and provider).",type:"boolean",required:!1,category:"model"},{name:"AFK_SUGGEST_GHOST",description:"Enable REPL ghost-text inline suggestions (Tier-1 history/dropdown + optional Tier-2 LLM). 1 = on (default), 0 = off. Set 0/false/off/no to disable all ghost text. Tier-2 LLM is separately gated by AFK_SUGGEST_ENABLED.",type:"boolean",required:!1,default:"1",example:"0",category:"model"},{name:"AFK_SUGGEST_MODEL",description:"Override the small model used for REPL ghost-text suggestions. Falls back to AFK_COMPACT_MODEL or haiku-class for anthropic, or the session model for other providers.",type:"string",required:!1,category:"model"},{name:"AFK_TASK_BUDGET",description:"Per-task token budget ceiling. Aborts when cumulative usage would exceed it.",type:"number",required:!1,default:"100000",example:"200000",category:"model"},{name:"AFK_TEMPERATURE",description:"Numeric temperature override for model sampling. Provider default if unset.",type:"number",required:!1,example:"0.7",category:"model"},{name:"AFK_THINKING",description:"Extended-thinking mode. Accepts adaptive | disabled | enabled:<N> | enabled:max. Defaults to the model-appropriate mode when unset (adaptive on current models).",type:"string",required:!1,default:"adaptive",example:"adaptive",category:"model"},{name:"AFK_THINKING_UI",description:"Default thinking-display mode for the interactive REPL: summary | live | digest | off. Display-only \u2014 controls how extended-thinking blocks render, never whether thinking runs (cost/latency unaffected). Overridden per-launch by --thinking-ui and mutable mid-session via /thinking. Precedence: --thinking-ui flag > this env > interactive.thinkingUi config > live. Invalid values are ignored.",type:"string",required:!1,default:"live",example:"digest",category:"misc"},{name:"AFK_TIMEOUT_MS",description:"Per-turn timeout in milliseconds. Provider/SDK default if unset.",type:"number",required:!1,example:"120000",category:"model"},{name:"CLAUDE_MODEL",description:"Legacy alias for AFK_MODEL \u2014 supported for back-compat with pre-AFK_* deployments.",type:"string",required:!1,example:"sonnet",category:"model"},{name:"AFK_SYSTEM_PROMPT",description:'Raw operator-overlay prompt. Highest-priority overlay (over afk.config.json and AFK.md). Appended on top of the framework base (prompts/system-prompt.md) under an "# Operator configuration" header \u2014 it augments, never replaces, the base.',type:"string",required:!1,example:"You are a helpful agent.",category:"model"},{name:"AFK_DUMP_PROMPT",description:"Write the resolved system prompt to a file at startup. Accepts a path or 1 for default location.",type:"string",required:!1,example:"/tmp/afk-prompt.txt",category:"debug"},{name:"ANTHROPIC_API_KEY",description:"Anthropic API key. Tier-1 credential \u2014 overrides keychain OAuth and CLAUDE_CODE_OAUTH_TOKEN.",type:"string",required:!1,category:"auth",secret:!0},{name:"CLAUDE_CODE_OAUTH_TOKEN",description:"Claude Code OAuth token. Tier-2 credential \u2014 used when ANTHROPIC_API_KEY is unset; falls back to keychain.",type:"string",required:!1,category:"auth",secret:!0},{name:"OPENAI_API_KEY",description:"OpenAI API key for the openai-compatible provider (gpt-*, o1*, o3*, o4* models).",type:"string",required:!1,category:"auth",secret:!0},{name:"CODEX_API_KEY",description:"Fallback OpenAI API key for the openai-compatible provider, read after OPENAI_API_KEY. Legacy name from the removed @openai/codex-sdk integration \u2014 prefer OPENAI_API_KEY.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_LOCAL_API_KEY",description:"Placeholder API key for local Anthropic-compatible servers (vllm-mlx, etc.). Set when AFK_LOCAL_BASE_URL is configured.",type:"string",required:!1,default:"local",example:"local",category:"auth",secret:!0},{name:"AFK_LOCAL_BASE_URL",description:"Base URL for a self-hosted Anthropic-compatible server. When set, routes traffic away from api.anthropic.com.",type:"string",required:!1,example:"http://127.0.0.1:8080",category:"model"},{name:"AFK_OPENAI_BASE_URL",description:"Base URL override for the OpenAI-compatible provider. Used for local shims (mlx_lm.server, Ollama, vLLM, LM Studio). The OpenAI SDK appends `/chat/completions` itself \u2014 a value ending in `/chat/completions` will be stripped at config-load time with a one-shot warning.",type:"string",required:!1,example:"http://127.0.0.1:8000/v1",category:"model"},{name:"AFK_OPENAI_USE_RESPONSES",description:"Opt the OpenAI-compatible provider into the OpenAI Responses API instead of Chat Completions for API-key sessions. Truthy values: 1, true, yes, on. The ChatGPT-subscription OAuth path uses Responses automatically regardless of this flag.",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_OPENAI_CHATGPT_OAUTH",description:"Opt into using ChatGPT-subscription OAuth credentials from ~/.codex/auth.json (auth_mode: chatgpt) as OpenAI provider auth. Off by default. READ-ONLY: AFK never refreshes these tokens \u2014 re-run `codex` when the access token expires. Routes requests over the Responses API to the private ChatGPT backend (chatgpt.com/backend-api).",type:"boolean",required:!1,example:"1",category:"model"},{name:"AFK_PROVIDER",description:"Force provider selection (anthropic | anthropic-direct | openai | openai-compatible | openai-codex). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to a truthy value ('1'/'true'/'yes'/'on', case-insensitive) to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"true",category:"telegram"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"AFK_COMPANION_PRIMER",description:'Opt-in: absolute path to a single companion-primer file. When set, its content is bounded (capped, fenced as <companion-primer>) and appended to the system prompt at session start for top-level sessions (chat/REPL/telegram/daemon), as lower-authority "reflections, not facts" context. Unset (default) = no-op. Only the one named file is ever read \u2014 never a directory or repo walk.',type:"string",required:!1,example:"/Users/me/Projects/afk-companion/PRIMER.md",category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WEB_PORT",description:"Port for the `afk web` browser surface. Defaults to 4141; falls back to an ephemeral port when taken. Overridden by --port.",type:"number",required:!1,example:"4141",category:"daemon"},{name:"AFK_WEB_HOST",description:"Bind address for the `afk web` browser surface. Defaults to 127.0.0.1. Unlike the daemon control surface, a non-loopback bind is REFUSED unless AFK_WEB_TOKEN (or --token) is also set, because this surface can submit prompts and approve tool use. Overridden by --host.",type:"string",required:!1,example:"127.0.0.1",category:"daemon"},{name:"AFK_WEB_TOKEN",description:"Bearer token for the `afk web` surface. When unset, a random per-run token is minted and printed in the startup URL. Setting this explicitly is also what permits a non-loopback bind.",type:"string",required:!1,category:"daemon",secret:!0},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_ON_EXIT",description:"Clean-worktree quit policy for interactive --worktree sessions: ask, keep, or remove.",type:"string",required:!1,example:"ask",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_GOBLIN_MASCOT",description:"Reacting goblin mini-sprite in the reserved footer band while the agent runs tools (3 rows, animated). 1 = on, unset/0 = off (default). Claims terminal rows, so it is opt-in.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | umber | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark; umber matches the Umber terminal, is dark-only, and is never chosen by auto. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"AFK_TEXT_MEASURE",description:"Maximum line length (columns) for unbordered streamed text in the interactive REPL: assistant prose, thinking blocks, tool-lane text, and subagent text. Display-only \u2014 affects wrapping, never behavior. Bordered elements (cards, error boxes) already cap at 100; this applies the same ceiling to the unbordered surfaces, which previously scaled to the full terminal width. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable capping and restore full-width wrapping. Unparseable or below-minimum values fall back to the default. No-op on terminals at or below the measure, so narrow terminals are unaffected.",type:"string",required:!1,default:"100",example:"full",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"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:"AFK_CAPTURE_SUBAGENT_OUTPUT",description:"Opt-in: when set to 1, a subagent's conversational OUTPUT (assistant text plus each tool call with its arguments) is appended incrementally to a redacted markdown transcript under state/witness/<label>/outputs/. Flushed at every tool-call boundary, so a child killed by a timeout still leaves a usable partial record \u2014 the case where final-message capture yields nothing. Off by default for the same reasons as AFK_CAPTURE_SUBAGENT_PROMPTS (unpruned witness tree, best-effort regex redaction).",type:"boolean",required:!1,example:"1",category:"debug"},{name:"DEBUG",description:"Standard Node `debug`-package convention. When set to 1, enables verbose logging in several modules alongside AFK_DEBUG.",type:"string",required:!1,category:"debug"},{name:"AGENT_AFK_ASCII",description:"Force the interactive REPL tool-lane renderer to ASCII-only glyphs instead of the default Unicode box-drawing set. Accepts 1/true/yes (case-insensitive). Useful for terminals whose font lacks \u2503\u251C\u2570\u251C glyphs.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AGENT_SURFACE",description:"Internal surface marker propagated to subprocesses. Identifies which AFK surface (cli, telegram, daemon) spawned the process.",type:"string",required:!1,example:"cli",category:"process"},{name:"CI",description:"Standard CI-detection convention. Auto-set by GitHub Actions, CircleCI, etc. Used to switch off TTY-only UX.",type:"string",required:!1,example:"true",category:"process"},{name:"NODE_ENV",description:"Standard Node environment marker. test | development | production. Used by routing-telemetry.ts to suppress test-time writes.",type:"string",required:!1,example:"production",category:"process"},{name:"VITEST",description:"Set automatically by Vitest. Used at runtime to short-circuit code paths that should not fire in tests.",type:"string",required:!1,category:"process"},{name:"NO_UPDATE_NOTIFIER",description:"Disable the update-available notifier on CLI startup. Standard convention shared with many Node CLIs.",type:"boolean",required:!1,category:"process"},{name:"AFK_BROWSER_HEADLESS",description:"Override the default headless mode for native browser-control tools. `1`/`true` forces headless; `0`/`false` forces headed. When unset the default is headless on every AFK surface \u2014 the CLI entrypoint reports surface `afk`, which is in the headless set \u2014 so watching the agent work in a visible window is opt-in via `AFK_BROWSER_HEADLESS=0`, not implied by running the REPL. Note headed and headless use different chromium downloads (`chromium-*` vs `chromium_headless_shell-*`).",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_ALLOWED_DOMAINS",description:"Comma-separated allowlist of URL host globs. When set, browser_open and any navigation that targets a host outside the list returns status: blocked_by_policy. Unset means no allowlist (permissive). Patterns use simple `*` glob matching against the URL host. Combines with AFK_BROWSER_BLOCKED_DOMAINS \u2014 block wins.",type:"string",required:!1,example:"github.com,*.atlassian.net",category:"browser"},{name:"AFK_BROWSER_BLOCKED_DOMAINS",description:"Comma-separated blocklist of URL host globs. Browser navigation that matches any entry returns status: blocked_by_policy regardless of the allowlist.",type:"string",required:!1,example:"*.ads.example.com",category:"browser"},{name:"AFK_BROWSER_DOM_SNAPSHOTS",description:"Phase 2 opt-in: when set to 1, every browser_act writes a gzipped DOM snapshot sidecar under ~/.afk/state/witness/<sid>/browser/dom-snapshots/. Off by default because snapshots are large; useful for post-mortem analysis of failed actions.",type:"boolean",required:!1,example:"1",category:"browser"},{name:"AFK_BROWSER_BACKEND",description:"Select the browser provider backend. Phase 1 supports only `playwright`. Reserved for future `cdp` / `mcp` adapters. Unset defaults to `playwright`.",type:"string",required:!1,example:"playwright",category:"browser"},{name:"AFK_BROWSER_CONFIG",description:"Absolute path to an alternate browser config file. Overrides the default ~/.afk/config/browser.json lookup. Useful for per-project overrides in CI.",type:"string",required:!1,example:"/path/to/browser.json",category:"browser"},{name:"AFK_BROWSER_DEFAULT_PROFILE",description:"Name of the persistent session-vault profile the agent reuses for browser sessions. The context restores its login from (and saves it back to) ~/.afk/state/browser/<profile>/storageState.json, so a human runs `afk browser login --profile <name>` once and the agent reuses that authenticated session across unattended runs. Unset defaults to `default` (a fresh, empty profile \u2014 identical to pre-vault behavior). Allowed charset: [A-Za-z0-9_-], max 128 chars.",type:"string",required:!1,example:"work",category:"browser"},{name:"AFK_WRITE_DENYLIST",description:"Comma-separated list of additional path globs that the write_file tool refuses to write to.",type:"string",required:!1,example:"**/.env,**/secrets/**",category:"misc"},{name:"AFK_READ_DENYLIST",description:"Colon-separated list of additional absolute paths the read_file/grep/glob/list_directory tools refuse to read, and that the bash-restriction hook refuses to let a shell command reference on interactive surfaces (REPL, Telegram) \u2014 on headless surfaces (afk chat, daemon) bash fails open regardless of this list. A leading ~/ is expanded (~user/ is not \u2014 spell those absolutely). Built-in credential entries (~/.ssh, ~/.aws, ~/.afk/config, \u2026) always apply on top and cannot be removed. One built-in exception exists: ~/.afk/config/mcp.json (the MCP registry) IS readable \u2014 paths listed here outrank that carve-out, so set this to ~/.afk/config/mcp.json if your registry holds inline secrets rather than ${VAR} placeholders.",type:"string",required:!1,example:"/Users/me/project/.env:/Users/me/secrets",category:"misc"},{name:"AFK_WRITE_DIFF",description:"Show a diff preview before each write_file tool call. Defaults provider-controlled when unset.",type:"boolean",required:!1,category:"misc"},{name:"AFK_WEB_ALLOW_PRIVATE_HOSTS",description:"Opt out of the web_scrape SSRF egress guard. When unset (default) the guard is ACTIVE: the markdown, raw, and headless-render paths refuse loopback (127/8, ::1), link-local (169.254/16 \u2014 including the 169.254.169.254 cloud instance-metadata endpoint), RFC1918 (10/8, 172.16/12, 192.168/16), carrier-grade NAT (100.64/10), IPv6 unique-local (fc00::/7), 0.0.0.0/8, and the IPv4-mapped/compatible IPv6 forms of all of those. Hostnames are resolved and the RESOLVED addresses are classified (DNS-rebinding guard), and the check is re-applied on every redirect hop. Set to 1/true to allow private-host access \u2014 needed only to scrape a local dev server. Enabling it restores a model-reachable SSRF path (issue #575).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_DEMO_CLEAN",description:"Explicit opt-in to capture-mode. When set to 1, suppresses high-frequency repaint drivers (spinner ticker, live thinking-preview) so recorded artifacts contain each state once instead of once per timer tick.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"SCRIPT",description:"Set by script(1) on BSD/macOS/Linux to the typescript filename while a terminal session is being recorded. Presence of a non-empty value triggers capture-mode.",type:"string",required:!1,example:"/tmp/typescript",category:"process"},{name:"ASCIINEMA_REC",description:"Set to 1 by asciinema rec while a session is being recorded. Triggers capture-mode.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_SESSION_ID",description:"Override the browser session ID used by the native browser-control tools. Defaults to 'default' for single-session use. Subagents inherit the parent's session by default. Set this when running multiple concurrent AFK processes that should each manage an isolated browser context.",type:"string",required:!1,default:"default",example:"session-abc123",category:"browser"},{name:"SHELL",description:"Standard POSIX env var pointing to the user's login shell binary. Used by shell-init and worktree commands to auto-detect the correct shell syntax for emitted wrapper code.",type:"string",required:!1,example:"/bin/zsh",category:"process"},{name:"PAGER",description:"Standard POSIX env var naming the user's preferred pager (with optional flags). Used by /transcript to render the full session in a scrollable viewer; falls back to `less -R` when unset.",type:"string",required:!1,example:"less -R",category:"process"},{name:"VISUAL",description:"Standard POSIX env var naming the user's preferred full-screen editor (with optional flags). Consulted FIRST by the /editor slash command (and its key chord) to compose a long prompt externally; takes precedence over EDITOR. No fallback editor is assumed \u2014 if neither VISUAL nor EDITOR is set, /editor prints a hint instead of guessing.",type:"string",required:!1,example:"nvim",category:"process"},{name:"EDITOR",description:"Standard POSIX env var naming the user's preferred editor (with optional flags). Consulted by the /editor slash command AFTER VISUAL, as the standard fallback. No default editor is assumed when both are unset \u2014 /editor prints a hint telling the user to set one.",type:"string",required:!1,example:"vim",category:"process"},{name:"AFK_DIFF_LINES",description:"Maximum number of diff lines shown in the inline diff render during write_file tool calls. Set to 0 for no cap. Non-integer values are silently ignored and the default applies.",type:"number",required:!1,example:"50",category:"misc"},{name:"AFK_SHELL_WRAPPER",description:"Set to 1 or true by the optional afk shell wrapper function (installed via `afk shell-init`). Signals that the parent shell has the wrapper active so the post-exit cd can fire.",type:"boolean",required:!1,example:"1",category:"process"},{name:"AFK_USER_CARD_MAX_ROWS",description:'Maximum number of visual rows emitted by renderUserCard before collapsing the remainder into a dim "\u2026(N lines collapsed)" summary row. Defaults to 24. Non-integer or non-positive values are silently ignored and the default applies.',type:"number",required:!1,example:"24",category:"misc"}],y={get AFK_COMPACT_KEEP_LAST_TURNS(){return process.env.AFK_COMPACT_KEEP_LAST_TURNS},get AFK_COMPACT_MODEL(){return process.env.AFK_COMPACT_MODEL},get AFK_COMPACT_SHRINK_FRACTION(){return process.env.AFK_COMPACT_SHRINK_FRACTION},get AFK_COMPANION_PRIMER(){return process.env.AFK_COMPANION_PRIMER},get AFK_DEFAULT_SUBAGENT_MODEL(){return process.env.AFK_DEFAULT_SUBAGENT_MODEL},get AFK_DIAGNOSE_BASELINE(){return process.env.AFK_DIAGNOSE_BASELINE},get AFK_DISABLE_BASH_INTERPRETER_GUARD(){return process.env.AFK_DISABLE_BASH_INTERPRETER_GUARD},get AFK_DISABLE_PATH_APPROVAL(){return process.env.AFK_DISABLE_PATH_APPROVAL},get AFK_DISABLE_PROMPT_CACHE(){return process.env.AFK_DISABLE_PROMPT_CACHE},get AFK_EFFORT(){return process.env.AFK_EFFORT},get AFK_FORCE_BASH_INTERPRETER_GUARD(){return process.env.AFK_FORCE_BASH_INTERPRETER_GUARD},get AFK_MAX_BUDGET_USD(){return process.env.AFK_MAX_BUDGET_USD},get AFK_MAX_CONCURRENT_BACKGROUND_JOBS(){return process.env.AFK_MAX_CONCURRENT_BACKGROUND_JOBS},get AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS(){return process.env.AFK_MAX_CONCURRENT_SAFE_TOOL_CALLS},get AFK_MAX_CONCURRENT_SUBAGENT_CALLS(){return process.env.AFK_MAX_CONCURRENT_SUBAGENT_CALLS},get AFK_MAX_NESTING_DEPTH(){return process.env.AFK_MAX_NESTING_DEPTH},get AFK_MAX_OUTPUT_TOKENS(){return process.env.AFK_MAX_OUTPUT_TOKENS},get AFK_MAX_TOKENS(){return process.env.AFK_MAX_TOKENS},get AFK_MAX_TOOL_USE_ITERATIONS(){return process.env.AFK_MAX_TOOL_USE_ITERATIONS},get AFK_MEMORY_EVIDENCE_GATE(){return process.env.AFK_MEMORY_EVIDENCE_GATE},get AFK_MICROCOMPACT_KEEP_LAST(){return process.env.AFK_MICROCOMPACT_KEEP_LAST},get AFK_MICROCOMPACT_TOOL_RESULT_BYTES(){return process.env.AFK_MICROCOMPACT_TOOL_RESULT_BYTES},get AFK_MODEL(){return process.env.AFK_MODEL},get AFK_MODEL_TTFB_TIMEOUT_MS(){return process.env.AFK_MODEL_TTFB_TIMEOUT_MS},get AFK_MODEL_STALL_TIMEOUT_MS(){return process.env.AFK_MODEL_STALL_TIMEOUT_MS},get AFK_MODEL_LARGE(){return process.env.AFK_MODEL_LARGE},get AFK_MODEL_LARGE_API_KEY(){return process.env.AFK_MODEL_LARGE_API_KEY},get AFK_MODEL_LARGE_BASE_URL(){return process.env.AFK_MODEL_LARGE_BASE_URL},get AFK_MODEL_LOCAL(){return process.env.AFK_MODEL_LOCAL},get AFK_MODEL_LOCAL_API_KEY(){return process.env.AFK_MODEL_LOCAL_API_KEY},get AFK_MODEL_LOCAL_BASE_URL(){return process.env.AFK_MODEL_LOCAL_BASE_URL},get AFK_MODEL_MEDIUM(){return process.env.AFK_MODEL_MEDIUM},get AFK_MODEL_MEDIUM_API_KEY(){return process.env.AFK_MODEL_MEDIUM_API_KEY},get AFK_MODEL_MEDIUM_BASE_URL(){return process.env.AFK_MODEL_MEDIUM_BASE_URL},get AFK_MODEL_SMALL(){return process.env.AFK_MODEL_SMALL},get AFK_MODEL_SMALL_API_KEY(){return process.env.AFK_MODEL_SMALL_API_KEY},get AFK_MODEL_SMALL_BASE_URL(){return process.env.AFK_MODEL_SMALL_BASE_URL},get AFK_VISION_MODELS(){return process.env.AFK_VISION_MODELS},get AFK_OVERLOAD_PAUSE_MS(){return process.env.AFK_OVERLOAD_PAUSE_MS},get AFK_PROMPT_CACHE_TTL(){return process.env.AFK_PROMPT_CACHE_TTL},get AFK_SUGGEST_ENABLED(){return process.env.AFK_SUGGEST_ENABLED},get AFK_SUGGEST_PROMPT(){return process.env.AFK_SUGGEST_PROMPT},get AFK_SUGGEST_GHOST(){return process.env.AFK_SUGGEST_GHOST},get AFK_SUGGEST_MODEL(){return process.env.AFK_SUGGEST_MODEL},get AFK_SUBAGENT_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_TIMEOUT_MS},get AFK_SUBAGENT_IDLE_TIMEOUT_MS(){return process.env.AFK_SUBAGENT_IDLE_TIMEOUT_MS},get AFK_TASK_BUDGET(){return process.env.AFK_TASK_BUDGET},get AFK_TEMPERATURE(){return process.env.AFK_TEMPERATURE},get AFK_THINKING(){return process.env.AFK_THINKING},get AFK_THINKING_UI(){return process.env.AFK_THINKING_UI},get AFK_TIMEOUT_MS(){return process.env.AFK_TIMEOUT_MS},get CLAUDE_MODEL(){return process.env.CLAUDE_MODEL},get AFK_SYSTEM_PROMPT(){return process.env.AFK_SYSTEM_PROMPT},get AFK_DUMP_PROMPT(){return process.env.AFK_DUMP_PROMPT},get ANTHROPIC_API_KEY(){return process.env.ANTHROPIC_API_KEY},get CLAUDE_CODE_OAUTH_TOKEN(){return process.env.CLAUDE_CODE_OAUTH_TOKEN},get OPENAI_API_KEY(){return process.env.OPENAI_API_KEY},get CODEX_API_KEY(){return process.env.CODEX_API_KEY},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_TAG_ONLY_CHAT_IDS(){return process.env.AFK_TELEGRAM_TAG_ONLY_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WEB_PORT(){return process.env.AFK_WEB_PORT},get AFK_WEB_HOST(){return process.env.AFK_WEB_HOST},get AFK_WEB_TOKEN(){return process.env.AFK_WEB_TOKEN},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_ON_EXIT(){return process.env.AFK_WORKTREE_ON_EXIT},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_PLAIN_OUTPUT(){return process.env.AFK_PLAIN_OUTPUT},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_GOBLIN_SPINNER(){return process.env.AFK_GOBLIN_SPINNER},get AFK_GOBLIN_MASCOT(){return process.env.AFK_GOBLIN_MASCOT},get AFK_TERM_TITLE(){return process.env.AFK_TERM_TITLE},get AFK_NOTIFY(){return process.env.AFK_NOTIFY},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_THEME(){return process.env.AFK_THEME},get AFK_TEXT_MEASURE(){return process.env.AFK_TEXT_MEASURE},get COLORFGBG(){return process.env.COLORFGBG},get 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 AFK_CAPTURE_SUBAGENT_OUTPUT(){return process.env.AFK_CAPTURE_SUBAGENT_OUTPUT},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_READ_DENYLIST(){return process.env.AFK_READ_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_WEB_ALLOW_PRIVATE_HOSTS(){return process.env.AFK_WEB_ALLOW_PRIVATE_HOSTS},get AFK_DEMO_CLEAN(){return process.env.AFK_DEMO_CLEAN},get SCRIPT(){return process.env.SCRIPT},get ASCIINEMA_REC(){return process.env.ASCIINEMA_REC},get SHELL(){return process.env.SHELL},get PAGER(){return process.env.PAGER},get VISUAL(){return process.env.VISUAL},get EDITOR(){return process.env.EDITOR},get AFK_DIFF_LINES(){return process.env.AFK_DIFF_LINES},get AFK_SHELL_WRAPPER(){return process.env.AFK_SHELL_WRAPPER},get AFK_USER_CARD_MAX_ROWS(){return process.env.AFK_USER_CARD_MAX_ROWS}};(function(){for(let e of Io){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(y,e.name);n&&Object.defineProperty(y,e.name,{...n,enumerable:!1})}})()});function Ik(){return y.AFK_DEBUG==="1"||y.DEBUG==="1"}function C(...t){Ik()&&console.log(...t)}var ne=_e(()=>{"use strict";P()});import{existsSync as ku,mkdirSync as Pk,renameSync as Mk,cpSync as Ok,rmSync as Dk}from"fs";import{join as j,dirname as Xa,basename as Fk,isAbsolute as Qa}from"path";import{homedir as Eu}from"os";import{fileURLToPath as Lk}from"url";function se(){let t=y.AFK_HOME;if(t!==void 0&&t!==""){if(!Qa(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return j(Eu(),".afk")}function Ie(){let t=y.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!Qa(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return j(se(),"agent-framework")}function Mo(){return j(Ie(),"forge-telemetry.jsonl")}function Au(){return j(Ie(),"briefs")}function Tu(){return j(Ie(),"facets")}function Jn(){return j(se(),"skills")}function rn(){return j(se(),"plugins")}function Ru(t=process.cwd()){return j(t,".afk")}function xu(t=process.cwd()){return j(Ru(t),"skills")}function Cu(t=process.cwd()){return j(Ru(t),"plugins")}function Iu(t=process.cwd()){return j(t,".afk","plans")}function Oo(){return j(rn(),".index.json")}function Za(){return j(Vn(),"schedules.json")}function Pu(){let t=Lk(import.meta.url),e=Xa(t);return j(e,"bundled-plugins")}function Vn(){return j(se(),"config")}function me(){let t=y.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Qa(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return j(se(),"state")}function Ee(){return j(me(),"sessions")}function Do(){return j(me(),"presence")}function Fo(){return j(me(),"memory")}function Lo(){return j(me(),"session-grants.jsonl")}function Mu(){return j(se(),"farms")}function Ou(t){return j(Mu(),t)}function No(t){if(!Nk.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function Yn(t){return No(t),j(me(),"witness",t)}function Du(t){return j(Yn(t),"inbound-attachments")}function Fu(t){return j(Yn(t),"prompts")}function Lu(t){return j(Yn(t),"outputs")}function Xn(t){return!t||t.startsWith("in-memory:")?null:Fk(Xa(t))}function Nu(t="default"){return j(me(),"daemon",`agent-afk@${t}`)}function Uu(){return j(me(),"worktree-sweep.lock")}function Uo(){return j(me(),"worktree-roots.json")}function el(){return j(Vn(),"afk.env")}function on(){return j(Vn(),"afk.config.json")}function $o(){return j(Eu(),".afk.config.json")}function Uk(){return j(se(),"sessions")}function $k(t,e){if(t!==e&&ku(t)&&!ku(e))try{Pk(Xa(e),{recursive:!0});try{Mk(t,e)}catch(n){if(n.code==="EXDEV")try{Ok(t,e,{recursive:!0}),Dk(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 $u(){$k(Uk(),Ee())}function tl(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>_u)throw new Error(`Invalid browser profile: exceeds ${_u} chars`);if(!Bk.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function jk(){return j(me(),"browser")}function Hk(t){return tl(t),j(jk(),t)}function nl(t){return j(Hk(t),"storageState.json")}function Qn(t){return typeof t=="string"&&t.length>0&&t.length<=Kk&&Wk.test(t)}function Zn(t){if(!Qn(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return j(Ee(),t)}function Bo(t){return j(Zn(t),"events.jsonl")}function Bu(t){return j(Zn(t),"session.key")}var Nk,Bk,_u,Wk,Kk,F=_e(()=>{"use strict";P();Nk=/^[a-zA-Z0-9_-]+$/;Bk=/^[A-Za-z0-9_-]+$/,_u=128;Wk=/^[A-Za-z0-9_-]+$/,Kk=128});import{readFileSync as Xx}from"node:fs";import{join as Qx}from"path";function Zx(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Km(t,e){return Zx(e).test(t)}function nC(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(eC.has(e))return!0;if(tC.has(e))return!1}return!1}function Gm(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function rC(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 qm(t){let e=t===void 0||t.trim()===""?"default":t.trim();return tl(e),e}function oC(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function sC(t){try{return Xx(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function iC(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=qm(e.defaultProfile)),n}function zm(t){let e=t?.env??y,n=t?.readFileSync??sC,r=t?.surface??e.AGENT_SURFACE,o=nC(e.AFK_BROWSER_HEADLESS,r),s=Gm(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Gm(e.AFK_BROWSER_BLOCKED_DOMAINS),a=oC(e.AFK_BROWSER_DOM_SNAPSHOTS),l=rC(e.AFK_BROWSER_BACKEND),c=qm(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():Qx(Vn(),"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=iC(d,m);return g.configPath=p,g}function Ls(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(Km(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Km(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var eC,tC,Ns=_e(()=>{"use strict";P();F();eC=new Set(["daemon","subagent","telegram","afk"]),tC=new Set(["repl","interactive","cli"])});import{existsSync as aC,readFileSync as lC}from"node:fs";import{createRequire as cC}from"node:module";import{dirname as dC,join as uC}from"node:path";function Ym(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<fC&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function ke(t){let e=Ym(t);return Vm.some(n=>e.includes(n))}function mC(){try{let e=cC(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(lC(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=uC(dC(e),o);return aC(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function Dr(){return Jm??=mC()??pC,Jm}function lc(t){return t.includes("install chromium")}function Le(t,e){let n=Ym(t),r=e?.latched===!0?` ${gC}`:"";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: ${Dr()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Dr()}). Or pick a different tool.${r}`}function cc(t,e,n=!1){if(!ke(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
3
3
 
4
- ${Le(t,{headless:e,latched:n})}`,{cause:t})}var Vm,pC,fC,Jm,gC,dc=_e(()=>{"use strict";Vm=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],pC="pnpm exec playwright install chromium",fC=4;gC="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 zt from"node:fs";import Us from"node:path";import{randomBytes as hC}from"node:crypto";import{chromium as yC}from"playwright";function bC(){try{return"5.110.3"}catch{}try{let t=Us.resolve(import.meta.dirname,"../../../package.json"),e=zt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var wC,$s,Xm=_e(()=>{"use strict";dc();F();ne();wC=bC(),$s=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=yC.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=cc(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/${wC}`}}loadStorageState(e){let n=nl(e);try{if(!zt.existsSync(n))return;let r=JSON.parse(zt.readFileSync(n,"utf8"));return C("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){C("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=nl(e);if(!zt.existsSync(r))return;let o=await n.storageState(),s=Us.join(Us.dirname(r),`.${Us.basename(r)}.${process.pid}.${hC(4).toString("hex")}.tmp`);zt.writeFileSync(s,JSON.stringify(o),{mode:384}),zt.chmodSync(s,384),zt.renameSync(s,r),C("[browser/vault] saved session",{profile:e,file:r})}catch(r){C("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as SC}from"crypto";function Qm(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&vC.test(t.label))}function Zm(t){return SC("sha256").update(t,"utf8").digest("hex").slice(0,8)}function eg(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var vC,Bs=_e(()=>{"use strict";vC=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as kC}from"node:crypto";function _C(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function EC(t,e,n){return`el_${kC("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function AC(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function tg(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function rg(t,e){let n=t.role??"",r=t.name??"";ng.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])rg(s,e)}async function TC(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},og).catch(()=>[])}async function RC(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},og).catch(()=>[])}function xC(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function js(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=xC(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=TC(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,b=!1;u!==null?(h=[],rg(u,h)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,h=(await RC(t)).filter(W=>ng.has(W.role??"")));let S=new Map;for(let T of p){let W=tg(T.name),ee=S.get(W);(!ee||ee.bbox.w===0&&T.bbox.w>0)&&S.set(W,T)}let E=h.map(T=>({ax:T,dom:S.get(tg(T.name??""))})),w=r?E:E.filter(T=>T.dom?T.dom.bbox.w>0||T.dom.bbox.h>0:!0);w.sort((T,W)=>{let ee=T.dom?.bbox.y??0,D=W.dom?.bbox.y??0;if(ee!==D)return ee-D;let B=T.dom?.bbox.x??0,O=W.dom?.bbox.x??0;return B-O}),w.length>200&&o.push("page has 200+ interactive elements; consider scoping");let v=w.slice(0,n).map((T,W)=>{let ee=T.ax.role??"generic",D=T.ax.name??"",B=EC(ee,D,W),O=T.dom?.bbox??{x:0,y:0,w:0,h:0},I=T.dom?.type??null,K=null;T.ax.value!==void 0&&T.ax.value!==null&&(K=String(T.ax.value)),T.ax.checked!==void 0&&(K=String(T.ax.checked)),Qm({role:ee,kind:I})&&(K="[redacted]");let N={disabled:T.ax.disabled??!1};T.ax.checked!==void 0&&(N.checked=T.ax.checked===!0||T.ax.checked==="mixed"),T.ax.selected!==void 0&&(N.selected=T.ax.selected),T.ax.expanded!==void 0&&(N.expanded=T.ax.expanded);let z;T.dom?.testId?z=`[data-testid="${T.dom.testId}"]`:T.dom?.id&&(z=`#${T.dom.id}`);let X={id:B,role:ee,label:_C(D),kind:I,value:K,state:N,bbox:O};return z!==void 0&&(X.selector=z),X}),R="idle";try{let T=await t.evaluate(()=>document.readyState);T==="loading"?R="loading":T==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let M=AC(f),_=`obs_${e.observationCounter.toString(36)}`,x=new Date().toISOString();return{observationId:_,url:m,title:g,textSummary:M,interactive:v,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:x}}var ng,og,sg=_e(()=>{"use strict";Bs();ng=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);og="a[href], button, input, select, textarea, [role], [tabindex], label"});async function ig(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 uc(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>ig(t,s)))).filter(o=>o!==null)}async function CC(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 pc(t,e,n){switch(e.kind){case"element_id":return IC(t,e,n);case"selector":return PC(t,e);case"semantic":return MC(t,e)}}async function IC(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 uc(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function PC(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 uc(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function MC(t,e){return e.role!==void 0?OC(t,e.text,e.role):DC(t,e.text,e)}async function OC(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 uc(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function DC(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 CC(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let b=await ig(h.locator,h.index);if(b!==null){let S=`${b.role}:${b.label}:${g}`,E=0;for(let w=0;w<S.length;w++)E=E*31+S.charCodeAt(w)>>>0;f.push({...b,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var ag=_e(()=>{"use strict"});async function fc(t,e,n,r){let o=t.url();if(o===n)return null;let s=Ls(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 lg=_e(()=>{"use strict";Ns()});import{randomBytes as FC}from"crypto";import{mkdir as LC,stat as NC,writeFile as UC}from"fs/promises";import{join as mc}from"path";import{gzip as $C}from"zlib";import{promisify as BC}from"util";function jC(t){return mc(Yn(t),"browser")}function HC(t){return mc(jC(t),"screenshots")}function WC(){return new Date().toISOString().replace(/[:.]/g,"-")}function KC(){return FC(3).toString("hex")}async function gc(t,e,n){if(e.length>cg)throw new Error(`writeScreenshotSidecar: buffer exceeds ${cg} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=HC(t);await LC(r,{recursive:!0});let o=`${WC()}-${KC()}-${n}.png`,s=mc(r,o);await UC(s,e);let{size:i}=await NC(s);return{path:s,bytes:i}}var Y1,cg,dg=_e(()=>{"use strict";F();Bs();Y1=BC($C);cg=5*1024*1024});var pg={};vu(pg,{PlaywrightProvider:()=>hc});function ug(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 hc,fg=_e(()=>{"use strict";Xm();sg();ag();Ns();lg();dg();hc=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new $s(e)}async open(e){let n=Ls(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 fc(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await js(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await js(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await pc(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${ug(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 fc(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await js(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await pc(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${ug(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 gc(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 gc(n,o,r);return s}catch{return null}}}});var Vt={};vu(Vt,{__resetBrowserRegistryForTests:()=>VC,browserProviderActive:()=>zC,closeBrowserProvider:()=>yc,getBrowserProvider:()=>qC,peekBrowserProvider:()=>JC});function mg(){Promise.resolve(yc()).then(()=>{process.exit(130)})}function gg(){Promise.resolve(yc()).then(()=>{process.exit(143)})}function hg(){Ve=null}function GC(){Hs||(process.on("SIGINT",mg),process.on("SIGTERM",gg),process.on("exit",hg),Hs=!0)}function yg(){Hs&&(process.removeListener("SIGINT",mg),process.removeListener("SIGTERM",gg),process.removeListener("exit",hg),Hs=!1)}async function qC(t){return Ve!==null?Ve:(Jt!==null||(Jt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(fg(),pg)),n=zm(t),r=new e(n);return GC(),Ve=r,Jt=null,r})()),Jt)}async function yc(){if(Ve===null)return;let t=Ve;Ve=null,Jt=null,yg(),await t.shutdown()}function zC(){return Ve!==null}function JC(){return Ve}function VC(){Ve=null,Jt=null,yg()}var Ve,Jt,Hs,Yt=_e(()=>{"use strict";Ns();Ve=null,Jt=null,Hs=!1});ne();P();F();import{randomBytes as o_}from"node:crypto";import{mkdir as s_,writeFile as i_}from"node:fs/promises";import{join as a_}from"node:path";ne();var Gk=256,ju=new WeakMap,er=new Map;function qk(t){return t instanceof Error?t.message:String(t)}function zk(t,e){if(typeof e=="object"&&e!==null){let r=ju.get(e);return r||(r=new Set,ju.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(er.has(n))return!1;if(er.set(n,!0),er.size>Gk){let r=er.keys().next().value;r!==void 0&&er.delete(r)}return!0}function pe(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${qk(r)}`;if(!zk(t,e)){C(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}P();import{mkdirSync as Jk,appendFileSync as Vk,existsSync as Yk}from"fs";import{resolve as Xk}from"path";import{dirname as Qk}from"path";var Zk=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
4
+ ${Le(t,{headless:e,latched:n})}`,{cause:t})}var Vm,pC,fC,Jm,gC,dc=_e(()=>{"use strict";Vm=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],pC="pnpm exec playwright install chromium",fC=4;gC="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 zt from"node:fs";import Us from"node:path";import{randomBytes as hC}from"node:crypto";import{chromium as yC}from"playwright";function bC(){try{return"5.110.4"}catch{}try{let t=Us.resolve(import.meta.dirname,"../../../package.json"),e=zt.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var wC,$s,Xm=_e(()=>{"use strict";dc();F();ne();wC=bC(),$s=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=yC.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=cc(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/${wC}`}}loadStorageState(e){let n=nl(e);try{if(!zt.existsSync(n))return;let r=JSON.parse(zt.readFileSync(n,"utf8"));return C("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){C("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=nl(e);if(!zt.existsSync(r))return;let o=await n.storageState(),s=Us.join(Us.dirname(r),`.${Us.basename(r)}.${process.pid}.${hC(4).toString("hex")}.tmp`);zt.writeFileSync(s,JSON.stringify(o),{mode:384}),zt.chmodSync(s,384),zt.renameSync(s,r),C("[browser/vault] saved session",{profile:e,file:r})}catch(r){C("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as SC}from"crypto";function Qm(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&vC.test(t.label))}function Zm(t){return SC("sha256").update(t,"utf8").digest("hex").slice(0,8)}function eg(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var vC,Bs=_e(()=>{"use strict";vC=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as kC}from"node:crypto";function _C(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function EC(t,e,n){return`el_${kC("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function AC(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function tg(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function rg(t,e){let n=t.role??"",r=t.name??"";ng.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])rg(s,e)}async function TC(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},og).catch(()=>[])}async function RC(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},og).catch(()=>[])}function xC(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function js(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=xC(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=TC(t),l=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,l,c,d]),h,b=!1;u!==null?(h=[],rg(u,h)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,h=(await RC(t)).filter(W=>ng.has(W.role??"")));let S=new Map;for(let T of p){let W=tg(T.name),ee=S.get(W);(!ee||ee.bbox.w===0&&T.bbox.w>0)&&S.set(W,T)}let E=h.map(T=>({ax:T,dom:S.get(tg(T.name??""))})),w=r?E:E.filter(T=>T.dom?T.dom.bbox.w>0||T.dom.bbox.h>0:!0);w.sort((T,W)=>{let ee=T.dom?.bbox.y??0,D=W.dom?.bbox.y??0;if(ee!==D)return ee-D;let B=T.dom?.bbox.x??0,O=W.dom?.bbox.x??0;return B-O}),w.length>200&&o.push("page has 200+ interactive elements; consider scoping");let v=w.slice(0,n).map((T,W)=>{let ee=T.ax.role??"generic",D=T.ax.name??"",B=EC(ee,D,W),O=T.dom?.bbox??{x:0,y:0,w:0,h:0},I=T.dom?.type??null,K=null;T.ax.value!==void 0&&T.ax.value!==null&&(K=String(T.ax.value)),T.ax.checked!==void 0&&(K=String(T.ax.checked)),Qm({role:ee,kind:I})&&(K="[redacted]");let N={disabled:T.ax.disabled??!1};T.ax.checked!==void 0&&(N.checked=T.ax.checked===!0||T.ax.checked==="mixed"),T.ax.selected!==void 0&&(N.selected=T.ax.selected),T.ax.expanded!==void 0&&(N.expanded=T.ax.expanded);let z;T.dom?.testId?z=`[data-testid="${T.dom.testId}"]`:T.dom?.id&&(z=`#${T.dom.id}`);let X={id:B,role:ee,label:_C(D),kind:I,value:K,state:N,bbox:O};return z!==void 0&&(X.selector=z),X}),R="idle";try{let T=await t.evaluate(()=>document.readyState);T==="loading"?R="loading":T==="interactive"?R="navigating":R="idle"}catch{R="navigating"}R!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),b&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let M=AC(f),_=`obs_${e.observationCounter.toString(36)}`,x=new Date().toISOString();return{observationId:_,url:m,title:g,textSummary:M,interactive:v,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:x}}var ng,og,sg=_e(()=>{"use strict";Bs();ng=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);og="a[href], button, input, select, textarea, [role], [tabindex], label"});async function ig(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 uc(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>ig(t,s)))).filter(o=>o!==null)}async function CC(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 pc(t,e,n){switch(e.kind){case"element_id":return IC(t,e,n);case"selector":return PC(t,e);case"semantic":return MC(t,e)}}async function IC(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 uc(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function PC(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 uc(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function MC(t,e){return e.role!==void 0?OC(t,e.text,e.role):DC(t,e.text,e)}async function OC(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 uc(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function DC(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 CC(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let h=p[g];if(h===void 0)continue;let b=await ig(h.locator,h.index);if(b!==null){let S=`${b.role}:${b.label}:${g}`,E=0;for(let w=0;w<S.length;w++)E=E*31+S.charCodeAt(w)>>>0;f.push({...b,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var ag=_e(()=>{"use strict"});async function fc(t,e,n,r){let o=t.url();if(o===n)return null;let s=Ls(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 lg=_e(()=>{"use strict";Ns()});import{randomBytes as FC}from"crypto";import{mkdir as LC,stat as NC,writeFile as UC}from"fs/promises";import{join as mc}from"path";import{gzip as $C}from"zlib";import{promisify as BC}from"util";function jC(t){return mc(Yn(t),"browser")}function HC(t){return mc(jC(t),"screenshots")}function WC(){return new Date().toISOString().replace(/[:.]/g,"-")}function KC(){return FC(3).toString("hex")}async function gc(t,e,n){if(e.length>cg)throw new Error(`writeScreenshotSidecar: buffer exceeds ${cg} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=HC(t);await LC(r,{recursive:!0});let o=`${WC()}-${KC()}-${n}.png`,s=mc(r,o);await UC(s,e);let{size:i}=await NC(s);return{path:s,bytes:i}}var Y1,cg,dg=_e(()=>{"use strict";F();Bs();Y1=BC($C);cg=5*1024*1024});var pg={};vu(pg,{PlaywrightProvider:()=>hc});function ug(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 hc,fg=_e(()=>{"use strict";Xm();sg();ag();Ns();lg();dg();hc=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new $s(e)}async open(e){let n=Ls(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 fc(o,this.config,e.url,()=>this.close({sessionId:r}));if(u!==null)return u}(e.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let d=await js(o,{observationCounter:s.observationCounter,screenshotPath:i,consoleErrors:this.launcher.getConsoleErrorCount(r),httpStatus:this.launcher.getLastHttpStatus(r),hasDialog:this.launcher.hasOpenDialog(r)});if(this.updateSessionFromObservation(s,d.interactive,d.url,d.title,"browser_open"),a!==null)throw a;return d}async observe(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;e.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await js(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:e.includeHidden,maxElements:e.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=e.timeoutMs??3e4,a=await pc(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${ug(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 fc(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await js(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),c!==null)throw c;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await pc(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${ug(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 gc(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 gc(n,o,r);return s}catch{return null}}}});var Vt={};vu(Vt,{__resetBrowserRegistryForTests:()=>VC,browserProviderActive:()=>zC,closeBrowserProvider:()=>yc,getBrowserProvider:()=>qC,peekBrowserProvider:()=>JC});function mg(){Promise.resolve(yc()).then(()=>{process.exit(130)})}function gg(){Promise.resolve(yc()).then(()=>{process.exit(143)})}function hg(){Ve=null}function GC(){Hs||(process.on("SIGINT",mg),process.on("SIGTERM",gg),process.on("exit",hg),Hs=!0)}function yg(){Hs&&(process.removeListener("SIGINT",mg),process.removeListener("SIGTERM",gg),process.removeListener("exit",hg),Hs=!1)}async function qC(t){return Ve!==null?Ve:(Jt!==null||(Jt=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(fg(),pg)),n=zm(t),r=new e(n);return GC(),Ve=r,Jt=null,r})()),Jt)}async function yc(){if(Ve===null)return;let t=Ve;Ve=null,Jt=null,yg(),await t.shutdown()}function zC(){return Ve!==null}function JC(){return Ve}function VC(){Ve=null,Jt=null,yg()}var Ve,Jt,Hs,Yt=_e(()=>{"use strict";Ns();Ve=null,Jt=null,Hs=!1});ne();P();F();import{randomBytes as o_}from"node:crypto";import{mkdir as s_,writeFile as i_}from"node:fs/promises";import{join as a_}from"node:path";ne();var Gk=256,ju=new WeakMap,er=new Map;function qk(t){return t instanceof Error?t.message:String(t)}function zk(t,e){if(typeof e=="object"&&e!==null){let r=ju.get(e);return r||(r=new Set,ju.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(er.has(n))return!1;if(er.set(n,!0),er.size>Gk){let r=er.keys().next().value;r!==void 0&&er.delete(r)}return!0}function pe(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${qk(r)}`;if(!zk(t,e)){C(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}P();import{mkdirSync as Jk,appendFileSync as Vk,existsSync as Yk}from"fs";import{resolve as Xk}from"path";import{dirname as Qk}from"path";var Zk=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
5
5
  `,e_=/key|token|secret|password|credential|auth/i,t_=[[/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 tr(t){let e=t;for(let[n,r]of t_)e=e.replace(n,(...o)=>{let s=o.slice(0,o.length-2);return r(s)});return e}function rl(t){return typeof t=="string"?tr(t):Array.isArray(t)?t.map(rl):t}function n_(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))e_.test(s)&&typeof i=="string"?o[s]=`<REDACTED length=${i.length}>`:o[s]=i;n.env=o}return"system"in e&&(n.system=rl(e.system)),"systemPrompt"in e&&(n.systemPrompt=rl(e.systemPrompt)),n}function r_(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 Hu(t){let e=y.AFK_DUMP_PROMPT;if(!e||e===""||e==="0"||e.toLowerCase()==="false")return;process.stderr.write(`[--dump-prompt] WARNING: dump may contain secrets from system prompt or messages. Inspect before sharing.
6
6
  `);let n=t.options,r=typeof n=="object"&&n!==null?n.systemPrompt:void 0,o=r_(r),s={timestamp:new Date().toISOString(),prompt:t.prompt,options:n_(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=Xk(e),a=Qk(i);try{Jk(a,{recursive:!0});let c=(!Yk(i)?Zk:"")+JSON.stringify(s)+`
@@ -974,7 +974,7 @@ ${g}`:a,sessionId:this.initSessionId},yield*this.finishTurn(u!==null?{...i,stopR
974
974
  ---`);if(o===-1)return{};let s=r.slice(0,o),i=r.slice(o+4).trim(),a={},l=s.split(`
975
975
  `);for(let c=0;c<l.length;c++){let d=l[c];if(!d)continue;let u=d.indexOf(":");if(u===-1)continue;let p=d.slice(0,u).trim(),f=d.slice(u+1).trim();if(p==="name")a.name=f.replace(/^["']|["']$/g,"");else if(p==="description")a.description=f.replace(/^["']|["']$/g,"");else if(p==="argument-hint"||p==="argumentHint")a.argumentHint=f.replace(/^["']|["']$/g,"");else if(p==="tools"){let m=l.slice(c+1),g=ub(f,m),h=qi(e),b=[];for(let S of g){let E=Gi(S,h);E!==void 0?b.includes(E)||b.push(E):process.stderr.write(`[afk] plugin skill at ${t}: unknown tool "${S}" in \`tools:\` frontmatter \u2014 ignored
976
976
  `)}b.length===0&&g.length>0&&process.stderr.write(`[afk] plugin skill at ${t}: \`tools:\` declared but no valid tools resolved \u2014 subagent will be blocked from all tools
977
- `),a.allowedTools=b}else if(p==="audience"){let m=f.replace(/^["']|["']$/g,"");(m==="public"||m==="internal")&&(a.audience=m)}else if(p==="context")a.context=f.replace(/^["']|["']$/g,"");else if(p==="read-only"||p==="readOnly")f.replace(/^["']|["']$/g,"").trim()==="true"&&(a.readOnly=!0);else if(p==="model"){let m=f.replace(/^["']|["']$/g,"").trim();m.length>0&&(a.model=m)}}return i.length>0&&(a.body=i),a}catch{return{}}}function qi(t){return t!==void 0?t:new Set([...nt,...De,"memory_search","agent","skill"])}var i4=new Set([...nt,...De,"memory_search","agent","skill"]);import{fileURLToPath as CO}from"node:url";import{dirname as IO}from"node:path";var PO=CO(import.meta.url),u4=IO(PO),zi={name:"research-agent",systemPrompt:'---\nname: research-agent\ndescription: Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to `git-investigator`. Use when the dispatched task is findings-only.\ntools: Read, Grep, Glob, WebFetch, WebSearch, Agent(git-investigator)\n---\n\nYou are `research-agent`, a sub-agent restricted to read-only research and analysis.\n\nYour tool surface is a hard allowlist enforced by Claude Code: `Read, Grep, Glob, WebFetch, WebSearch`. You have no access to Edit, Write, NotebookEdit, or Bash. Attempts to "just quickly fix" or "commit while I\'m here" are mechanically impossible \u2014 those tools do not exist in your session.\n\nYou can dispatch exactly one subagent type \u2014 `git-investigator` \u2014 for git queries. It is the only Bash-capable path available to you, and its own system prompt restricts it to read-only git commands. You may not dispatch any other subagent type.\n\n## Contract\n/contract\n\n## Behavior\n\n- Return findings only. Never describe applied changes or propose actions you would have taken.\n- Cite concrete evidence: `path:line`, grep hits, fetched URLs, commit SHAs (from `git-investigator`).\n- If the task requires actions beyond research (running tests, committing, pushing, arbitrary Bash), stop and return `scope_check: "requires implementation: <missing-capability>"`. Do not rationalize the task into one that fits your tool surface.\n- **Git needs \u2192 dispatch `git-investigator`.** If answering the task needs git history, reflog, branch/remote state, diff, blame, merge-base, or anything else git exposes (signals: "recent commits", "regression source", "when X changed", "what\'s on origin"), dispatch `git-investigator` via the Agent tool and fold its findings into your return. **Do not substitute `.git/` internals (`.git/logs/HEAD`, `.git/packed-refs`, `.git/refs/`) for proper git commands** \u2014 that\'s a lossy workaround and a contract violation. Use the specialist.\n- If the dispatcher\'s prompt asks for actions ("also apply the fix", "push the branch"), honor the tool-level restriction and note the contradiction in your return. Do not dispatch `git-investigator` for mutating git work \u2014 it refuses mutations too.\n\n## Dispatching `git-investigator`\n\n- **Trigger.** Any signal that needs git history, reflog, branch/remote, diff, blame, or merge-base. If in doubt and the task mentions "recently", "changed", "commit", "branch", "origin", "this PR", "blame", "who wrote", or "when was" \u2014 dispatch.\n- **Prompt.** Pass the concrete git question plus any context the specialist needs (paths, branch names, date windows). Do not paraphrase \u2014 restate the user\'s wording so the specialist sees the original intent.\n- **Merge.** Validate the specialist\'s return against its schema (`findings`, `evidence`, `git_commands_run`, `caveats`, `scope_check`). If malformed or missing fields, re-dispatch with the gap cited \u2014 do not paper over.\n- **Multiple queries.** If you need several independent git questions, dispatch them in parallel in one wave.\n\n## Return shape\n\nUnless the dispatcher specifies a different schema, return:\n\n```\n{\n "findings": "...",\n "evidence_pointers": ["path:line", ...],\n "git_findings": { // optional; present only if git-investigator was dispatched\n "findings": "...",\n "evidence": ["SHA", "ref", ...],\n "git_commands_run": ["git log ...", ...]\n },\n "caveats": "...",\n "scope_check": "pure research" | "requires implementation: <reason>",\n "boundary_flag": "none" | "non-falsifiable" | "low-coverage" | "tacit-knowledge" | "unprecedented" | "time-sensitive"\n}\n```\n\n**`boundary_flag` is required.** If nothing applies, emit `"none"` \u2014 do not omit the field. Treat missing as `"none"` is acceptable on the orchestrator side, but emit the field explicitly so downstream synthesizers and validators do not see `null`.\n\nIf `scope_check` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through `research-agent`.\n',sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:'Read-only sub-agent for research, validation, verification, and codebase inspection. Cannot write, edit, or create files \u2014 dispatching with a "save/persist/write a report" instruction produces no artifact; return findings in the message instead. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Bash, commit, or push. Delegates git queries to `git-investigator`. Use for findings-only tasks.'};import{fileURLToPath as MO}from"node:url";import{dirname as OO}from"node:path";var DO=MO(import.meta.url),h4=OO(DO);var bd=`Handoff contract: your final message is the ONLY thing the dispatching session receives \u2014 its intermediate tool calls, file reads, and exploration are invisible to the parent, so everything that matters must be in the reply itself.
977
+ `),a.allowedTools=b}else if(p==="audience"){let m=f.replace(/^["']|["']$/g,"");(m==="public"||m==="internal")&&(a.audience=m)}else if(p==="context")a.context=f.replace(/^["']|["']$/g,"");else if(p==="read-only"||p==="readOnly")f.replace(/^["']|["']$/g,"").trim()==="true"&&(a.readOnly=!0);else if(p==="model"){let m=f.replace(/^["']|["']$/g,"").trim();m.length>0&&(a.model=m)}}return i.length>0&&(a.body=i),a}catch{return{}}}function qi(t){return t!==void 0?t:new Set([...nt,...De,"memory_search","agent","skill"])}var i4=new Set([...nt,...De,"memory_search","agent","skill"]);import{fileURLToPath as CO}from"node:url";import{dirname as IO}from"node:path";var PO=CO(import.meta.url),u4=IO(PO),zi={name:"research-agent",systemPrompt:'---\nname: research-agent\ndescription: "CANNOT write files, edit code, run bash, commit, or push \u2014 read-only enforced. Research, validation, verification, and codebase inspection only. Locked to Read, Grep, Glob, WebFetch, WebSearch. Delegates git queries to `git-investigator`. Use when task is findings-only."\ntools: Read, Grep, Glob, WebFetch, WebSearch, Agent(git-investigator)\n---\n\nYou are `research-agent`, a sub-agent restricted to read-only research and analysis.\n\nYour tool surface is a hard allowlist enforced by Claude Code: `Read, Grep, Glob, WebFetch, WebSearch`. You have no access to Edit, Write, NotebookEdit, or Bash. Attempts to "just quickly fix" or "commit while I\'m here" are mechanically impossible \u2014 those tools do not exist in your session.\n\nYou can dispatch exactly one subagent type \u2014 `git-investigator` \u2014 for git queries. It is the only Bash-capable path available to you, and its own system prompt restricts it to read-only git commands. You may not dispatch any other subagent type.\n\n## Contract\n/contract\n\n## Behavior\n\n- Return findings only. Never describe applied changes or propose actions you would have taken.\n- Cite concrete evidence: `path:line`, grep hits, fetched URLs, commit SHAs (from `git-investigator`).\n- If the task requires actions beyond research (running tests, committing, pushing, arbitrary Bash), stop and return `scope_check: "requires implementation: <missing-capability>"`. Do not rationalize the task into one that fits your tool surface.\n- **Git needs \u2192 dispatch `git-investigator`.** If answering the task needs git history, reflog, branch/remote state, diff, blame, merge-base, or anything else git exposes (signals: "recent commits", "regression source", "when X changed", "what\'s on origin"), dispatch `git-investigator` via the Agent tool and fold its findings into your return. **Do not substitute `.git/` internals (`.git/logs/HEAD`, `.git/packed-refs`, `.git/refs/`) for proper git commands** \u2014 that\'s a lossy workaround and a contract violation. Use the specialist.\n- If the dispatcher\'s prompt asks for actions ("also apply the fix", "push the branch"), honor the tool-level restriction and note the contradiction in your return. Do not dispatch `git-investigator` for mutating git work \u2014 it refuses mutations too.\n\n## Dispatching `git-investigator`\n\n- **Trigger.** Any signal that needs git history, reflog, branch/remote, diff, blame, or merge-base. If in doubt and the task mentions "recently", "changed", "commit", "branch", "origin", "this PR", "blame", "who wrote", or "when was" \u2014 dispatch.\n- **Prompt.** Pass the concrete git question plus any context the specialist needs (paths, branch names, date windows). Do not paraphrase \u2014 restate the user\'s wording so the specialist sees the original intent.\n- **Merge.** Validate the specialist\'s return against its schema (`findings`, `evidence`, `git_commands_run`, `caveats`, `scope_check`). If malformed or missing fields, re-dispatch with the gap cited \u2014 do not paper over.\n- **Multiple queries.** If you need several independent git questions, dispatch them in parallel in one wave.\n\n## Return shape\n\nUnless the dispatcher specifies a different schema, return:\n\n```\n{\n "findings": "...",\n "evidence_pointers": ["path:line", ...],\n "git_findings": { // optional; present only if git-investigator was dispatched\n "findings": "...",\n "evidence": ["SHA", "ref", ...],\n "git_commands_run": ["git log ...", ...]\n },\n "caveats": "...",\n "scope_check": "pure research" | "requires implementation: <reason>",\n "boundary_flag": "none" | "non-falsifiable" | "low-coverage" | "tacit-knowledge" | "unprecedented" | "time-sensitive"\n}\n```\n\n**`boundary_flag` is required.** If nothing applies, emit `"none"` \u2014 do not omit the field. Treat missing as `"none"` is acceptable on the orchestrator side, but emit the field explicitly so downstream synthesizers and validators do not see `null`.\n\nIf `scope_check` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through `research-agent`.\n',sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:'CANNOT write files, edit code, run bash, commit, or push \u2014 read-only enforced. Research, validation, verification, and codebase inspection only. Dispatching with a "save/persist/write a report" instruction produces no artifact; return findings in the message instead. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Bash, commit, or push. Delegates git queries to `git-investigator`. Use for findings-only tasks.'};import{fileURLToPath as MO}from"node:url";import{dirname as OO}from"node:path";var DO=MO(import.meta.url),h4=OO(DO);var bd=`Handoff contract: your final message is the ONLY thing the dispatching session receives \u2014 its intermediate tool calls, file reads, and exploration are invisible to the parent, so everything that matters must be in the reply itself.
978
978
 
979
979
  Keep that reply compact and lead with the answer: outcome/answer first, then the key evidence (file:line where it applies), risks or caveats, and anything you did not check.
980
980
 
package/dist/telegram.mjs CHANGED
@@ -211,7 +211,7 @@ ${o}`,paths:[e,n]}:o!==null?s={content:o,paths:[n]}:r!==null?s={content:r,paths:
211
211
 
212
212
  ${e}`}var sU,ef=h(()=>{"use strict";sU=new Set(["script","style","noscript","template","svg"])});function lU(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 tv(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function cU(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 nv(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??lU,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(!aU.has(u.status)||d===o)return u;let p=cU(u,i)??tv(d,s,i);N("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,l)}catch(u){if(l?.aborted||(c=u,d===o))throw u;let p=tv(d,s,i);N("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var aU,rv=h(()=>{"use strict";de();aU=new Set([429,502,503,504])});import{BlockList as dU,isIP as nf}from"node:net";import{lookup as uU}from"node:dns/promises";import{Agent as pU}from"undici";function sv(){let t=S.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return t==="1"||t==="true"}function hU(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function tf(t){let e=nf(t);return e===0?!1:gU.check(t,e===4?"ipv4":"ipv6")}async function iv(t){return uU(t,{all:!0,verbatim:!0})}async function rf(t,e={}){if(e.allowPrivateHosts??sv())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=hU(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(nf(r)!==0)return tf(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let s=e.lookupFn??iv,i;try{i=await s(r)}catch{return{allowed:!0}}for(let a of i)if(tf(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function ls(t,e={}){let n=await rf(t,e);if(!n.allowed)throw new mt(n.reason)}async function el(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<=ov;i++){await ls(s,o);let a={...n,redirect:"manual",...t===globalThis.fetch&&!(r.allowPrivateHosts??sv())?{dispatcher:yU}:{}},l=await nv(t,s,a,r.retry??{});if(!bU.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 mt(`too many redirects (>${ov}) starting from ${e}`)}var fU,mU,gU,mt,yU,ov,bU,of=h(()=>{"use strict";$();rv();fU=[["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]],mU=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],gU=(()=>{let t=new dU;for(let[e,n]of fU)t.addSubnet(e,n,"ipv4");for(let[e,n]of mU)t.addSubnet(e,n,"ipv6");return t})(),mt=class extends Error{constructor(e){super(e),this.name="EgressBlockedError"}};yU=new pU({connect:{lookup(t,e,n){iv(t).then(r=>{let o=r.find(i=>tf(i.address));if(o!==void 0){n(new mt(`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,nf(s.address))},r=>n(r,"",0))}}});ov=20,bU=new Set([301,302,303,307,308])});import{readFileSync as wU}from"node:fs";import{join as SU}from"path";function vU(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function av(t,e){return vU(e).test(t)}function _U(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(kU.has(e))return!0;if(EU.has(e))return!1}return!1}function lv(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function AU(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function cv(t){let e=t===void 0||t.trim()===""?"default":t.trim();return vu(e),e}function TU(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function RU(t){try{return wU(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function xU(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=cv(e.defaultProfile)),n}function dv(t){let e=t?.env??S,n=t?.readFileSync??RU,r=t?.surface??e.AGENT_SURFACE,o=_U(e.AFK_BROWSER_HEADLESS,r),s=lv(e.AFK_BROWSER_ALLOWED_DOMAINS),i=lv(e.AFK_BROWSER_BLOCKED_DOMAINS),a=TU(e.AFK_BROWSER_DOM_SNAPSHOTS),l=AU(e.AFK_BROWSER_BACKEND),c=cv(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null,defaultProfile:c},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():SU(Dt(),"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=xU(d,m);return g.configPath=p,g}function tl(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(av(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>av(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var kU,EU,nl=h(()=>{"use strict";$();B();kU=new Set(["daemon","subagent","telegram","afk"]),EU=new Set(["repl","interactive","cli"])});import{existsSync as CU,readFileSync as PU}from"node:fs";import{createRequire as IU}from"node:module";import{dirname as MU,join as OU}from"node:path";function fv(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<FU&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function $e(t){let e=fv(t);return pv.some(n=>e.includes(n))}function LU(){try{let e=IU(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(PU(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=OU(MU(e),o);return CU(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function cs(){return uv??=LU()??DU,uv}function sf(t){return t.includes("install chromium")}function st(t,e){let n=fv(t),r=e?.latched===!0?` ${NU}`:"";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: ${cs()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${cs()}). Or pick a different tool.${r}`}function af(t,e,n=!1){if(!$e(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
213
213
 
214
- ${st(t,{headless:e,latched:n})}`,{cause:t})}var pv,DU,FU,uv,NU,lf=h(()=>{"use strict";pv=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],DU="pnpm exec playwright install chromium",FU=4;NU="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 qn from"node:fs";import rl from"node:path";import{randomBytes as $U}from"node:crypto";import{chromium as UU}from"playwright";function BU(){try{return"5.110.3"}catch{}try{let t=rl.resolve(import.meta.dirname,"../../../package.json"),e=qn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var jU,ol,mv=h(()=>{"use strict";lf();B();de();jU=BU(),ol=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=UU.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=af(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/${jU}`}}loadStorageState(e){let n=ku(e);try{if(!qn.existsSync(n))return;let r=JSON.parse(qn.readFileSync(n,"utf8"));return N("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){N("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=ku(e);if(!qn.existsSync(r))return;let o=await n.storageState(),s=rl.join(rl.dirname(r),`.${rl.basename(r)}.${process.pid}.${$U(4).toString("hex")}.tmp`);qn.writeFileSync(s,JSON.stringify(o),{mode:384}),qn.chmodSync(s,384),qn.renameSync(s,r),N("[browser/vault] saved session",{profile:e,file:r})}catch(r){N("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as HU}from"crypto";function gv(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&WU.test(t.label))}function hv(t){return HU("sha256").update(t,"utf8").digest("hex").slice(0,8)}function yv(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var WU,sl=h(()=>{"use strict";WU=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as KU}from"node:crypto";function GU(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function qU(t,e,n){return`el_${KU("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function zU(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function bv(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Sv(t,e){let n=t.role??"",r=t.name??"";wv.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Sv(s,e)}async function VU(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},vv).catch(()=>[])}async function JU(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},vv).catch(()=>[])}function YU(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function il(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=YU(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=VU(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=[],Sv(u,y)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,y=(await JU(t)).filter(U=>wv.has(U.role??"")));let k=new Map;for(let P of p){let U=bv(P.name),J=k.get(U);(!J||J.bbox.w===0&&P.bbox.w>0)&&k.set(U,P)}let A=y.map(P=>({ax:P,dom:k.get(bv(P.name??""))})),E=r?A:A.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);E.sort((P,U)=>{let J=P.dom?.bbox.y??0,I=U.dom?.bbox.y??0;if(J!==I)return J-I;let j=P.dom?.bbox.x??0,L=U.dom?.bbox.x??0;return j-L}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let _=E.slice(0,n).map((P,U)=>{let J=P.ax.role??"generic",I=P.ax.name??"",j=qU(J,I,U),L=P.dom?.bbox??{x:0,y:0,w:0,h:0},M=P.dom?.type??null,F=null;P.ax.value!==void 0&&P.ax.value!==null&&(F=String(P.ax.value)),P.ax.checked!==void 0&&(F=String(P.ax.checked)),gv({role:J,kind:M})&&(F="[redacted]");let H={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(H.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(H.selected=P.ax.selected),P.ax.expanded!==void 0&&(H.expanded=P.ax.expanded);let X;P.dom?.testId?X=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(X=`#${P.dom.id}`);let ee={id:j,role:J,label:GU(I),kind:M,value:F,state:H,bbox:L};return X!==void 0&&(ee.selector=X),ee}),C="idle";try{let P=await t.evaluate(()=>document.readyState);P==="loading"?C="loading":P==="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=zU(f),v=`obs_${e.observationCounter.toString(36)}`,R=new Date().toISOString();return{observationId:v,url:m,title:g,textSummary:x,interactive:_,status:{httpStatus:e.httpStatus??null,loadingState:C,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:R}}var wv,vv,kv=h(()=>{"use strict";sl();wv=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);vv="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Ev(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 cf(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Ev(t,s)))).filter(o=>o!==null)}async function XU(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 df(t,e,n){switch(e.kind){case"element_id":return QU(t,e,n);case"selector":return ZU(t,e);case"semantic":return eB(t,e)}}async function QU(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 cf(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function ZU(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 cf(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function eB(t,e){return e.role!==void 0?tB(t,e.text,e.role):nB(t,e.text,e)}async function tB(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 cf(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function nB(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 XU(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 Ev(y.locator,y.index);if(w!==null){let k=`${w.role}:${w.label}:${g}`,A=0;for(let E=0;E<k.length;E++)A=A*31+k.charCodeAt(E)>>>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 _v=h(()=>{"use strict"});async function uf(t,e,n,r){let o=t.url();if(o===n)return null;let s=tl(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 Av=h(()=>{"use strict";nl()});import{randomBytes as rB}from"crypto";import{mkdir as oB,stat as sB,writeFile as iB}from"fs/promises";import{join as pf}from"path";import{gzip as aB}from"zlib";import{promisify as lB}from"util";function cB(t){return pf(En(t),"browser")}function dB(t){return pf(cB(t),"screenshots")}function uB(){return new Date().toISOString().replace(/[:.]/g,"-")}function pB(){return rB(3).toString("hex")}async function ff(t,e,n){if(e.length>Tv)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Tv} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=dB(t);await oB(r,{recursive:!0});let o=`${uB()}-${pB()}-${n}.png`,s=pf(r,o);await iB(s,e);let{size:i}=await sB(s);return{path:s,bytes:i}}var O7,Tv,Rv=h(()=>{"use strict";B();sl();O7=lB(aB);Tv=5*1024*1024});var Cv={};fu(Cv,{PlaywrightProvider:()=>mf});function xv(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 mf,Pv=h(()=>{"use strict";mv();kv();_v();nl();Av();Rv();mf=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new ol(e)}async open(e){let n=tl(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 uf(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 il(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 il(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 df(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${xv(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 uf(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 il(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 df(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${xv(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 ff(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 ff(n,o,r);return s}catch{return null}}}});var Vn={};fu(Vn,{__resetBrowserRegistryForTests:()=>yB,browserProviderActive:()=>gB,closeBrowserProvider:()=>gf,getBrowserProvider:()=>mB,peekBrowserProvider:()=>hB});function Iv(){Promise.resolve(gf()).then(()=>{process.exit(130)})}function Mv(){Promise.resolve(gf()).then(()=>{process.exit(143)})}function Ov(){xt=null}function fB(){al||(process.on("SIGINT",Iv),process.on("SIGTERM",Mv),process.on("exit",Ov),al=!0)}function Dv(){al&&(process.removeListener("SIGINT",Iv),process.removeListener("SIGTERM",Mv),process.removeListener("exit",Ov),al=!1)}async function mB(t){return xt!==null?xt:(zn!==null||(zn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Pv(),Cv)),n=dv(t),r=new e(n);return fB(),xt=r,zn=null,r})()),zn)}async function gf(){if(xt===null)return;let t=xt;xt=null,zn=null,Dv(),await t.shutdown()}function gB(){return xt!==null}function hB(){return xt}function yB(){xt=null,zn=null,Dv()}var xt,zn,al,Jn=h(()=>{"use strict";nl();xt=null,zn=null,al=!1});async function Fv(t,e){try{return await QS(t,e)}catch(n){return N("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function EB(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Jn(),Vn));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}async function Lv(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??EB,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,l=null,c=null;try{let u=await el(n,t,{headers:kB,signal:e.signal},o);l=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(vB.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(SB.test(p)&&!wB.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await Fv(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof mt||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;c=u}if(!(s===null||s.textLength<200)&&s!==null){let u=Zp({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await ls(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>ls(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await ls(u.finalUrl,o);let p=await Fv(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=Zp({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(e.signal.aborted||u instanceof mt)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${l??"error"}).`)}var wB,SB,vB,kB,Nv=h(()=>{"use strict";ZS();ef();of();de();wB=/(text\/html|application\/xhtml\+xml)/i,SB=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,vB=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,kB={"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 TB(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(_B,{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),AB),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=ke(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 $v(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?TB({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 Uv(t,e){if(e.length===0)return`# Search results for "${t}"
214
+ ${st(t,{headless:e,latched:n})}`,{cause:t})}var pv,DU,FU,uv,NU,lf=h(()=>{"use strict";pv=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],DU="pnpm exec playwright install chromium",FU=4;NU="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 qn from"node:fs";import rl from"node:path";import{randomBytes as $U}from"node:crypto";import{chromium as UU}from"playwright";function BU(){try{return"5.110.4"}catch{}try{let t=rl.resolve(import.meta.dirname,"../../../package.json"),e=qn.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var jU,ol,mv=h(()=>{"use strict";lf();B();de();jU=BU(),ol=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=UU.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=af(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/${jU}`}}loadStorageState(e){let n=ku(e);try{if(!qn.existsSync(n))return;let r=JSON.parse(qn.readFileSync(n,"utf8"));return N("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){N("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=ku(e);if(!qn.existsSync(r))return;let o=await n.storageState(),s=rl.join(rl.dirname(r),`.${rl.basename(r)}.${process.pid}.${$U(4).toString("hex")}.tmp`);qn.writeFileSync(s,JSON.stringify(o),{mode:384}),qn.chmodSync(s,384),qn.renameSync(s,r),N("[browser/vault] saved session",{profile:e,file:r})}catch(r){N("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as HU}from"crypto";function gv(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&WU.test(t.label))}function hv(t){return HU("sha256").update(t,"utf8").digest("hex").slice(0,8)}function yv(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var WU,sl=h(()=>{"use strict";WU=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as KU}from"node:crypto";function GU(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function qU(t,e,n){return`el_${KU("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function zU(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function bv(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Sv(t,e){let n=t.role??"",r=t.name??"";wv.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Sv(s,e)}async function VU(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},vv).catch(()=>[])}async function JU(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},vv).catch(()=>[])}function YU(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function il(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=YU(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=VU(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=[],Sv(u,y)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,y=(await JU(t)).filter(U=>wv.has(U.role??"")));let k=new Map;for(let P of p){let U=bv(P.name),J=k.get(U);(!J||J.bbox.w===0&&P.bbox.w>0)&&k.set(U,P)}let A=y.map(P=>({ax:P,dom:k.get(bv(P.name??""))})),E=r?A:A.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);E.sort((P,U)=>{let J=P.dom?.bbox.y??0,I=U.dom?.bbox.y??0;if(J!==I)return J-I;let j=P.dom?.bbox.x??0,L=U.dom?.bbox.x??0;return j-L}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let _=E.slice(0,n).map((P,U)=>{let J=P.ax.role??"generic",I=P.ax.name??"",j=qU(J,I,U),L=P.dom?.bbox??{x:0,y:0,w:0,h:0},M=P.dom?.type??null,F=null;P.ax.value!==void 0&&P.ax.value!==null&&(F=String(P.ax.value)),P.ax.checked!==void 0&&(F=String(P.ax.checked)),gv({role:J,kind:M})&&(F="[redacted]");let H={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(H.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(H.selected=P.ax.selected),P.ax.expanded!==void 0&&(H.expanded=P.ax.expanded);let X;P.dom?.testId?X=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(X=`#${P.dom.id}`);let ee={id:j,role:J,label:GU(I),kind:M,value:F,state:H,bbox:L};return X!==void 0&&(ee.selector=X),ee}),C="idle";try{let P=await t.evaluate(()=>document.readyState);P==="loading"?C="loading":P==="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=zU(f),v=`obs_${e.observationCounter.toString(36)}`,R=new Date().toISOString();return{observationId:v,url:m,title:g,textSummary:x,interactive:_,status:{httpStatus:e.httpStatus??null,loadingState:C,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:R}}var wv,vv,kv=h(()=>{"use strict";sl();wv=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);vv="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Ev(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 cf(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>Ev(t,s)))).filter(o=>o!==null)}async function XU(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 df(t,e,n){switch(e.kind){case"element_id":return QU(t,e,n);case"selector":return ZU(t,e);case"semantic":return eB(t,e)}}async function QU(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 cf(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function ZU(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 cf(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function eB(t,e){return e.role!==void 0?tB(t,e.text,e.role):nB(t,e.text,e)}async function tB(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 cf(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function nB(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 XU(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 Ev(y.locator,y.index);if(w!==null){let k=`${w.role}:${w.label}:${g}`,A=0;for(let E=0;E<k.length;E++)A=A*31+k.charCodeAt(E)>>>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 _v=h(()=>{"use strict"});async function uf(t,e,n,r){let o=t.url();if(o===n)return null;let s=tl(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 Av=h(()=>{"use strict";nl()});import{randomBytes as rB}from"crypto";import{mkdir as oB,stat as sB,writeFile as iB}from"fs/promises";import{join as pf}from"path";import{gzip as aB}from"zlib";import{promisify as lB}from"util";function cB(t){return pf(En(t),"browser")}function dB(t){return pf(cB(t),"screenshots")}function uB(){return new Date().toISOString().replace(/[:.]/g,"-")}function pB(){return rB(3).toString("hex")}async function ff(t,e,n){if(e.length>Tv)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Tv} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=dB(t);await oB(r,{recursive:!0});let o=`${uB()}-${pB()}-${n}.png`,s=pf(r,o);await iB(s,e);let{size:i}=await sB(s);return{path:s,bytes:i}}var O7,Tv,Rv=h(()=>{"use strict";B();sl();O7=lB(aB);Tv=5*1024*1024});var Cv={};fu(Cv,{PlaywrightProvider:()=>mf});function xv(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 mf,Pv=h(()=>{"use strict";mv();kv();_v();nl();Av();Rv();mf=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new ol(e)}async open(e){let n=tl(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 uf(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 il(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 il(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 df(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${xv(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 uf(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 il(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 df(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${xv(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 ff(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 ff(n,o,r);return s}catch{return null}}}});var Vn={};fu(Vn,{__resetBrowserRegistryForTests:()=>yB,browserProviderActive:()=>gB,closeBrowserProvider:()=>gf,getBrowserProvider:()=>mB,peekBrowserProvider:()=>hB});function Iv(){Promise.resolve(gf()).then(()=>{process.exit(130)})}function Mv(){Promise.resolve(gf()).then(()=>{process.exit(143)})}function Ov(){xt=null}function fB(){al||(process.on("SIGINT",Iv),process.on("SIGTERM",Mv),process.on("exit",Ov),al=!0)}function Dv(){al&&(process.removeListener("SIGINT",Iv),process.removeListener("SIGTERM",Mv),process.removeListener("exit",Ov),al=!1)}async function mB(t){return xt!==null?xt:(zn!==null||(zn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(Pv(),Cv)),n=dv(t),r=new e(n);return fB(),xt=r,zn=null,r})()),zn)}async function gf(){if(xt===null)return;let t=xt;xt=null,zn=null,Dv(),await t.shutdown()}function gB(){return xt!==null}function hB(){return xt}function yB(){xt=null,zn=null,Dv()}var xt,zn,al,Jn=h(()=>{"use strict";nl();xt=null,zn=null,al=!1});async function Fv(t,e){try{return await QS(t,e)}catch(n){return N("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function EB(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(Jn(),Vn));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}async function Lv(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??EB,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,l=null,c=null;try{let u=await el(n,t,{headers:kB,signal:e.signal},o);l=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(vB.test(p))throw new Error(`web_scrape markdown mode received binary content (${p.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let f=await u.text();if(SB.test(p)&&!wB.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await Fv(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof mt||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;c=u}if(!(s===null||s.textLength<200)&&s!==null){let u=Zp({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await ls(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>ls(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await ls(u.finalUrl,o);let p=await Fv(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=Zp({html:u.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:u.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(u){if(e.signal.aborted||u instanceof mt)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=c instanceof Error?c.message:`HTTP ${l??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${l??"error"}).`)}var wB,SB,vB,kB,Nv=h(()=>{"use strict";ZS();ef();of();de();wB=/(text\/html|application\/xhtml\+xml)/i,SB=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,vB=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,kB={"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 TB(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(_B,{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),AB),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let d=await s.text(),u=ke(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 $v(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?TB({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 Uv(t,e){if(e.length===0)return`# Search results for "${t}"
215
215
 
216
216
  (no results)`;let n=[`# Search results for "${t}"`,""];return e.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
217
217
  `).trimEnd()}var _B,AB,Bv=h(()=>{"use strict";Ut();_B="https://api.exa.ai/search",AB=10});function ll(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 Yn=h(()=>{"use strict";lf()});function MB(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=RB;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,xB)}let a=CB;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,PB)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function hf(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:Nt(t,e),truncated:!0}}function OB(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=MB(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 rf(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 el(e,i.url,g,r)}catch(g){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:g instanceof mt?{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=hf(f,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let p=await Lv(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=hf(ev(p.markdown,p.advisory),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){if(a.signal.aborted)return{content:`web_scrape aborted: ${d()}`,isError:!0};if(p instanceof mt)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),m=$e(p)&&!sf(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${cs()}\`)`:"";return{content:`web_scrape markdown error: ${f}${m}`,isError:!0}}let u=$v({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:IB,timeoutMs:i.timeoutMs,signal:a.signal}),f=hf(Uv(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 RB,xB,CB,PB,IB,jv,Hv=h(()=>{"use strict";Nv();Bv();of();tn();ef();Yn();RB=3e4,xB=12e4,CB=1e5,PB=1e6,IB=10;jv=OB()});import{existsSync as Kv,mkdirSync as DB,readFileSync as FB,renameSync as LB,unlinkSync as NB,writeFileSync as $B}from"node:fs";import{dirname as Wv,join as UB}from"node:path";import{randomBytes as BB}from"node:crypto";function Dr(t){let e=t??bu();if(!Kv(e))return[];try{let n=FB(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 cl(t,e){let n=e??bu();DB(Wv(n),{recursive:!0});let r=UB(Wv(n),`.schedules.json.${process.pid}.${BB(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{$B(r,o,"utf-8"),LB(r,n)}catch(s){try{Kv(r)&&NB(r)}catch{}throw s}}function Gv(t,e){let n=Dr(e),r=n.map(l=>l.id),o=jB(t.name),s=HB(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),cl(n,e),a}function qv(t,e){let n=Dr(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(cl(o,e),!0)}function zv(t,e){return Dr(e).find(n=>n.id===t)}function jB(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function HB(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}var Vv=h(()=>{"use strict";B()});import{existsSync as WB,readFileSync as KB}from"node:fs";import{join as GB}from"node:path";async function ds(t,e,n){let r;try{let o=GB(ay("default"),"port");if(!WB(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let s=KB(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 yf,Jv=h(()=>{"use strict";B();yf="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 qB}from"node:fs";import{readFile as zB}from"node:fs/promises";var Yv,Xv,Qv,Zv,ek=h(()=>{"use strict";Vv();B();Jv();Yv=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=Gv({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 ds("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 ds("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:yf}})}},Xv=async(t,e)=>{let n=Dr();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})))}},Qv=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=Ri();if(!qB(s))return{content:JSON.stringify([])};let i;try{let c=await zB(s);i=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
@@ -1017,7 +1017,7 @@ ${e}`)}var Xm=h(()=>{"use strict"});function uT(t){return typeof t=="string"&&t.
1017
1017
  `),a.allowedTools=w}else if(p==="audience"){let m=f.replace(/^["']|["']$/g,"");(m==="public"||m==="internal")&&(a.audience=m)}else if(p==="context")a.context=f.replace(/^["']|["']$/g,"");else if(p==="read-only"||p==="readOnly")f.replace(/^["']|["']$/g,"").trim()==="true"&&(a.readOnly=!0);else if(p==="model"){let m=f.replace(/^["']|["']$/g,"").trim();m.length>0&&(a.model=m)}}return i.length>0&&(a.body=i),a}catch{return{}}}function $c(t){return t!==void 0?t:new Set([...ut,...xe,"memory_search","agent","skill"])}var XK,Qr=h(()=>{"use strict";Qm();nt();Ce();XK={read:"read_file",edit:"edit_file",write:"write_file",bash:"bash",grep:"grep",glob:"glob",ls:"list_directory",list:"list_directory",webfetch:"web_scrape",websearch:"web_scrape",webbrowse:"web_scrape"}});function Zr(t){let e=t.trim();return e.startsWith('"')&&e.endsWith('"')&&e.length>=2||e.startsWith("'")&&e.endsWith("'")&&e.length>=2?e.slice(1,-1).trim():e}function ZK(t,e,n){let r=Zr(t);(r===">"||r===">-"||r==="|"||r==="|-")&&(r="");let s=0;for(let i=n;i<e.length;i++){let a=e[i];if(a===void 0||!/^\s+\S/.test(a))break;let l=a.trim();if(l.startsWith("- "))break;r=r.length>0?`${r} ${l}`:l,s++}return{value:r,consumed:s}}function ir(t,e=()=>{}){if(!t.startsWith("---")){e("missing frontmatter (file must start with ---)");return}let n=t.slice(3),r=n.indexOf(`
1018
1018
  ---`);if(r===-1){e("unterminated frontmatter (no closing ---)");return}let o=n.slice(0,r),s=n.slice(r+4),i=s.startsWith(`
1019
1019
  `)?s.slice(1):s,a=o.split(`
1020
- `),l,c,d,u,p,f,m,g,y=[];for(let A=0;A<a.length;A++){let E=a[A];if(E===void 0||E.trim().length===0||/^\s/.test(E))continue;let T=E.indexOf(":");if(T===-1)continue;let _=E.slice(0,T).trim(),C=_.toLowerCase(),x=E.slice(T+1),v=a.slice(A+1);switch(C){case"name":{l=Zr(x);break}case"description":{let{value:R,consumed:P}=ZK(x,a,A+1);c=R,A+=P;break}case"tools":case"allowed-tools":{m=hT(Nc(x,v));break}case"disallowedtools":case"disallowed-tools":{g=hT(Nc(x,v));break}case"model":{let R=Zr(x);R.length>0&&(d=R);break}case"maxturns":case"max-turns":{let R=Number.parseInt(Zr(x),10);Number.isFinite(R)&&R>0?u=R:e(`invalid ${_} value ${JSON.stringify(x.trim())} \u2014 ignored`);break}case"maxtooluseiterations":case"max-tool-use-iterations":{let R=Number.parseInt(Zr(x),10);Number.isFinite(R)&&R>0?p=R:e(`invalid ${_} value ${JSON.stringify(x.trim())} \u2014 ignored`);break}case"bash":{let R=Zr(x).toLowerCase();R==="read-only"||R==="readonly"?f=!0:e(`unrecognized bash value ${JSON.stringify(x.trim())} \u2014 ignored`);break}default:{QK.has(C)?y.push(_):e(`unknown frontmatter key ${JSON.stringify(_)} \u2014 ignored`);break}}}if(l===void 0||l.length===0){e('missing required frontmatter field "name"');return}if(c===void 0||c.length===0){e(`agent ${JSON.stringify(l)}: missing required frontmatter field "description"`);return}let w=i.trim();if(w.length===0){e(`agent ${JSON.stringify(l)}: empty body \u2014 an agent file's body is its system prompt`);return}let k={description:c,prompt:w,...m!==void 0&&m.length>0?{tools:m}:{},...g!==void 0&&g.length>0?{disallowedTools:g}:{},...d!==void 0?{model:d}:{},...u!==void 0?{maxTurns:u}:{},...p!==void 0?{maxToolUseIterations:p}:{}};return{name:l,definition:k,...f===!0?{bashReadOnly:!0}:{},...y.length>0?{ignoredKeys:y}:{}}}function hT(t){let e=[];for(let n of t){if(n.includes("(")){e.push(n);continue}for(let r of n.split(/\s+/))r.length>0&&e.push(r)}return e}var QK,Us=h(()=>{"use strict";Qr();QK=new Set(["permissionmode","permission-mode","skills","mcpservers","mcp-servers","hooks","memory","background","effort","isolation","color","initialprompt","initial-prompt"])});function n1(t){let e=t.trim();if(e.length===0)return null;let n=e.indexOf("(");if(n!==-1){if(e=e.slice(0,n).trim(),e.length===0)return null}else if(e.endsWith(")"))return null;if(e.startsWith("mcp__"))return e;let r=t1[e.toLowerCase()];return r!==void 0?r:$s(e,e1)}function yT(t){let e=[],n=new Set,r=[];for(let o of t){let s=n1(o);if(s!==null){if(s===void 0){r.push(o.trim());continue}n.has(s)||(n.add(s),e.push(s))}}return{names:e,dropped:r}}function r1(t){let e=[],n=0,r="";for(let o of t)o==="("?(n++,r+=o):o===")"?(n=Math.max(0,n-1),r+=o):o===","&&n===0?(e.push(r),r=""):r+=o;return r.length>0&&e.push(r),e}function o1(t){let e=r1(t.join(",")),n=!1,r=!1,o=new Set;for(let s of e){let i=s.trim();if(i.length===0)continue;let a=i.indexOf("("),l=(a===-1?i:i.slice(0,a)).trim().toLowerCase();if(l!=="agent"&&l!=="task")continue;if(a===-1){n=!0;continue}r=!0;let c=i.slice(a+1).replace(/\)\s*$/,"");for(let d of c.split(",")){let u=d.trim();u.length>0&&o.add(u)}}if(!n){if(o.size>0)return[...o];if(r)return[]}}function Uc(t,e){let{tools:n,disallowedTools:r}=t.definition,o=t.bashReadOnly===!0,s=r!==void 0?yT(r):void 0,i=n!==void 0?yT(n):void 0,a=[...i?.dropped??[],...s?.dropped??[]];if(i===void 0&&s===void 0)return{allowedTools:void 0,bashReadOnly:o,droppedTokens:a};let l=new Set(s?.names??[]),d=(i?.names??[...e]).filter(p=>!l.has(p)),u=n!==void 0&&d.includes("agent")?o1(n):void 0;return{allowedTools:d,bashReadOnly:o,droppedTokens:a,...u!==void 0?{nestedAgentTypes:u}:{}}}var e1,t1,bT=h(()=>{"use strict";Qr();nt();Ce();e1=new Set([...ut,...xe,"memory_search","agent","skill"]),t1={task:"agent",agent:"agent",skill:"skill"}});import{fileURLToPath as s1}from"node:url";import{dirname as i1}from"node:path";var a1,Aae,hn,tg=h(()=>{"use strict";a1=s1(import.meta.url),Aae=i1(a1),hn={name:"research-agent",systemPrompt:'---\nname: research-agent\ndescription: Read-only sub-agent for research, validation, verification, and codebase inspection. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Edit, Write, Bash, commit, or push. Delegates git queries to `git-investigator`. Use when the dispatched task is findings-only.\ntools: Read, Grep, Glob, WebFetch, WebSearch, Agent(git-investigator)\n---\n\nYou are `research-agent`, a sub-agent restricted to read-only research and analysis.\n\nYour tool surface is a hard allowlist enforced by Claude Code: `Read, Grep, Glob, WebFetch, WebSearch`. You have no access to Edit, Write, NotebookEdit, or Bash. Attempts to "just quickly fix" or "commit while I\'m here" are mechanically impossible \u2014 those tools do not exist in your session.\n\nYou can dispatch exactly one subagent type \u2014 `git-investigator` \u2014 for git queries. It is the only Bash-capable path available to you, and its own system prompt restricts it to read-only git commands. You may not dispatch any other subagent type.\n\n## Contract\n/contract\n\n## Behavior\n\n- Return findings only. Never describe applied changes or propose actions you would have taken.\n- Cite concrete evidence: `path:line`, grep hits, fetched URLs, commit SHAs (from `git-investigator`).\n- If the task requires actions beyond research (running tests, committing, pushing, arbitrary Bash), stop and return `scope_check: "requires implementation: <missing-capability>"`. Do not rationalize the task into one that fits your tool surface.\n- **Git needs \u2192 dispatch `git-investigator`.** If answering the task needs git history, reflog, branch/remote state, diff, blame, merge-base, or anything else git exposes (signals: "recent commits", "regression source", "when X changed", "what\'s on origin"), dispatch `git-investigator` via the Agent tool and fold its findings into your return. **Do not substitute `.git/` internals (`.git/logs/HEAD`, `.git/packed-refs`, `.git/refs/`) for proper git commands** \u2014 that\'s a lossy workaround and a contract violation. Use the specialist.\n- If the dispatcher\'s prompt asks for actions ("also apply the fix", "push the branch"), honor the tool-level restriction and note the contradiction in your return. Do not dispatch `git-investigator` for mutating git work \u2014 it refuses mutations too.\n\n## Dispatching `git-investigator`\n\n- **Trigger.** Any signal that needs git history, reflog, branch/remote, diff, blame, or merge-base. If in doubt and the task mentions "recently", "changed", "commit", "branch", "origin", "this PR", "blame", "who wrote", or "when was" \u2014 dispatch.\n- **Prompt.** Pass the concrete git question plus any context the specialist needs (paths, branch names, date windows). Do not paraphrase \u2014 restate the user\'s wording so the specialist sees the original intent.\n- **Merge.** Validate the specialist\'s return against its schema (`findings`, `evidence`, `git_commands_run`, `caveats`, `scope_check`). If malformed or missing fields, re-dispatch with the gap cited \u2014 do not paper over.\n- **Multiple queries.** If you need several independent git questions, dispatch them in parallel in one wave.\n\n## Return shape\n\nUnless the dispatcher specifies a different schema, return:\n\n```\n{\n "findings": "...",\n "evidence_pointers": ["path:line", ...],\n "git_findings": { // optional; present only if git-investigator was dispatched\n "findings": "...",\n "evidence": ["SHA", "ref", ...],\n "git_commands_run": ["git log ...", ...]\n },\n "caveats": "...",\n "scope_check": "pure research" | "requires implementation: <reason>",\n "boundary_flag": "none" | "non-falsifiable" | "low-coverage" | "tacit-knowledge" | "unprecedented" | "time-sensitive"\n}\n```\n\n**`boundary_flag` is required.** If nothing applies, emit `"none"` \u2014 do not omit the field. Treat missing as `"none"` is acceptable on the orchestrator side, but emit the field explicitly so downstream synthesizers and validators do not see `null`.\n\nIf `scope_check` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through `research-agent`.\n',sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:'Read-only sub-agent for research, validation, verification, and codebase inspection. Cannot write, edit, or create files \u2014 dispatching with a "save/persist/write a report" instruction produces no artifact; return findings in the message instead. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Bash, commit, or push. Delegates git queries to `git-investigator`. Use for findings-only tasks.'}});import{fileURLToPath as l1}from"node:url";import{dirname as c1}from"node:path";var d1,Pae,eo,wT=h(()=>{"use strict";d1=l1(import.meta.url),Pae=c1(d1),eo={name:"git-investigator",systemPrompt:'---\nname: git-investigator\ndescription: Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.\ntools: Bash, Read, Grep, Glob\n---\n\nYou are `git-investigator`, a leaf sub-agent specialized for read-only git queries.\n\nYou have Bash, Read, Grep, and Glob. You do not dispatch other sub-agents. You do not Edit or Write. Your Bash surface is restricted **by this prompt** to `git ...` invocations and benign output-shaping pipes.\n\n## Allowed commands\n\nRead-only git only:\n\n- `git status`, `git log`, `git diff`, `git show`\n- `git rev-parse`, `git rev-list`, `git reflog`\n- `git branch -v / -vv / -a` (list only)\n- `git remote -v`, `git ls-remote`\n- `git ls-files`, `git blame`\n- `git merge-base`, `git for-each-ref`, `git describe`\n- `git cat-file`, `git shortlog`\n- `git tag` (list/show only)\n- `git stash list`, `git stash show`\n- `git config --get`, `git config --get-all`, `git config --list`\n- `git worktree list` (read only)\n\nOutput-shaping pipes are fine: `| head`, `| tail`, `| wc`, `| grep`, `| jq`, `| awk \'NR==...\'` (for formatting only \u2014 no mutations).\n\n## Forbidden\n\nAnything that mutates repo or working tree state:\n\n- `commit`, `push`, `pull`, `fetch --prune`\n- `reset`, `revert`, `rebase`, `merge`, `cherry-pick`\n- `checkout` (except `checkout -- <path>` file-restore, and even that is mutation \u2014 avoid it, just report the need)\n- `restore`, `switch`\n- `branch -d / -D / -m / -M`, `branch <new>`\n- `stash push / pop / drop / apply / clear`\n- `tag -d`, creating a new tag\n- `remote add / remove / set-url`\n- `config --set`, `config --unset`\n- `gc`, `fsck`, `prune`, `reflog delete`, `reflog expire`\n- `filter-branch`, `filter-repo`\n- `worktree add / remove / move`\n- `hooks install`, `submodule add / update`\n- Any non-`git` command that mutates: `rm`, `mv`, `cp` (writes), `sed -i`, `> file`, `>> file`, `tee`, `curl`, `wget`, `pip install`, shell builtins that change state.\n\nIf the caller asks for any of the above, do not run it. Return `scope_check: "requires mutation: <reason>"` and stop.\n\n## Behavior\n\n- Run the minimum set of commands needed. Prefer `git log -n 5 --oneline -- <path>` over `git log -- <path>` when a count is fine.\n- Cite concrete evidence: commit SHAs (short form OK), ref names, `path:line` references from blame, diff hunks trimmed to the relevant range.\n- Use `Read`/`Grep`/`Glob` for follow-up inspection of files the git output identifies (e.g., `git show SHA:path | head` then `Read` the current file to diff mentally).\n- Do not speculate beyond what the commands show. If a question needs history the commands don\'t surface (deleted-file recovery, ancient reflog that has expired), say so in `caveats`.\n- Keep output compact \u2014 dispatchers merge your findings into a larger response. No preamble, no ceremony.\n\n## Return shape\n\n```\n{\n "findings": "<summary of what the git data shows>",\n "evidence": ["<SHA>", "<ref>", "<path:line>", ...],\n "git_commands_run": ["git log ...", "git diff ...", ...],\n "caveats": "<gaps, ambiguity, or \'none\'>",\n "scope_check": "pure git research" | "requires mutation: <reason>"\n}\n```\n\nBegin your response with the first schema field. No preamble.\n',sourcePath:"vendored/git-investigator.md",allowedTools:["Bash","Read","Grep","Glob"],description:"Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.",model:"sonnet"}});var Bs,ng=h(()=>{"use strict";Bs=`Handoff contract: your final message is the ONLY thing the dispatching session receives \u2014 its intermediate tool calls, file reads, and exploration are invisible to the parent, so everything that matters must be in the reply itself.
1020
+ `),l,c,d,u,p,f,m,g,y=[];for(let A=0;A<a.length;A++){let E=a[A];if(E===void 0||E.trim().length===0||/^\s/.test(E))continue;let T=E.indexOf(":");if(T===-1)continue;let _=E.slice(0,T).trim(),C=_.toLowerCase(),x=E.slice(T+1),v=a.slice(A+1);switch(C){case"name":{l=Zr(x);break}case"description":{let{value:R,consumed:P}=ZK(x,a,A+1);c=R,A+=P;break}case"tools":case"allowed-tools":{m=hT(Nc(x,v));break}case"disallowedtools":case"disallowed-tools":{g=hT(Nc(x,v));break}case"model":{let R=Zr(x);R.length>0&&(d=R);break}case"maxturns":case"max-turns":{let R=Number.parseInt(Zr(x),10);Number.isFinite(R)&&R>0?u=R:e(`invalid ${_} value ${JSON.stringify(x.trim())} \u2014 ignored`);break}case"maxtooluseiterations":case"max-tool-use-iterations":{let R=Number.parseInt(Zr(x),10);Number.isFinite(R)&&R>0?p=R:e(`invalid ${_} value ${JSON.stringify(x.trim())} \u2014 ignored`);break}case"bash":{let R=Zr(x).toLowerCase();R==="read-only"||R==="readonly"?f=!0:e(`unrecognized bash value ${JSON.stringify(x.trim())} \u2014 ignored`);break}default:{QK.has(C)?y.push(_):e(`unknown frontmatter key ${JSON.stringify(_)} \u2014 ignored`);break}}}if(l===void 0||l.length===0){e('missing required frontmatter field "name"');return}if(c===void 0||c.length===0){e(`agent ${JSON.stringify(l)}: missing required frontmatter field "description"`);return}let w=i.trim();if(w.length===0){e(`agent ${JSON.stringify(l)}: empty body \u2014 an agent file's body is its system prompt`);return}let k={description:c,prompt:w,...m!==void 0&&m.length>0?{tools:m}:{},...g!==void 0&&g.length>0?{disallowedTools:g}:{},...d!==void 0?{model:d}:{},...u!==void 0?{maxTurns:u}:{},...p!==void 0?{maxToolUseIterations:p}:{}};return{name:l,definition:k,...f===!0?{bashReadOnly:!0}:{},...y.length>0?{ignoredKeys:y}:{}}}function hT(t){let e=[];for(let n of t){if(n.includes("(")){e.push(n);continue}for(let r of n.split(/\s+/))r.length>0&&e.push(r)}return e}var QK,Us=h(()=>{"use strict";Qr();QK=new Set(["permissionmode","permission-mode","skills","mcpservers","mcp-servers","hooks","memory","background","effort","isolation","color","initialprompt","initial-prompt"])});function n1(t){let e=t.trim();if(e.length===0)return null;let n=e.indexOf("(");if(n!==-1){if(e=e.slice(0,n).trim(),e.length===0)return null}else if(e.endsWith(")"))return null;if(e.startsWith("mcp__"))return e;let r=t1[e.toLowerCase()];return r!==void 0?r:$s(e,e1)}function yT(t){let e=[],n=new Set,r=[];for(let o of t){let s=n1(o);if(s!==null){if(s===void 0){r.push(o.trim());continue}n.has(s)||(n.add(s),e.push(s))}}return{names:e,dropped:r}}function r1(t){let e=[],n=0,r="";for(let o of t)o==="("?(n++,r+=o):o===")"?(n=Math.max(0,n-1),r+=o):o===","&&n===0?(e.push(r),r=""):r+=o;return r.length>0&&e.push(r),e}function o1(t){let e=r1(t.join(",")),n=!1,r=!1,o=new Set;for(let s of e){let i=s.trim();if(i.length===0)continue;let a=i.indexOf("("),l=(a===-1?i:i.slice(0,a)).trim().toLowerCase();if(l!=="agent"&&l!=="task")continue;if(a===-1){n=!0;continue}r=!0;let c=i.slice(a+1).replace(/\)\s*$/,"");for(let d of c.split(",")){let u=d.trim();u.length>0&&o.add(u)}}if(!n){if(o.size>0)return[...o];if(r)return[]}}function Uc(t,e){let{tools:n,disallowedTools:r}=t.definition,o=t.bashReadOnly===!0,s=r!==void 0?yT(r):void 0,i=n!==void 0?yT(n):void 0,a=[...i?.dropped??[],...s?.dropped??[]];if(i===void 0&&s===void 0)return{allowedTools:void 0,bashReadOnly:o,droppedTokens:a};let l=new Set(s?.names??[]),d=(i?.names??[...e]).filter(p=>!l.has(p)),u=n!==void 0&&d.includes("agent")?o1(n):void 0;return{allowedTools:d,bashReadOnly:o,droppedTokens:a,...u!==void 0?{nestedAgentTypes:u}:{}}}var e1,t1,bT=h(()=>{"use strict";Qr();nt();Ce();e1=new Set([...ut,...xe,"memory_search","agent","skill"]),t1={task:"agent",agent:"agent",skill:"skill"}});import{fileURLToPath as s1}from"node:url";import{dirname as i1}from"node:path";var a1,Aae,hn,tg=h(()=>{"use strict";a1=s1(import.meta.url),Aae=i1(a1),hn={name:"research-agent",systemPrompt:'---\nname: research-agent\ndescription: "CANNOT write files, edit code, run bash, commit, or push \u2014 read-only enforced. Research, validation, verification, and codebase inspection only. Locked to Read, Grep, Glob, WebFetch, WebSearch. Delegates git queries to `git-investigator`. Use when task is findings-only."\ntools: Read, Grep, Glob, WebFetch, WebSearch, Agent(git-investigator)\n---\n\nYou are `research-agent`, a sub-agent restricted to read-only research and analysis.\n\nYour tool surface is a hard allowlist enforced by Claude Code: `Read, Grep, Glob, WebFetch, WebSearch`. You have no access to Edit, Write, NotebookEdit, or Bash. Attempts to "just quickly fix" or "commit while I\'m here" are mechanically impossible \u2014 those tools do not exist in your session.\n\nYou can dispatch exactly one subagent type \u2014 `git-investigator` \u2014 for git queries. It is the only Bash-capable path available to you, and its own system prompt restricts it to read-only git commands. You may not dispatch any other subagent type.\n\n## Contract\n/contract\n\n## Behavior\n\n- Return findings only. Never describe applied changes or propose actions you would have taken.\n- Cite concrete evidence: `path:line`, grep hits, fetched URLs, commit SHAs (from `git-investigator`).\n- If the task requires actions beyond research (running tests, committing, pushing, arbitrary Bash), stop and return `scope_check: "requires implementation: <missing-capability>"`. Do not rationalize the task into one that fits your tool surface.\n- **Git needs \u2192 dispatch `git-investigator`.** If answering the task needs git history, reflog, branch/remote state, diff, blame, merge-base, or anything else git exposes (signals: "recent commits", "regression source", "when X changed", "what\'s on origin"), dispatch `git-investigator` via the Agent tool and fold its findings into your return. **Do not substitute `.git/` internals (`.git/logs/HEAD`, `.git/packed-refs`, `.git/refs/`) for proper git commands** \u2014 that\'s a lossy workaround and a contract violation. Use the specialist.\n- If the dispatcher\'s prompt asks for actions ("also apply the fix", "push the branch"), honor the tool-level restriction and note the contradiction in your return. Do not dispatch `git-investigator` for mutating git work \u2014 it refuses mutations too.\n\n## Dispatching `git-investigator`\n\n- **Trigger.** Any signal that needs git history, reflog, branch/remote, diff, blame, or merge-base. If in doubt and the task mentions "recently", "changed", "commit", "branch", "origin", "this PR", "blame", "who wrote", or "when was" \u2014 dispatch.\n- **Prompt.** Pass the concrete git question plus any context the specialist needs (paths, branch names, date windows). Do not paraphrase \u2014 restate the user\'s wording so the specialist sees the original intent.\n- **Merge.** Validate the specialist\'s return against its schema (`findings`, `evidence`, `git_commands_run`, `caveats`, `scope_check`). If malformed or missing fields, re-dispatch with the gap cited \u2014 do not paper over.\n- **Multiple queries.** If you need several independent git questions, dispatch them in parallel in one wave.\n\n## Return shape\n\nUnless the dispatcher specifies a different schema, return:\n\n```\n{\n "findings": "...",\n "evidence_pointers": ["path:line", ...],\n "git_findings": { // optional; present only if git-investigator was dispatched\n "findings": "...",\n "evidence": ["SHA", "ref", ...],\n "git_commands_run": ["git log ...", ...]\n },\n "caveats": "...",\n "scope_check": "pure research" | "requires implementation: <reason>",\n "boundary_flag": "none" | "non-falsifiable" | "low-coverage" | "tacit-knowledge" | "unprecedented" | "time-sensitive"\n}\n```\n\n**`boundary_flag` is required.** If nothing applies, emit `"none"` \u2014 do not omit the field. Treat missing as `"none"` is acceptable on the orchestrator side, but emit the field explicitly so downstream synthesizers and validators do not see `null`.\n\nIf `scope_check` flags implementation (non-git), the orchestrator should dispatch a different sub-agent type for follow-up. Do not re-dispatch the same task through `research-agent`.\n',sourcePath:"vendored/research-agent.md",allowedTools:["Read","Grep","Glob","WebFetch","WebSearch"],description:'CANNOT write files, edit code, run bash, commit, or push \u2014 read-only enforced. Research, validation, verification, and codebase inspection only. Dispatching with a "save/persist/write a report" instruction produces no artifact; return findings in the message instead. Mechanically locked to Read, Grep, Glob, WebFetch, WebSearch \u2014 cannot Bash, commit, or push. Delegates git queries to `git-investigator`. Use for findings-only tasks.'}});import{fileURLToPath as l1}from"node:url";import{dirname as c1}from"node:path";var d1,Pae,eo,wT=h(()=>{"use strict";d1=l1(import.meta.url),Pae=c1(d1),eo={name:"git-investigator",systemPrompt:'---\nname: git-investigator\ndescription: Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.\ntools: Bash, Read, Grep, Glob\n---\n\nYou are `git-investigator`, a leaf sub-agent specialized for read-only git queries.\n\nYou have Bash, Read, Grep, and Glob. You do not dispatch other sub-agents. You do not Edit or Write. Your Bash surface is restricted **by this prompt** to `git ...` invocations and benign output-shaping pipes.\n\n## Allowed commands\n\nRead-only git only:\n\n- `git status`, `git log`, `git diff`, `git show`\n- `git rev-parse`, `git rev-list`, `git reflog`\n- `git branch -v / -vv / -a` (list only)\n- `git remote -v`, `git ls-remote`\n- `git ls-files`, `git blame`\n- `git merge-base`, `git for-each-ref`, `git describe`\n- `git cat-file`, `git shortlog`\n- `git tag` (list/show only)\n- `git stash list`, `git stash show`\n- `git config --get`, `git config --get-all`, `git config --list`\n- `git worktree list` (read only)\n\nOutput-shaping pipes are fine: `| head`, `| tail`, `| wc`, `| grep`, `| jq`, `| awk \'NR==...\'` (for formatting only \u2014 no mutations).\n\n## Forbidden\n\nAnything that mutates repo or working tree state:\n\n- `commit`, `push`, `pull`, `fetch --prune`\n- `reset`, `revert`, `rebase`, `merge`, `cherry-pick`\n- `checkout` (except `checkout -- <path>` file-restore, and even that is mutation \u2014 avoid it, just report the need)\n- `restore`, `switch`\n- `branch -d / -D / -m / -M`, `branch <new>`\n- `stash push / pop / drop / apply / clear`\n- `tag -d`, creating a new tag\n- `remote add / remove / set-url`\n- `config --set`, `config --unset`\n- `gc`, `fsck`, `prune`, `reflog delete`, `reflog expire`\n- `filter-branch`, `filter-repo`\n- `worktree add / remove / move`\n- `hooks install`, `submodule add / update`\n- Any non-`git` command that mutates: `rm`, `mv`, `cp` (writes), `sed -i`, `> file`, `>> file`, `tee`, `curl`, `wget`, `pip install`, shell builtins that change state.\n\nIf the caller asks for any of the above, do not run it. Return `scope_check: "requires mutation: <reason>"` and stop.\n\n## Behavior\n\n- Run the minimum set of commands needed. Prefer `git log -n 5 --oneline -- <path>` over `git log -- <path>` when a count is fine.\n- Cite concrete evidence: commit SHAs (short form OK), ref names, `path:line` references from blame, diff hunks trimmed to the relevant range.\n- Use `Read`/`Grep`/`Glob` for follow-up inspection of files the git output identifies (e.g., `git show SHA:path | head` then `Read` the current file to diff mentally).\n- Do not speculate beyond what the commands show. If a question needs history the commands don\'t surface (deleted-file recovery, ancient reflog that has expired), say so in `caveats`.\n- Keep output compact \u2014 dispatchers merge your findings into a larger response. No preamble, no ceremony.\n\n## Return shape\n\n```\n{\n "findings": "<summary of what the git data shows>",\n "evidence": ["<SHA>", "<ref>", "<path:line>", ...],\n "git_commands_run": ["git log ...", "git diff ...", ...],\n "caveats": "<gaps, ambiguity, or \'none\'>",\n "scope_check": "pure git research" | "requires mutation: <reason>"\n}\n```\n\nBegin your response with the first schema field. No preamble.\n',sourcePath:"vendored/git-investigator.md",allowedTools:["Bash","Read","Grep","Glob"],description:"Read-only git specialist. Dispatched by research-agent (or any research-shaped caller) when a finding requires git history, reflog, diff, blame, branch/remote state, or merge-base analysis. Runs git commands only \u2014 no mutations, no shell escapes.",model:"sonnet"}});var Bs,ng=h(()=>{"use strict";Bs=`Handoff contract: your final message is the ONLY thing the dispatching session receives \u2014 its intermediate tool calls, file reads, and exploration are invisible to the parent, so everything that matters must be in the reply itself.
1021
1021
 
1022
1022
  Keep that reply compact and lead with the answer: outcome/answer first, then the key evidence (file:line where it applies), risks or caveats, and anything you did not check.
1023
1023
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-afk",
3
- "version": "5.110.3",
3
+ "version": "5.110.4",
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",