agent-afk 5.119.2 → 5.119.3
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 Dce,cR=y(()=>{"use strict";Dce=new Set(["script","style","noscript","template","svg"])});function Lce(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 ON(e,t,n){let r=Math.min(t*2**e,n);return Math.round(Math.random()*r)}function Nce(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 DN(e,t,n={},r={}){let o=r.retries??3,i=r.baseDelayMs??500,s=r.maxDelayMs??1e4,a=r.sleep??Lce,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(!Fce.has(d.status)||u===o)return d;let p=Nce(d,s)??ON(u,i,s);U("[web/retryFetch] retrying",{url:t,attempt:u,status:d.status,waitMs:p}),await d.body?.cancel().catch(()=>{}),await a(p,l)}catch(d){if(l?.aborted||(c=d,u===o))throw d;let p=ON(u,i,s);U("[web/retryFetch] retrying after error",{url:t,attempt:u,waitMs:p}),await a(p,l)}}throw c??new Error("retryFetch: exhausted without a result")}var Fce,$N=y(()=>{"use strict";ue();Fce=new Set([429,502,503,504])});import{BlockList as Bce,isIP as dR}from"node:net";import{lookup as Uce}from"node:dns/promises";import{Agent as jce}from"undici";function LN(){let e=v.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return e==="1"||e==="true"}function Gce(e){return e.startsWith("[")&&e.endsWith("]")?e.slice(1,-1):e}function uR(e){let t=dR(e);return t===0?!1:Kce.check(e,t===4?"ipv4":"ipv6")}async function NN(e){return Uce(e,{all:!0,verbatim:!0})}async function pR(e,t={}){if(t.allowPrivateHosts??LN())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=Gce(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(dR(r)!==0)return uR(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let i=t.lookupFn??NN,s;try{s=await i(r)}catch{return{allowed:!0}}for(let a of s)if(uR(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function pp(e,t={}){let n=await pR(e,t);if(!n.allowed)throw new er(n.reason)}async function Gh(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<=FN;s++){await pp(i,o);let a={...n,redirect:"manual",...e===globalThis.fetch&&!(r.allowPrivateHosts??LN())?{dispatcher:qce}:{}},l=await DN(e,i,a,r.retry??{});if(!zce.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 er(`too many redirects (>${FN}) starting from ${t}`)}var Hce,Wce,Kce,er,qce,FN,zce,mR=y(()=>{"use strict";B();$N();Hce=[["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]],Wce=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],Kce=(()=>{let e=new Bce;for(let[t,n]of Hce)e.addSubnet(t,n,"ipv4");for(let[t,n]of Wce)e.addSubnet(t,n,"ipv6");return e})(),er=class extends Error{constructor(t){super(t),this.name="EgressBlockedError"}};qce=new jce({connect:{lookup(e,t,n){NN(e).then(r=>{let o=r.find(s=>uR(s.address));if(o!==void 0){n(new er(`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,dR(i.address))},r=>n(r,"",0))}}});FN=20,zce=new Set([301,302,303,307,308])});import{readFileSync as Vce}from"node:fs";import{join as Yce}from"path";function Jce(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function BN(e,t){return Jce(t).test(e)}function Zce(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(Xce.has(t))return!0;if(Qce.has(t))return!1}return!1}function UN(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function eue(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 jN(e){let t=e===void 0||e.trim()===""?"default":e.trim();return fd(t),t}function tue(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function nue(e){try{return Vce(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function rue(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=jN(t.defaultProfile)),n}function HN(e){let t=e?.env??v,n=e?.readFileSync??nue,r=e?.surface??t.AGENT_SURFACE,o=Zce(t.AFK_BROWSER_HEADLESS,r),i=UN(t.AFK_BROWSER_ALLOWED_DOMAINS),s=UN(t.AFK_BROWSER_BLOCKED_DOMAINS),a=tue(t.AFK_BROWSER_DOM_SNAPSHOTS),l=eue(t.AFK_BROWSER_BACKEND),c=jN(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,p=d!==void 0&&d.trim()!==""?d.trim():Yce(qn(),"browser.json"),f=n(p);if(f===void 0)return u;let g;try{g=JSON.parse(f)}catch(b){throw new Error(`Failed to parse browser config at ${p}: ${String(b)}`)}if(typeof g!="object"||g===null||Array.isArray(g))throw new Error(`Browser config at ${p} must be a JSON object`);let h=rue(u,g);return h.configPath=p,h}function qh(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(BN(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>BN(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Xce,Qce,zh=y(()=>{"use strict";B();K();Xce=new Set(["daemon","subagent","telegram","afk"]),Qce=new Set(["repl","interactive","cli"])});import{existsSync as oue,readFileSync as iue}from"node:fs";import{createRequire as sue}from"node:module";import{dirname as aue,join as lue}from"node:path";function GN(e){if(typeof e=="string")return e;let t=[],n=e;for(let r=0;r<uue&&n instanceof Error;r++)t.push(n.message),n=n.cause;return t.length>0?t.join(" | "):String(e)}function tn(e){let t=GN(e);return KN.some(n=>t.includes(n))}function due(){try{let t=sue(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(iue(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=lue(aue(t),o);return oue(i)?`node ${/\s/.test(i)?`"${i}"`:i} install chromium`:void 0}catch{return}}function mp(){return WN??=due()??cue,WN}function fR(e){return e.includes("install chromium")}function Mn(e,t){let n=GN(e),r=t?.latched===!0?` ${pue}`:"";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: ${mp()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${mp()}). Or pick a different tool.${r}`}function fp(e,t,n=!1){if(!tn(e))return e;let r=e instanceof Error?e.message:String(e);return new Error(`${r}
|
|
316
316
|
|
|
317
|
-
${Mn(e,{headless:t,latched:n})}`,{cause:e})}var KN,cue,uue,WN,pue,Vh=y(()=>{"use strict";KN=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],cue="pnpm exec playwright install chromium",uue=4;pue="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 Ns from"node:fs";import Yh from"node:path";import{randomBytes as mue}from"node:crypto";import{chromium as fue}from"playwright";function gue(){try{return"5.119.2"}catch{}try{let e=Yh.resolve(import.meta.dirname,"../../../package.json"),t=Ns.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var hue,Jh,qN=y(()=>{"use strict";Vh();K();ue();hue=gue(),Jh=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=fue.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=fp(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){i=l,await a.abort("blockedbyclient")}});let s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw i??p}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;let 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/${hue}`}}loadStorageState(t){let n=gd(t);try{if(!Ns.existsSync(n))return;let r=JSON.parse(Ns.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=gd(t);if(!Ns.existsSync(r))return;let o=await n.storageState(),i=Yh.join(Yh.dirname(r),`.${Yh.basename(r)}.${process.pid}.${mue(4).toString("hex")}.tmp`);Ns.writeFileSync(i,JSON.stringify(o),{mode:384}),Ns.chmodSync(i,384),Ns.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 yue}from"crypto";function zN(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&bue.test(e.label))}function VN(e){return yue("sha256").update(e,"utf8").digest("hex").slice(0,8)}function YN(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var bue,Xh=y(()=>{"use strict";bue=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Sue}from"node:crypto";function wue(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function vue(e,t,n){return`el_${Sue("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function kue(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function JN(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function QN(e,t){let n=e.role??"",r=e.name??"";XN.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])QN(i,t)}async function Tue(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},ZN).catch(()=>[])}async function Eue(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,p=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},ZN).catch(()=>[])}function xue(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Qh(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=xue(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Tue(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,f,g,h]=await Promise.all([s,a,l,c,u]),b,S=!1;d!==null?(b=[],QN(d,b)):(o.push("observation skipped accessibility tree (returned null)"),S=!0,b=(await Eue(e)).filter(O=>XN.has(O.role??"")));let w=new Map;for(let P of p){let O=JN(P.name),z=w.get(O);(!z||z.bbox.w===0&&P.bbox.w>0)&&w.set(O,P)}let k=b.map(P=>({ax:P,dom:w.get(JN(P.name??""))})),E=r?k:k.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);E.sort((P,O)=>{let z=P.dom?.bbox.y??0,$=O.dom?.bbox.y??0;if(z!==$)return z-$;let G=P.dom?.bbox.x??0,H=O.dom?.bbox.x??0;return G-H}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=E.slice(0,n).map((P,O)=>{let z=P.ax.role??"generic",$=P.ax.name??"",G=vue(z,$,O),H=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)),zN({role:z,kind:I})&&(L="[redacted]");let F={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(F.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(F.selected=P.ax.selected),P.ax.expanded!==void 0&&(F.expanded=P.ax.expanded);let D;P.dom?.testId?D=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(D=`#${P.dom.id}`);let W={id:G,role:z,label:wue($),kind:I,value:L,state:F,bbox:H};return D!==void 0&&(W.selector=D),W}),M="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?M="loading":P==="interactive"?M="navigating":M="idle"}catch{M="navigating"}M!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),S&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let _=kue(f),R=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:R,url:g,title:h,textSummary:_,interactive:A,status:{httpStatus:t.httpStatus??null,loadingState:M,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var XN,ZN,eB=y(()=>{"use strict";Xh();XN=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);ZN="a[href], button, input, select, textarea, [role], [tabindex], label"});async function tB(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 gR(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>tB(e,i)))).filter(o=>o!==null)}async function Rue(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 hR(e,t,n){switch(t.kind){case"element_id":return Aue(e,t,n);case"selector":return Cue(e,t);case"semantic":return _ue(e,t)}}async function Aue(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 gR(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function Cue(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 gR(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function _ue(e,t){return t.role!==void 0?Iue(e,t.text,t.role):Pue(e,t.text,t)}async function Iue(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 gR(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function Pue(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 Rue(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 p=d.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let S=await tB(b.locator,b.index);if(S!==null){let w=`${S.role}:${S.label}:${h}`,k=0;for(let E=0;E<w.length;E++)k=k*31+w.charCodeAt(E)>>>0;f.push({...S,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var nB=y(()=>{"use strict"});async function yR(e,t,n,r){let o=e.url();if(o===n)return null;let i=qh(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 rB=y(()=>{"use strict";zh()});import{randomBytes as Mue}from"crypto";import{mkdir as Oue,stat as Due,writeFile as $ue}from"fs/promises";import{join as bR}from"path";import{gzip as Fue}from"zlib";import{promisify as Lue}from"util";function Nue(e){return bR(un(e),"browser")}function Bue(e){return bR(Nue(e),"screenshots")}function Uue(){return new Date().toISOString().replace(/[:.]/g,"-")}function jue(){return Mue(3).toString("hex")}async function SR(e,t,n){if(t.length>oB)throw new Error(`writeScreenshotSidecar: buffer exceeds ${oB} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=Bue(e);await Oue(r,{recursive:!0});let o=`${Uue()}-${jue()}-${n}.png`,i=bR(r,o);await $ue(i,t);let{size:s}=await Due(i);return{path:i,bytes:s}}var nYe,oB,iB=y(()=>{"use strict";K();Xh();nYe=Lue(Fue);oB=5*1024*1024});var aB={};no(aB,{PlaywrightProvider:()=>wR});function sB(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 wR,lB=y(()=>{"use strict";qN();eB();nB();zh();rB();iB();wR=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Jh(t)}async open(t){let n=qh(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 yR(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 Qh(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 Qh(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 hR(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${sB(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 yR(r,this.config,i,()=>this.close({sessionId:n}));if(d!==null)return d;let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Qh(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,requestGuard:t.requestGuard})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),i;if(t.target!==void 0){let u=await hR(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${sB(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 SR(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 SR(n,o,r);return i}catch{return null}}}});var Us={};no(Us,{__resetBrowserRegistryForTests:()=>que,browserProviderActive:()=>Kue,closeBrowserProvider:()=>vR,getBrowserProvider:()=>Wue,peekBrowserProvider:()=>Gue});function cB(){Promise.resolve(vR()).then(()=>{process.exit(130)})}function uB(){Promise.resolve(vR()).then(()=>{process.exit(143)})}function dB(){Mr=null}function Hue(){Zh||(process.on("SIGINT",cB),process.on("SIGTERM",uB),process.on("exit",dB),Zh=!0)}function pB(){Zh&&(process.removeListener("SIGINT",cB),process.removeListener("SIGTERM",uB),process.removeListener("exit",dB),Zh=!1)}async function Wue(e){return Mr!==null?Mr:(Bs!==null||(Bs=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(lB(),aB)),n=HN(e),r=new t(n);return Hue(),Mr=r,Bs=null,r})()),Bs)}async function vR(){if(Mr===null)return;let e=Mr;Mr=null,Bs=null,pB(),await e.shutdown()}function Kue(){return Mr!==null}function Gue(){return Mr}function que(){Mr=null,Bs=null,pB()}var Mr,Bs,Zh,js=y(()=>{"use strict";zh();Mr=null,Bs=null,Zh=!1});async function mB(e,t){try{return await IN(e,t)}catch(n){return U("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function Que(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(js(),Us));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function fB(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??Que,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let d=await Gh(n,e,{headers:Xue,signal:t.signal},o);l=d.status,a=d.url||e;let p=d.headers.get("content-type")??"";if(d.ok){if(Jue.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 d.text();if(Yue.test(p)&&!Vue.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await mB(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof er||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=lR({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...d!==void 0?{advisory:d}:{}}}try{await pp(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>pp(f,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await pp(d.finalUrl,o);let p=await mB(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=lR({html:d.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:d.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(d){if(t.signal.aborted||d instanceof er)throw d;if(i===null){let p=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 (${p}).`);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 Vue,Yue,Jue,Xue,gB=y(()=>{"use strict";PN();cR();mR();ue();Vue=/(text\/html|application\/xhtml\+xml)/i,Yue=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,Jue=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,Xue={"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 tde(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(Zue,{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),ede),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=Oe(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 hB(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?tde({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 yB(e,t){if(t.length===0)return`# Search results for "${e}"
|
|
317
|
+
${Mn(e,{headless:t,latched:n})}`,{cause:e})}var KN,cue,uue,WN,pue,Vh=y(()=>{"use strict";KN=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],cue="pnpm exec playwright install chromium",uue=4;pue="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 Ns from"node:fs";import Yh from"node:path";import{randomBytes as mue}from"node:crypto";import{chromium as fue}from"playwright";function gue(){try{return"5.119.3"}catch{}try{let e=Yh.resolve(import.meta.dirname,"../../../package.json"),t=Ns.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var hue,Jh,qN=y(()=>{"use strict";Vh();K();ue();hue=gue(),Jh=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=fue.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=fp(t,this.config.headless,!0);throw this.latchLaunchFailure(n),n}),this.launchPromise)}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let r=await this.ensureBrowser(),o=this.loadStorageState(this.config.defaultProfile),i=await r.newContext({...this.contextOptions(),...o!==void 0?{storageState:o}:{}}),s={context:i,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),i}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",i=>{i.type()==="error"&&(r.consoleErrors+=1)}),o.on("request",i=>{i.isNavigationRequest()&&i.frame()===o.mainFrame()&&(r.lastHttpStatus=null)}),o.on("response",i=>{i.frame()===o.mainFrame()&&i.request().isNavigationRequest()&&(r.lastHttpStatus=i.status())}),o.on("dialog",i=>{r.openDialog=i}),o}getPage(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),i;n.requestGuard!==void 0&&await o.route("**/*",async a=>{try{await n.requestGuard(a.request().url()),await a.continue()}catch(l){i=l,await a.abort("blockedbyclient")}});let s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let a=await o.newPage(),l;try{l=await a.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw i??p}if(i!==void 0)throw i;let c=await a.content();if(i!==void 0)throw i;let 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/${hue}`}}loadStorageState(t){let n=gd(t);try{if(!Ns.existsSync(n))return;let r=JSON.parse(Ns.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=gd(t);if(!Ns.existsSync(r))return;let o=await n.storageState(),i=Yh.join(Yh.dirname(r),`.${Yh.basename(r)}.${process.pid}.${mue(4).toString("hex")}.tmp`);Ns.writeFileSync(i,JSON.stringify(o),{mode:384}),Ns.chmodSync(i,384),Ns.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 yue}from"crypto";function zN(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&bue.test(e.label))}function VN(e){return yue("sha256").update(e,"utf8").digest("hex").slice(0,8)}function YN(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var bue,Xh=y(()=>{"use strict";bue=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Sue}from"node:crypto";function wue(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function vue(e,t,n){return`el_${Sue("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function kue(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function JN(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function QN(e,t){let n=e.role??"",r=e.name??"";XN.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let i of e.children??[])QN(i,t)}async function Tue(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},ZN).catch(()=>[])}async function Eue(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,p=i.disabled??!1,f=s==="input"?i.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},ZN).catch(()=>[])}function xue(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Qh(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],i=xue(e),s=i?i.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Tue(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,f,g,h]=await Promise.all([s,a,l,c,u]),b,S=!1;d!==null?(b=[],QN(d,b)):(o.push("observation skipped accessibility tree (returned null)"),S=!0,b=(await Eue(e)).filter(O=>XN.has(O.role??"")));let w=new Map;for(let P of p){let O=JN(P.name),z=w.get(O);(!z||z.bbox.w===0&&P.bbox.w>0)&&w.set(O,P)}let k=b.map(P=>({ax:P,dom:w.get(JN(P.name??""))})),E=r?k:k.filter(P=>P.dom?P.dom.bbox.w>0||P.dom.bbox.h>0:!0);E.sort((P,O)=>{let z=P.dom?.bbox.y??0,$=O.dom?.bbox.y??0;if(z!==$)return z-$;let G=P.dom?.bbox.x??0,H=O.dom?.bbox.x??0;return G-H}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=E.slice(0,n).map((P,O)=>{let z=P.ax.role??"generic",$=P.ax.name??"",G=vue(z,$,O),H=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)),zN({role:z,kind:I})&&(L="[redacted]");let F={disabled:P.ax.disabled??!1};P.ax.checked!==void 0&&(F.checked=P.ax.checked===!0||P.ax.checked==="mixed"),P.ax.selected!==void 0&&(F.selected=P.ax.selected),P.ax.expanded!==void 0&&(F.expanded=P.ax.expanded);let D;P.dom?.testId?D=`[data-testid="${P.dom.testId}"]`:P.dom?.id&&(D=`#${P.dom.id}`);let W={id:G,role:z,label:wue($),kind:I,value:L,state:F,bbox:H};return D!==void 0&&(W.selector=D),W}),M="idle";try{let P=await e.evaluate(()=>document.readyState);P==="loading"?M="loading":P==="interactive"?M="navigating":M="idle"}catch{M="navigating"}M!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),S&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let _=kue(f),R=`obs_${t.observationCounter.toString(36)}`,C=new Date().toISOString();return{observationId:R,url:g,title:h,textSummary:_,interactive:A,status:{httpStatus:t.httpStatus??null,loadingState:M,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:C}}var XN,ZN,eB=y(()=>{"use strict";Xh();XN=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);ZN="a[href], button, input, select, textarea, [role], [tabindex], label"});async function tB(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 gR(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,i)=>tB(e,i)))).filter(o=>o!==null)}async function Rue(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 hR(e,t,n){switch(t.kind){case"element_id":return Aue(e,t,n);case"selector":return Cue(e,t);case"semantic":return _ue(e,t)}}async function Aue(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 gR(o,i);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:s}}async function Cue(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 gR(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function _ue(e,t){return t.role!==void 0?Iue(e,t.text,t.role):Pue(e,t.text,t)}async function Iue(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 gR(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:i}}async function Pue(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 Rue(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 p=d.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let S=await tB(b.locator,b.index);if(S!==null){let w=`${S.role}:${S.label}:${h}`,k=0;for(let E=0;E<w.length;E++)k=k*31+w.charCodeAt(E)>>>0;f.push({...S,id:`el_${k.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var nB=y(()=>{"use strict"});async function yR(e,t,n,r){let o=e.url();if(o===n)return null;let i=qh(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 rB=y(()=>{"use strict";zh()});import{randomBytes as Mue}from"crypto";import{mkdir as Oue,stat as Due,writeFile as $ue}from"fs/promises";import{join as bR}from"path";import{gzip as Fue}from"zlib";import{promisify as Lue}from"util";function Nue(e){return bR(un(e),"browser")}function Bue(e){return bR(Nue(e),"screenshots")}function Uue(){return new Date().toISOString().replace(/[:.]/g,"-")}function jue(){return Mue(3).toString("hex")}async function SR(e,t,n){if(t.length>oB)throw new Error(`writeScreenshotSidecar: buffer exceeds ${oB} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=Bue(e);await Oue(r,{recursive:!0});let o=`${Uue()}-${jue()}-${n}.png`,i=bR(r,o);await $ue(i,t);let{size:s}=await Due(i);return{path:i,bytes:s}}var nYe,oB,iB=y(()=>{"use strict";K();Xh();nYe=Lue(Fue);oB=5*1024*1024});var aB={};no(aB,{PlaywrightProvider:()=>wR});function sB(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 wR,lB=y(()=>{"use strict";qN();eB();nB();zh();rB();iB();wR=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Jh(t)}async open(t){let n=qh(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 yR(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 Qh(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 Qh(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 hR(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${sB(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 yR(r,this.config,i,()=>this.close({sessionId:n}));if(d!==null)return d;let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Qh(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal,requestGuard:t.requestGuard})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),i;if(t.target!==void 0){let u=await hR(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${sB(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 SR(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 SR(n,o,r);return i}catch{return null}}}});var Us={};no(Us,{__resetBrowserRegistryForTests:()=>que,browserProviderActive:()=>Kue,closeBrowserProvider:()=>vR,getBrowserProvider:()=>Wue,peekBrowserProvider:()=>Gue});function cB(){Promise.resolve(vR()).then(()=>{process.exit(130)})}function uB(){Promise.resolve(vR()).then(()=>{process.exit(143)})}function dB(){Mr=null}function Hue(){Zh||(process.on("SIGINT",cB),process.on("SIGTERM",uB),process.on("exit",dB),Zh=!0)}function pB(){Zh&&(process.removeListener("SIGINT",cB),process.removeListener("SIGTERM",uB),process.removeListener("exit",dB),Zh=!1)}async function Wue(e){return Mr!==null?Mr:(Bs!==null||(Bs=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(lB(),aB)),n=HN(e),r=new t(n);return Hue(),Mr=r,Bs=null,r})()),Bs)}async function vR(){if(Mr===null)return;let e=Mr;Mr=null,Bs=null,pB(),await e.shutdown()}function Kue(){return Mr!==null}function Gue(){return Mr}function que(){Mr=null,Bs=null,pB()}var Mr,Bs,Zh,js=y(()=>{"use strict";zh();Mr=null,Bs=null,Zh=!1});async function mB(e,t){try{return await IN(e,t)}catch(n){return U("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function Que(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(js(),Us));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:t.requestGuard})}async function fB(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??Que,o=t.lookupFn!==void 0?{lookupFn:t.lookupFn}:{},i=null,s="",a=e,l=null,c=null;try{let d=await Gh(n,e,{headers:Xue,signal:t.signal},o);l=d.status,a=d.url||e;let p=d.headers.get("content-type")??"";if(d.ok){if(Jue.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 d.text();if(Yue.test(p)&&!Vue.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(s=f,i=await mB(f,a),t.signal.aborted)throw t.signal.reason??new Error("aborted")}}catch(d){if(t.signal.aborted||d instanceof er||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=lR({html:s,extractedTextLength:i.textLength});return{title:i.title,markdown:i.markdown,finalUrl:a,usedRender:!1,...d!==void 0?{advisory:d}:{}}}try{await pp(e,o);let d=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal,requestGuard:f=>pp(f,o)});d.finalUrl!==e&&/^https?:\/\//i.test(d.finalUrl)&&await pp(d.finalUrl,o);let p=await mB(d.html,d.finalUrl);if(t.signal.aborted)throw t.signal.reason??new Error("aborted");if(i===null||p.textLength>=i.textLength){let f=lR({html:d.html,extractedTextLength:p.textLength});return{title:p.title,markdown:p.markdown,finalUrl:d.finalUrl,usedRender:!0,...f!==void 0?{advisory:f}:{}}}}catch(d){if(t.signal.aborted||d instanceof er)throw d;if(i===null){let p=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 (${p}).`);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 Vue,Yue,Jue,Xue,gB=y(()=>{"use strict";PN();cR();mR();ue();Vue=/(text\/html|application\/xhtml\+xml)/i,Yue=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,Jue=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,Xue={"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 tde(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let i=await t(Zue,{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),ede),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!i.ok){let l="";try{let u=await i.text(),d=Oe(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 hB(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?tde({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 yB(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 Zue,ede,bB=y(()=>{"use strict";_n();Zue="https://api.exa.ai/search",ede=10});function ey(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 Hs=y(()=>{"use strict";Vh()});function ade(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=nde;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,rde)}let a=ode;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,ide)}return{mode:r,url:o,query:i,timeoutMs:s,maxBytes:a}}function kR(e,t){return Buffer.byteLength(e,"utf8")<=t?{content:e,truncated:!1}:{content:ao(e,t),truncated:!0}}function lde(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=ade(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 p=await pR(s.url,r);if(a.signal.aborted)return{content:`web_scrape aborted: ${u()}`,isError:!0};if(!p.allowed)return{content:`web_scrape blocked: ${p.reason}`,isError:!0}}if(s.mode==="raw"){let p;try{let h={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await Gh(t,s.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:h instanceof er?{content:`web_scrape blocked: ${h.message}`,isError:!0}:{content:`web_scrape network error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let f;try{f=await p.text()}catch(h){return{content:`web_scrape read error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let g=kR(f,s.maxBytes);return{content:g.content,...g.truncated?{truncated:!0}:{}}}if(s.mode==="markdown")try{let p=await fB(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:a.signal,...e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{}});if(p.markdown.trim().length===0)return{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0};let f=kR(MN(p.markdown,p.advisory),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){if(a.signal.aborted)return{content:`web_scrape aborted: ${u()}`,isError:!0};if(p instanceof er)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),g=tn(p)&&!fR(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${mp()}\`)`:"";return{content:`web_scrape markdown error: ${f}${g}`,isError:!0}}let d=hB({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in d)return{content:d.error,isError:!0};try{let p=await d.search(s.query,{limit:sde,timeoutMs:s.timeoutMs,signal:a.signal}),f=kR(yB(s.query,p),s.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){return a.signal.aborted?{content:`web_scrape aborted: ${u()}`,isError:!0}:{content:`web_scrape search error (${d.name}): ${p instanceof Error?p.message:String(p)}`,isError:!0}}}finally{c!==void 0&&clearTimeout(c),i.removeEventListener("abort",l)}}}var nde,rde,ode,ide,sde,SB,wB=y(()=>{"use strict";gB();bB();mR();ei();cR();Hs();nde=3e4,rde=12e4,ode=1e5,ide=1e6,sde=10;SB=lde()});import{existsSync as kB,mkdirSync as cde,readFileSync as ude,renameSync as dde,unlinkSync as pde,writeFileSync as mde}from"node:fs";import{dirname as vB,join as fde}from"node:path";import{randomBytes as gde}from"node:crypto";function On(e){let t=e??cE();if(!kB(t))return[];try{let n=ude(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 Ws(e,t){let n=t??cE();cde(vB(n),{recursive:!0});let r=fde(vB(n),`.schedules.json.${process.pid}.${gde(4).toString("hex")}.tmp`),o=JSON.stringify(e,null,2);try{mde(r,o,"utf-8"),dde(r,n)}catch(i){try{kB(r)&&pde(r)}catch{}throw i}}function ty(e,t){let n=On(t),r=n.map(l=>l.id),o=hde(e.name),i=yde(o,r),s=new Date().toISOString(),a={...e,notifyOn:e.notifyOn??"failure",id:i,createdAt:s,updatedAt:s};return n.push(a),Ws(n,t),a}function ny(e,t){let n=On(t),r=n.length,o=n.filter(i=>i.id!==e);return o.length===r?!1:(Ws(o,t),!0)}function gp(e,t){return On(t).find(n=>n.id===e)}function hde(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function yde(e,t){if(!t.includes(e))return e;let n=2;for(;t.includes(`${e}-${n}`);)n+=1;return`${e}-${n}`}function TB(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 ry=y(()=>{"use strict";K()});import{existsSync as bde,readFileSync as Sde}from"node:fs";import{join as wde}from"node:path";async function tr(e,t,n){let r;try{let o=wde(pg("default"),"port");if(!bde(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=Sde(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 si,TR=y(()=>{"use strict";K();si="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 vde}from"node:fs";import{readFile as kde}from"node:fs/promises";var EB,xB,RB,AB,CB=y(()=>{"use strict";ry();K();TR();EB=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=ty({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 tr("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 tr("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:si}})}},xB=async(e,t)=>{let n=On();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})))}},RB=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=yr();if(!vde(i))return{content:JSON.stringify([])};let s;try{let c=await kde(i);s=(c.length>1048576?c.subarray(c.length-1048576):c).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=s.split(`
|
|
@@ -1069,7 +1069,7 @@ ${b}`:l,sessionId:this.initSessionId},yield*this.finishTurn(p!==null?{...a,stopR
|
|
|
1069
1069
|
|
|
1070
1070
|
`+a})}if(r!==null){let a=r===ir?wb:Eb;o.push({role:"user",content:a})}let i=r!==null?void 0:this.activeOpenAITools(),s={controller:t,traceWriter:this.traceWriter,initSessionId:this.initSessionId,currentModel:this.currentModel,isClosed:()=>this.closed};if(this.wireMode==="responses"){let a=this.opts.auth.source==="chatgpt-oauth";if(a&&rb(this.currentModel))return yield{type:"error",error:new Error(`Model "${this.currentModel}" can't run on a ChatGPT subscription \u2014 the ChatGPT/Codex backend only supports OpenAI gpt-5.x models. This usually means a subagent or skill requested a Claude model. Pass a gpt-5.x model to it (e.g. model: "gpt-5.5"); for an auto-dispatched agent you can't pass a model to (e.g. git-investigator), set AFK_DEFAULT_SUBAGENT_MODEL to a gpt-5.x id. Or run it on a provider configured with the matching API key.`)},null;let l=lb({model:this.currentModel,messages:o,activeTools:i,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort,isChatGptBackend:a});return yield*GA(s,{createStream:async c=>await this.client.responses.create(l,{signal:c}),translate:(c,u)=>nb(c,u,this.initSessionId),clarifyError:c=>this.clarifyResponsesError(c,a)})}else{let a=S1({model:this.currentModel,messages:o,activeTools:i,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort});return yield*GA(s,{createStream:async l=>await this.client.chat.completions.create(a,{signal:l}),translate:(l,c)=>Yj(l,c,this.initSessionId),clarifyError:l=>l instanceof Error?l:new Error(String(l))})}}async*dispatchAndAppend(t,n,r){return yield*R1({state:t,signal:n,vision:r,toolDispatcher:this.toolDispatcher,traceWriter:this.traceWriter,priorTurns:this.priorTurns,sessionId:this.initSessionId,subagentId:this.opts.config.subagentId})}async interrupt(t="interrupted"){this.abort.requestAbort(t)}async compact(){let t=await this.compactHistory("manual");return t.compacted&&(this.lastUsage=null),t}async compactHistory(t){let n=this.priorTurns.length;if(this.opts.auth.apiKey===null)return{compacted:!1,reason:"no-usable-auth",messagesBefore:n,messagesAfter:n};if(this.wireMode==="responses"&&this.responsesCompactionUnavailable){let i=ic(v.AFK_MICROCOMPACT_TOOL_RESULT_BYTES,v.AFK_MICROCOMPACT_KEEP_LAST),{blocksCleared:s,bytesReclaimed:a}=DA(this.priorTurns,i);return s>0?{compacted:!1,reason:"microcompacted",messagesBefore:n,messagesAfter:this.priorTurns.length,microcompaction:{blocksCleared:s,bytesReclaimed:a}}:{compacted:!1,reason:"responses-compaction-unavailable",messagesBefore:n,messagesAfter:n}}let r=v.AFK_COMPACT_MODEL??this.currentModel,o=Pd(Ct(this.lastUsage??{}),so(this.currentModel));return p1({priorTurns:this.priorTurns,usedFraction:o,shrinkAtFraction:d1(),summarize:(i,s)=>this.wireMode==="responses"?this.summarizeViaResponses(i,s,r):ub({client:this.client,model:r,system:Op,user:Fp(i),maxTokens:1024,signal:s}),isClosed:this.closed,isIdle:this.abort.isIdle(),beginAbort:()=>this.abort.begin(),clearAbort:i=>this.abort.clear(i),trigger:t,traceWriter:this.traceWriter})}async summarizeViaResponses(t,n,r){try{return await v1({client:this.client,model:r,system:Op,user:Fp(t),isChatGptBackend:this.opts.auth.source==="chatgpt-oauth",maxTokens:1024,signal:n})}catch(o){if(!n.aborted&&F1(o)){this.responsesCompactionUnavailable=!0;let i=gi(o);re(this.traceWriter,{phase:"compaction_disabled",metadata:{wire:"responses",reason:"responses-compaction-unavailable",error:o instanceof Error?o.message:String(o),...i!==void 0?{status:i}:{}}})}throw o}}async setModel(t){t!==void 0&&(this.currentModel=At(t)??t)}async setPermissionMode(t){this.currentPermissionMode=$A(t);let n=Yn(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(t){this.toolDispatcher?.setResolveBase?.(t),this.onCwdChange?.(t)}async supportedCommands(){return Jy()}async supportedModels(){return[{value:"gpt-5.6",displayName:"GPT-5.6 (Sol)",description:"OpenAI flagship \u2014 alias for gpt-5.6-sol"},{value:"gpt-5.6-sol",displayName:"GPT-5.6 Sol",description:"Frontier capability"},{value:"gpt-5.6-terra",displayName:"GPT-5.6 Terra",description:"Balanced intelligence/cost"},{value:"gpt-5.6-luna",displayName:"GPT-5.6 Luna",description:"Fast, high-volume workloads"},{value:"gpt-5.5",displayName:"GPT-5.5",description:"Prior flagship (ChatGPT backend)"},{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let t=this.lastUsage,n=it(this.currentModel),r;if(t&&n>0){let s=Ct(t);r=Math.min(100,Math.max(0,s/n*100))}let{totalTokens:o,apiUsage:i}=_d(t);return{tools:[],agents:[],isAutoCompactEnabled:this.autoCompactThreshold!==void 0,apiUsage:i,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(t=>({name:t.serverName,status:t.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(t,n){return{canRewind:!1,error:`${qA} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed(),U(`\u{1F7E2} ${qA}: closed`)}}});var VA,zt,Jfe,cc=y(()=>{"use strict";Fy();eh();Al();Vg();vl();XR();qs();mn();Nt();hA();or();zA();db();Lt();uA();ec();zA();VA="openai-compatible",zt=class{name=VA;providerOpts;memoryStore;schemas;_defaultHeaders;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_presenceSessionId=null;_mintedSessionId=null;constructor(t={}){this.providerOpts=t,this._defaultHeaders=t.defaultHeaders,this.memoryStore=t.memoryStore??new _t;let n=[...Cr];t.subagentExecutor&&n.push(t.subagentExecutor.describeAgentTool?.()??pn),t.skillExecutor&&n.push(As),t.composeExecutor&&n.push(Cs),t.readOnlyMemory===!0?n.push(Tl):n.push(...ti),n.push(Jn);for(let r of t.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);this.schemas=n}setEndpointDefaults(t){t.baseURL!==void 0&&(this.providerOpts.baseURL=t.baseURL),t.defaultHeaders!==void 0&&(this._defaultHeaders=t.defaultHeaders)}query(t){let n=t.config,r=n.permissionMode??"default";this._currentPermissionMode=r,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,i=typeof n.model=="string"?n.model:String(n.model),s=n.cwd??process.cwd(),a=Ud({surface:this.providerOpts.surface??"cli",getCwd:()=>s,modelName:i,providerName:VA,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof Xt?o.toolDefs.map(E=>E.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?jd(this.providerOpts.tools,a):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.subagentId!==void 0?{subagentId:n.subagentId}:{},...n.subagentToolOutputCapBytes!==void 0?{subagentToolOutputCapBytes:n.subagentToolOutputCapBytes}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},runtimeStateSource:a,...n.isSkillDispatch?{isSkillDispatch:!0}:{},...n.isNonInteractive?{isNonInteractive:!0}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{},...n.planExitControls!==void 0?{planExitControls:n.planExitControls}:{}});let l=Ep({sessionId:n.sessionId,resume:n.resume,depth:n.depth,parentSessionId:n.parentSessionId,surface:this.providerOpts.surface??"cli",memoized:this._mintedSessionId});this._mintedSessionId=l.memoized;let c={};l.id!==void 0&&(c.sessionIdOverride=l.id);let u=n.openaiBaseUrl??this.providerOpts.baseURL;u!==void 0&&(c.baseURL=u),this._defaultHeaders!==void 0&&(c.defaultHeaders=this._defaultHeaders),c.toolDispatcher=o,c.onPermissionMode=E=>{this._currentPermissionMode=E},this.providerOpts.mcpManager!==void 0&&(c.mcpManager=this.providerOpts.mcpManager),this._presenceSessionId=xp({depth:n.depth,parentSessionId:n.parentSessionId,sessionId:l.id,currentPresenceSessionId:this._presenceSessionId,runtimeStateSource:a,surface:this.providerOpts.surface??"cli",cwd:n.cwd,providerName:VA,model:i});let d=Vy(n.isSkillDispatch),p=Yy(this.providerOpts.readOnlyMemory),f=this.providerOpts.skillExecutor?Cb(void 0,{...typeof n.cwd=="string"&&n.cwd.length>0?{cwd:n.cwd}:{},...typeof n.skillDispatchName=="string"&&n.skillDispatchName.length>0?{excludeName:n.skillDispatchName}:{}}):"",g=typeof n.hotMemory=="string"?n.hotMemory:"",h=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,b=E=>{let T=[d];return h!==void 0&&h.length>0&&T.push(h),T.push(p),g.length>0&&T.push(g),T.push(E),f.length>0&&T.push(f),T.join(`
|
|
1071
1071
|
|
|
1072
|
-
`)},S=()=>Bd({cwd:s,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:a.getWorkspace()}),w={...n,systemPrompt:b(S())},k=E=>{s=E,w.systemPrompt=b(S())};return c.onCwdChange=k,N1(w,t.prompt,c)}buildDispatcher(t,n){let r=Iy(t,n.cwd),o=Nd(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[u,d]of o)this.providerOpts.readOnlyMemory===!0&&u!=="memory_search"||r.set(u,d);n.runtimeStateSource&&r.set("get_runtime_state",El(n.runtimeStateSource));for(let u of this.providerOpts.customTools??[])r.has(u.schema.name)||r.set(u.schema.name,u.handler);let i=n.planExitControls;i&&r.set(hn,Oy(i));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[u,d]of this.providerOpts.mcpManager.getMcpHandlers())r.set(u,d);let a=n.isSkillDispatch?this.schemas.filter(u=>u.name!=="ask_question"&&u.name!=="terminal_font_size"):n.isNonInteractive?this.schemas.filter(u=>u.name!=="ask_question"):this.schemas,l={handlers:r,schemas:[...a,...s,...i?[My]:[]],hookRegistry:$y(n.hookRegistry,this.providerOpts.hookRegistry)},c=Zg(this.providerOpts.mcpManager?Qg(this.providerOpts.permissions,this.providerOpts.mcpManager.getMcpToolWireNames()):this.providerOpts.permissions,(this.providerOpts.customTools??[]).map(u=>u.schema.name));return c!==void 0&&(l.permissions=c),this.providerOpts.subagentExecutor!==void 0&&(l.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(l.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(l.composeExecutor=this.providerOpts.composeExecutor),this.providerOpts.canUseTool!==void 0&&(l.canUseTool=this.providerOpts.canUseTool),n.cwd!==void 0&&(l.cwd=n.cwd),n.readRoots!==void 0&&(l.readRoots=n.readRoots),n.writeRoots!==void 0&&(l.writeRoots=n.writeRoots),n.sessionId!==void 0&&(l.sessionId=n.sessionId),n.parentSessionId!==void 0&&(l.parentSessionId=n.parentSessionId),n.subagentId!==void 0&&(l.subagentId=n.subagentId),n.subagentToolOutputCapBytes!==void 0&&(l.maxOutputBytes=n.subagentToolOutputCapBytes),n.traceWriter!==void 0&&(l.traceWriter=n.traceWriter),this.providerOpts.readOnlyBash===!0&&(l.readOnlyBash=!0),l.allowAll=Yn(t),l.sessionGrantManager=this,new Xt(l)}ensureSharedRoots(t){if(!this._sharedReadRoots){let n=t?[t]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t)}}grantManager=new Zo({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>Yn(this._currentPermissionMode)});addReadRoot(t,n="slash",r){this.grantManager.addReadRoot(t,n,r)}addWriteRoot(t,n="slash",r){this.grantManager.addWriteRoot(t,n,r)}revokeRoot(t,n="slash",r){this.grantManager.revokeRoot(t,n,r)}getGrants(){return this.grantManager.getGrants()}close(){this.memoryStore.close()}async complete(t){let n={model:t.model??"gpt-4o-mini",system:t.system,user:t.user,maxTokens:t.maxTokens??64};t.apiKey!==void 0&&(n.apiKey=t.apiKey);let r=t.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),this._defaultHeaders!==void 0&&(n.defaultHeaders=this._defaultHeaders),t.signal&&(n.signal=t.signal),ub(n)}},Jfe=new zt});function bi(e,t){if(e.has(t))return!0;let n=t.charAt(0).toUpperCase()+t.slice(1);return n!==t&&e.has(n)}function Bn(e){return e.startsWith("mcp__")||e.startsWith("MCP__")?"mcp":bi(Xfe,e)?"read":bi(Qfe,e)?"write":bi(Zfe,e)?"shell":bi(Si,e)?"subagent":bi(Hp,e)?"skill":bi(Wp,e)?"dag":bi(ege,e)?"web":tge.has(e)?"browser":bi(nge,e)?"planning":rge.has(e)?"schedule":"other"}function JA(e){return oge[e]}var Xfe,Qfe,Zfe,Si,Hp,Wp,tt,ege,tge,nge,rge,YA,B1,oge,Qs=y(()=>{"use strict";fh();Xfe=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness"]),Qfe=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","memory_update","procedure_write","terminal_font_size","config_set"]),Zfe=new Set(["Bash","BashOutput","KillBash","bash"]),Si=new Set(["Agent","Task","agent"]),Hp=new Set(["Skill","skill"]),Wp=new Set(["Compose","compose"]),tt=new Set([...Si,...Wp,...Hp]),ege=new Set(["WebFetch","WebSearch","send_telegram","web_scrape"]),tge=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),nge=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),rge=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);YA=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness",...bt],B1=[...YA,"web_scrape","agent"];oge={subagent:"subagent",skill:"skill",dag:"dag"}});function _b(e,t){return`Skill tool not available at nesting depth ${e} (max ${t}). ${wi}`}function U1(e,t){return`Agent tool not available at nesting depth ${e} (max ${t}). ${wi}`}function j1(e,t){return`Compose tool not available at nesting depth ${e} (max ${t}). ${wi}`}var wi,Kp=y(()=>{"use strict";wi="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function W1(e){H1.add(e)}function K1(e){return H1.has(e)}var H1,XA=y(()=>{"use strict";H1=new Set});function G1(e){QA.add(e)}function q1(e){QA.delete(e)}function z1(e){ZA.add(e)}function V1(e){ZA.delete(e)}function Y1(e){for(let t of QA)t(e)}function J1(e){for(let t of ZA)t(e)}var QA,ZA,eC=y(()=>{"use strict";QA=new Set,ZA=new Set});function Ib(e){return ige.has(e)}function X1(e,t=sge){return e.length<=t?e:e.slice(0,t)+"\u2026"}function uc(e){return e.surface!==void 0?{origin:ci(e.surface),actor:ui(e.depth)}:{}}var ige,sge,tC=y(()=>{"use strict";zs();ige=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","
|
|
1072
|
+
`)},S=()=>Bd({cwd:s,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:a.getWorkspace()}),w={...n,systemPrompt:b(S())},k=E=>{s=E,w.systemPrompt=b(S())};return c.onCwdChange=k,N1(w,t.prompt,c)}buildDispatcher(t,n){let r=Iy(t,n.cwd),o=Nd(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[u,d]of o)this.providerOpts.readOnlyMemory===!0&&u!=="memory_search"||r.set(u,d);n.runtimeStateSource&&r.set("get_runtime_state",El(n.runtimeStateSource));for(let u of this.providerOpts.customTools??[])r.has(u.schema.name)||r.set(u.schema.name,u.handler);let i=n.planExitControls;i&&r.set(hn,Oy(i));let s=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[u,d]of this.providerOpts.mcpManager.getMcpHandlers())r.set(u,d);let a=n.isSkillDispatch?this.schemas.filter(u=>u.name!=="ask_question"&&u.name!=="terminal_font_size"):n.isNonInteractive?this.schemas.filter(u=>u.name!=="ask_question"):this.schemas,l={handlers:r,schemas:[...a,...s,...i?[My]:[]],hookRegistry:$y(n.hookRegistry,this.providerOpts.hookRegistry)},c=Zg(this.providerOpts.mcpManager?Qg(this.providerOpts.permissions,this.providerOpts.mcpManager.getMcpToolWireNames()):this.providerOpts.permissions,(this.providerOpts.customTools??[]).map(u=>u.schema.name));return c!==void 0&&(l.permissions=c),this.providerOpts.subagentExecutor!==void 0&&(l.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(l.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(l.composeExecutor=this.providerOpts.composeExecutor),this.providerOpts.canUseTool!==void 0&&(l.canUseTool=this.providerOpts.canUseTool),n.cwd!==void 0&&(l.cwd=n.cwd),n.readRoots!==void 0&&(l.readRoots=n.readRoots),n.writeRoots!==void 0&&(l.writeRoots=n.writeRoots),n.sessionId!==void 0&&(l.sessionId=n.sessionId),n.parentSessionId!==void 0&&(l.parentSessionId=n.parentSessionId),n.subagentId!==void 0&&(l.subagentId=n.subagentId),n.subagentToolOutputCapBytes!==void 0&&(l.maxOutputBytes=n.subagentToolOutputCapBytes),n.traceWriter!==void 0&&(l.traceWriter=n.traceWriter),this.providerOpts.readOnlyBash===!0&&(l.readOnlyBash=!0),l.allowAll=Yn(t),l.sessionGrantManager=this,new Xt(l)}ensureSharedRoots(t){if(!this._sharedReadRoots){let n=t?[t]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),t&&!this._initialResolveBase&&(this._initialResolveBase=t)}}grantManager=new Zo({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>Yn(this._currentPermissionMode)});addReadRoot(t,n="slash",r){this.grantManager.addReadRoot(t,n,r)}addWriteRoot(t,n="slash",r){this.grantManager.addWriteRoot(t,n,r)}revokeRoot(t,n="slash",r){this.grantManager.revokeRoot(t,n,r)}getGrants(){return this.grantManager.getGrants()}close(){this.memoryStore.close()}async complete(t){let n={model:t.model??"gpt-4o-mini",system:t.system,user:t.user,maxTokens:t.maxTokens??64};t.apiKey!==void 0&&(n.apiKey=t.apiKey);let r=t.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),this._defaultHeaders!==void 0&&(n.defaultHeaders=this._defaultHeaders),t.signal&&(n.signal=t.signal),ub(n)}},Jfe=new zt});function bi(e,t){if(e.has(t))return!0;let n=t.charAt(0).toUpperCase()+t.slice(1);return n!==t&&e.has(n)}function Bn(e){return e.startsWith("mcp__")||e.startsWith("MCP__")?"mcp":bi(Xfe,e)?"read":bi(Qfe,e)?"write":bi(Zfe,e)?"shell":bi(Si,e)?"subagent":bi(Hp,e)?"skill":bi(Wp,e)?"dag":bi(ege,e)?"web":tge.has(e)?"browser":bi(nge,e)?"planning":rge.has(e)?"schedule":"other"}function JA(e){return oge[e]}var Xfe,Qfe,Zfe,Si,Hp,Wp,tt,ege,tge,nge,rge,YA,B1,oge,Qs=y(()=>{"use strict";fh();Xfe=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness"]),Qfe=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","memory_update","procedure_write","terminal_font_size","config_set"]),Zfe=new Set(["Bash","BashOutput","KillBash","bash"]),Si=new Set(["Agent","Task","agent"]),Hp=new Set(["Skill","skill"]),Wp=new Set(["Compose","compose"]),tt=new Set([...Si,...Wp,...Hp]),ege=new Set(["WebFetch","WebSearch","send_telegram","web_scrape"]),tge=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),nge=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),rge=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);YA=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness",...bt],B1=[...YA,"web_scrape","agent"];oge={subagent:"subagent",skill:"skill",dag:"dag"}});function _b(e,t){return`Skill tool not available at nesting depth ${e} (max ${t}). ${wi}`}function U1(e,t){return`Agent tool not available at nesting depth ${e} (max ${t}). ${wi}`}function j1(e,t){return`Compose tool not available at nesting depth ${e} (max ${t}). ${wi}`}var wi,Kp=y(()=>{"use strict";wi="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function W1(e){H1.add(e)}function K1(e){return H1.has(e)}var H1,XA=y(()=>{"use strict";H1=new Set});function G1(e){QA.add(e)}function q1(e){QA.delete(e)}function z1(e){ZA.add(e)}function V1(e){ZA.delete(e)}function Y1(e){for(let t of QA)t(e)}function J1(e){for(let t of ZA)t(e)}var QA,ZA,eC=y(()=>{"use strict";QA=new Set,ZA=new Set});function Ib(e){return ige.has(e)}function X1(e,t=sge){return e.length<=t?e:e.slice(0,t)+"\u2026"}function uc(e){return e.surface!==void 0?{origin:ci(e.surface),actor:ui(e.depth)}:{}}var ige,sge,tC=y(()=>{"use strict";zs();ige=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","long-bash-gate","exploration-gate","irreversible-action-gate","safe-destruct","plan-probe"]);sge=240});function Q1(e){let t=[],n="",r=null,o=!1;for(let i of e){if(r!==null){i===r?r=null:n+=i;continue}if(i==='"'||i==="'"){r=i,o=!0;continue}if(/\s/.test(i)){o&&(t.push(n),n="",o=!1);continue}n+=i,o=!0}return o&&t.push(n),t}function vi(e,t){let n=t??"",r;return e.replace(/(\\?)\$(ARGUMENTS?\b|\{(\d+)\})/g,(o,i,s,a)=>{if(i==="\\")return o.slice(1);if(s==="ARGUMENT"||s==="ARGUMENTS")return n;let l=Number(a);return l<1?o:(r??=Q1(n),r[l-1]??o)})}var Pb=y(()=>{"use strict"});function Z1(e,t,n){let r=n&&n.trim().length>0?n.trim():"(none)";return{content:`${`[Skill "${e}" loaded into your current context \u2014 act on it now]
|
|
1073
1073
|
The instructions below are your operating procedure for THIS task. Execute them immediately, in this session, using the tools you already have. This is an instruction set, not reference material: follow it directly \u2014 do not merely summarize or describe it. No sub-agent was forked; you are the one carrying it out.
|
|
1074
1074
|
Arguments: ${r}`}
|
|
1075
1075
|
|
|
@@ -1449,13 +1449,20 @@ A goal phrased as a question \u2014 "why does X keep happening", "how come Y", "
|
|
|
1449
1449
|
|
|
1450
1450
|
These skills fire automatically at specific points in the task lifecycle. Check each condition before the relevant phase begins.
|
|
1451
1451
|
|
|
1452
|
-
- **intent-lock** \u2014 before any multi-step work, scan the request for ambiguous referents ("the text", "her Y"), unverified characterizations ("the meeting is substantive"), identity assumptions (which contact = the user), code-vs-runtime dual referents, or no task statement at all (a bare path, URL, noun phrase, or pasted trace). Emit a one-sentence interpretation lock per finding and proceed; when multiple plausible reads gate an irreversible action, escalate to Asking on an interactive surface or Blocked without acting on a non-interactive surface.
|
|
1453
1452
|
- **ground-state** \u2014 before any non-trivial implementation (multi-file edits, new features, config changes, anything that writes), invoke the \`/ground-state\` skill to run a parallel reconnaissance wave for git state, infrastructure, and memory context. Do not settle for inline \`git status\` / \`get_runtime_state\` \u2014 those are serial and miss the memory/infra dimensions the skill triangulates.
|
|
1454
|
-
- **thesis-lock** \u2014 before drafting first-person analysis or recommendations, lock the thesis to a single sentence for async correction before building on it.
|
|
1455
1453
|
- **premise-gate** \u2014 during research and analysis, check named-entity and status-claim pairs before acting on them.
|
|
1456
1454
|
|
|
1457
1455
|
Routing hints are checks, not ceremonies. Skip when the condition is trivially absent.
|
|
1458
1456
|
|
|
1457
|
+
## Behavioral checks
|
|
1458
|
+
|
|
1459
|
+
These are inline behaviors \u2014 follow them directly, do not invoke a skill.
|
|
1460
|
+
|
|
1461
|
+
- **intent-lock** \u2014 before any multi-step work, scan the request for ambiguous referents ("the text", "her Y"), unverified characterizations ("the meeting is substantive"), identity assumptions (which contact = the user), code-vs-runtime dual referents, or no task statement at all (a bare path, URL, noun phrase, or pasted trace). Emit a one-sentence interpretation lock per finding and proceed; when multiple plausible reads gate an irreversible action, escalate to Asking on an interactive surface or Blocked without acting on a non-interactive surface.
|
|
1462
|
+
- **thesis-lock** \u2014 before drafting first-person analysis or recommendations, lock the thesis to a single sentence for async correction before building on it.
|
|
1463
|
+
- **reground** \u2014 before extrapolating, composing, or synthesizing on top of a previous sub-agent's findings within the same conversation, reread at least one file the sub-agent cited in the main path. Tag every extrapolated claim that extends beyond the reread as [UNVERIFIED] naming what source would ground it. The sub-agent's prose is not a primary source \u2014 the files it cited are.
|
|
1464
|
+
- **exploration-gate** \u2014 when a session's goal is understanding-first (explore, explain, understand, figure out, walk me through) and no deliverable was explicitly named, do not pressure toward commits or file edits at session end. "No commit" is not failure on an exploration session.
|
|
1465
|
+
|
|
1459
1466
|
## Priorities
|
|
1460
1467
|
|
|
1461
1468
|
Ordered. Higher wins on conflict.
|
|
@@ -1865,7 +1872,7 @@ ${E}
|
|
|
1865
1872
|
${T}`})}return{fileBlocks:l,warnings:c}}function z9(e){let t=e.replace(/\s+/g," ").trim();return t.length<=60?t:`${t.slice(0,59)}\u2026`}async function V9(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}}kv();async function Y9(e,t,n,r,o="summary",i,s){let a=SJ(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0),au(process.stdout,Lm(process.cwd(),!0));let l="",c=0,u=!1,d=!1,p=!1,f=!1,g=!1,h,b=!1,S=!1,w={abort:null},k=0,E=3e3,T=[],A=new Map,M=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,_=()=>{let $=r.subagentControl;$?.hasPromotableForeground()&&V9($,R,r.onQueuedUserMessage).then(({jobs:G,flushedText:H,flushedPreview:I})=>{let L=(i??{fn:console.log}).fn;for(let F of G)L(m.dim(` \u2192 subagent backgrounded as ${F.jobId}: ${F.label}`));H!==void 0&&L(m.dim(` \u2192 queued message sent to this turn: ${z9(I??H)}`))}).catch(()=>{})},R=r.getCompositor?r.getCompositor():null,C=()=>new Pu({out:Mu(i),thinkingMode:o,...M?{activeSkillName:M}:{},onCancel:()=>{t.interrupt().catch($=>{Ge()&&console.error(" "+m.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}:{},...R?{compositor:R}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),P=C(),O=async()=>{if(!f){f=!0;try{await P.dispose()}catch{}}},z=async()=>{await P.arm();let $=P.getCompositor();if(i&&$){let G=$;i.fn=H=>G.commitAbove(H),i.suppressSubagentCompletion=!0}r.setActiveCompositor?.($),r.setInterruptNotifier?.(G=>P.setInterrupting(G)),r.rearmStatus?.()};try{R?R.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{b=!0,P.setSoftStopping(!0),t.interrupt().catch(D=>{Ge()&&console.error(" "+m.error("soft-stop session.interrupt() failed:"),D)});let F=r.subagentControl;F?.hasActiveForeground()&&F.cancelActiveForeground().catch(D=>{Ge()&&console.error(" "+m.error("soft-stop cancelActiveForeground() failed:"),D)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{S=!0,t.interrupt().catch(F=>{Ge()&&console.error(" "+m.error("pause-interrupt session.interrupt() failed:"),F)})}),await z(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(_);let{fileBlocks:$,warnings:G}=q9(e.text,{rootDir:process.cwd()});for(let F of G)(i??{fn:console.log}).fn(m.dim(` @-file: ${F}`));if(e.attachments.length>0&&(await t.waitForInitialization(),t.sessionId===void 0))throw new Error("CLI session initialized without a session id");let H=$.length>0||e.attachments.length>0?await G9(e.text,e.attachments,void 0,$,t.sessionId):e.text,I=t.sendMessageStream(H);if(await Jl((F,D)=>{P.process(F,D)},async()=>{for await(let F of I){if(b||S)break;if(F.type==="chunk"&&F.chunk.type==="content"?(l=u?W9(l,F.chunk.content):l+F.chunk.content,u=!1,d=!0):F.type==="message"&&!d&&(l=F.message.content),F.type==="stream_retry"&&(l=l.slice(0,c),u=l.length>0),F.type==="chunk"&&F.chunk.type==="tool_use_detail"){let D=F.chunk,W={toolName:D.toolName,toolUseId:D.toolUseId,input:D.toolInput,...D.toolInputRaw!==void 0&&{inputRaw:D.toolInputRaw}};A.set(D.toolUseId,W),T.push(W)}else if(F.type==="chunk"&&F.chunk.type==="tool_result"){let D=F.chunk;c=l.length,u=!0;let W=A.get(D.toolUseId);if(W&&(W.result=D.content,W.isError=D.isError,A.delete(D.toolUseId)),r.onContextProgress){let ne=Date.now();if(ne-k>=E){k=ne;try{let ee=r.onContextProgress();ee instanceof Promise&&await ee}catch(ee){Ge()&&console.error(" "+m.error("onContextProgress (status refresh) failed:"),ee)}}}}if(F.type==="paused"){if(r.setPausedState?.(!0),await O(),R&&F.autoResume===!0){let D=new AbortController;w.abort=D;let W=F.resetsAt?F.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,ne=W?`Keep waiting \u2014 auto-resumes at ${W}`:"Keep waiting \u2014 auto-resume in progress",ee="Switch model / provider (type /model after)",X="Stop waiting",ae=[m.warning(" \u23F3 Usage limit reached.")+(W?m.dim(` Auto-resumes at ${W}.`):""),m.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];Wn(R,{header:ae,options:[ne,ee,X],signal:D.signal,initialIndex:0}).then(V=>{if(w.abort=null,!V)return;let Pe=V[0];Pe===void 0||Pe===ne||(S=!0,Pe===ee&&(i??{fn:console.log}).fn(m.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(Re=>{Ge()&&console.error(" "+m.error("picker pause-interrupt session.interrupt() failed:"),Re)}))}).catch(V=>{Ge()&&console.error(" "+m.error("picker promise rejected:"),V)})}else(i??{fn:console.log}).fn(qD({reason:F.reason,...F.resetsAt!==void 0?{resetsAt:F.resetsAt}:{},...F.accountId!==void 0?{accountId:F.accountId}:{},...F.autoResume!==void 0?{autoResume:F.autoResume}:{}}));continue}if(F.type==="resumed"){r.setPausedState?.(!1),w.abort?.abort(),w.abort=null;let D=F.hotSwapped&&F.accountId?`\u25B6 Resumed on ${F.accountId}`:"\u25B6 Resumed";l="",c=0,u=!1,d=!1,T.length=0,A.clear(),g=!1,h=void 0,p=!1,P=C(),f=!1,await z(),(i??{fn:console.log}).fn(m.success(D));continue}if(F.type==="error"){await O(),ml(sl(F.error)),p=!0;continue}P.process(F),F.type==="done"&&(g=!0,h=F.metadata)}}),await O(),b){let F=i?i.fn:console.log,D=R?R.getPendingCount():0,W=D>0?` \xB7 ${D} queued`:"";F(m.warning(`\u23F8 Stopped${W} \u2014 work so far kept.`)+m.dim(" Send a message to continue.")),F("")}if(S){let F=i?i.fn:console.log;F(m.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),F("")}if(g&&!b&&!S){fa(n,a,l,h,T),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),su(process.stdout),MY(process.stdout,"afk: turn complete");let F=W=>{i?i.fn(W):console.log(W)},D=iT(l);if(D){F(K9(D)),F("");let W=T6(T);if(r.onTerminalState)try{r.onTerminalState(D,{doneHasCorroboratingEvidence:W})}catch{}if(n.permissionMode==="autonomous"){let ne=D.kind==="done"&&up().verifyDone===!0&&!W;x6(D,void 0,{unverified:ne})}}if(R0e(h,n,F),r.onAfterTurn){let W=r.onAfterTurn();W instanceof Promise&&await W.catch(()=>{})}}}catch($){await O(),p||ml(sl($))}finally{await O(),au(process.stdout,Lm(process.cwd(),!1)),i&&(i.fn=i.idleFn,i.suppressSubagentCompletion=!1),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),w.abort?.abort(),w.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function x0e(e,t){let n=Math.round(e*100),r=fe(t);if(e>=1){let o=Math.round((e-1)*t);return{tier:"over",text:` context OVER ${Math.round(t/1e3)}k tok by ~${fe(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 R0e(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(_e(e.durationMs)),e.totalCostUsd!==void 0&&r.push(kt(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),i=Number(e.usage?.output_tokens??0);o+i>0&&r.push(fe(o+i)+" tok"),r.length>0&&n(m.dim(" \u25E6 "+r.join(" \xB7 ")));let s=XP(t),a=it(t.model),l=x0e(s,a);if(l.text!==null){let u=l.tier==="over"||l.tier==="near"?m.error:l.tier==="caution"?m.warning:m.dim;n(u(l.text))}let c=H9(Xv(Gy()),new Date,{autoResume:vN()});if(c.text!==null){let u=c.tier==="over"||c.tier==="near"?m.error:c.tier==="caution"?m.warning:m.dim;n(u(c.text))}n("")}Ni();var A0e=5e3,C0e=3,_0e="[auto-resume] The background task above has finished. Continue the work it was dispatched for.";async function I0e(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function J9(e,t,n,r,o,i,s,a){let{contextPane:l,loopStageBar:c,mascotBar:u,verdictLedger:d,shellPassthrough:p,bgResultNotifier:f}=s,g=null,h=[];e.session.current.waitForInitialization().then(async _=>{Ge()&&(g=hk(_)),await pf(e.session.current),Ge()&&(h=qP())}).catch(()=>{});let b=e.initialInput!==void 0?{text:e.initialInput,attachments:[]}:void 0,S,w=!1,k=!1,E,T,A,M=0;for(f.onInjectable=()=>{M>=C0e||!o.isAwaitingInput()||!o.bufferIsEmpty()||(M++,su(process.stdout),b={text:_0e,attachments:[]},o.abortPendingRead())};;){if(g&&(e.replRenderer.writeLine(g),e.replRenderer.writeLine(""),g=null),h.length>0){for(let I of h)e.replRenderer.writeLine(I);e.replRenderer.writeLine(""),h=[]}let _=p.drainNotifications();for(let{job:I,result:L}of _){let F=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}`,W=Math.max(0,Math.round(L.durationMs/100)/10);e.replRenderer.writeLine(m.dim(` ${F} [${I.id}] ${D} \xB7 ${W}s \xB7 `)+I.command)}let R=f.drainNotifications();for(let{job:I}of R){let L=I.status==="completed"?"\u2713":I.status==="failed"?"\u2717":"\u2298",F=I.endedAt!==void 0?Math.max(0,Math.round((I.endedAt-I.startedAt)/100)/10):0,D=se(I.label,60);e.replRenderer.writeLine(m.dim(` ${L} [${I.jobId}] subagent ${I.status} \xB7 ${F}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,O;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=Uu(e.stats.permissionMode),F=Sa({buffer:I.text,promptText:L,isTTY:!!process.stdout.isTTY,attachmentSummary:Su([...I.attachments])});e.replRenderer.writeLine(F),P=I.text.trim(),O=I.attachments}else{let I=S;S=void 0;let L=await o.readLine({promptFn:()=>Uu(e.stats.permissionMode),...I!==void 0?{initialBuffer:I}:{},primePromptSuggestion:!0,onSigint:r,onShiftTab:()=>{eT(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});P=L.text.trim(),O=L.attachments}if(!P&&O.length===0)continue;if(P.startsWith("!")){let I=/^(0|false|off|no)$/i.test(v.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!I&&(w||(w=!0,e.replRenderer.writeLine(m.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await p.dispatch(P))){e.statusLine.rearm();continue}}let z=!1;if(P.startsWith("/")){let I=await $Y(P,e.slashCtx,O);if(I.handled){if(I.result==="exit"){await e.resolveWorktreeDisposition?.(!0),e.rl.close();return}if((P==="/clear"||P.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),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:O??[]},e.statusLine.rearm();continue}if(I.result!==null&&typeof I.result=="object"&&"kind"in I.result&&I.result.kind==="prefill"){S=I.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}z=!0}a.push(P),await I0e(e,P);let $=P;if(z){let I=CI(P);if(I){let L=I.name.replace(/^\//,"").split(":").pop()??"";if(L&&jP(L)){let F={skillName:L,rawArgs:I.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},D=e.session.current.sessionId,W=Ia(D),ne=Date.now();U(`[afk trace] preflight.start commandName=${L}`);let ee=!1,X=await _a(F,{cwd:e.stats.cwd??process.cwd(),artifactDir:W},ae=>{Ge()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${L}) failed: `)+(ae instanceof Error?ae.message:String(ae)))});ee=X!==null,U(`[afk trace] preflight.end commandName=${L} durationMs=${Date.now()-ne} success=${ee}`),$=KP(X?.manifestBlock,P)}}}let G=p.drainInjections();G.length>0&&($=G+$);let H=f.drainInjections();if(H.length>0&&($=H+$),E!==void 0&&($=E+`
|
|
1866
1873
|
|
|
1867
1874
|
`+$,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(m.warning("\u2298 Turn blocked by hook")+(I.reason?m.dim(`: ${Oe(I.reason)}`):"")),e.statusLine.rearm();continue}if(I instanceof Rr){e.replRenderer.writeLine(m.warning("\u2298 Turn blocked by hook")+m.dim(`: handler timed out after ${I.timeoutMs}ms`)),e.statusLine.rearm();continue}throw I}if(T=void 0,A=void 0,await Y9({text:$,attachments:O},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{Li(e.stats)}catch(F){k||(k=!0,e.replRenderer.writeLine(m.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(F instanceof Error?F.message:String(F))))}},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,A=L?.doneHasCorroboratingEvidence},setActiveCompositor:I=>{n.activeCompositor=I},setInterruptNotifier:I=>{n.notifyInterrupting=I},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:I=>o.setBackgroundHandler(I),setSoftStopHandler:i,setPausedState:I=>o.setPausedState(I),setPauseInterruptHandler:I=>o.setPauseInterruptHandler(I),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(mr(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(Uu(e.stats.permissionMode))),e.hookRegistry)try{let I=await e.hookRegistry.dispatch({event:"Stop",sessionId:e.stats.sessionId,...T!==void 0?{terminalState:T}:{},...A!==void 0?{doneHasCorroboratingEvidence:A}:{}},void 0,A0e);I.injectContext&&I.injectContext.trim().length>0&&(E=I.injectContext)}catch(I){if(I instanceof xt)throw I;I instanceof Rr?(U("[stop hook] handler timed out"),e.completionWriter.fn(m.dim(" [stop hook] timed out"))):I instanceof Ae?e.completionWriter.fn(m.dim(` [stop hook] blocked: ${Oe(I.reason??"no reason given")}`)):U("[stop hook] unexpected error: "+String(I))}}}function P0e(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 X9(e,t,n,r){let o=await y9(),i=new Zk({rl:e.rl,history:o,statusLine:e.statusLine}),s=P0e(v.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await E9(e,i,n,t,r,s,{getLoopStageBar:()=>a?.loopStageBar,getMascotBar:()=>a?.mascotBar});a=U9(e,n),await J9(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)}}np();Ul();import{execFile as M0e}from"node:child_process";import{dirname as O0e,isAbsolute as D0e,resolve as $0e}from"node:path";import{promisify as F0e}from"node:util";var Q9=F0e(M0e),L0e=3e3,N0e=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function B0e(){let t=(await Q9("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=D0e(t)?t:$0e(process.cwd(),t);return O0e(n)}async function Z9(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await B0e()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),L0e)});try{let o=$n({execFile:Q9,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=>N0e.has(c.verdict)&&s.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}Bg();np();import{promises as U0e}from"node:fs";import{dirname as j0e,join as nQ}from"node:path";import{randomBytes as H0e}from"node:crypto";var W0e=["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(`
|
|
1868
|
-
`),eQ=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,v0=30,K0e=1024,G0e=8e3,q0e="haiku";async function z0e(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=X0e(n,K0e),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??G0e),s=t.signal?Q0e([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await bl({token:t.token,model:t.model??q0e,system:W0e,user:r,maxTokens:32,signal:s})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=V0e(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=j0e(t.worktreePath);return await Y0e(l,c)}function V0e(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(eQ.test(t)&&t.length<=v0)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>v0)break;o=s}return eQ.test(o)?o:null}async function Y0e(e,t){if(!await J0e(nQ(t,e)))return e;let n=H0e(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,v0-5)}-${n}`}async function J0e(e){try{return await U0e.access(e),!0}catch{return!1}}function X0e(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 Q0e(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 rQ(e){let t,n,r=nQ(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await z0e(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=`${Lh(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return tQ(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 tQ(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 tQ(e,t){e&&e.setCwd(t),Z0e(t)}function Z0e(e){try{process.chdir(e)}catch{}}ut();It();ol();Yr();K();import{spawn as iQ}from"child_process";import{existsSync as sQ,mkdirSync as oOe,readFileSync as aQ,unlinkSync as oQ,writeFileSync as lQ}from"fs";import{get as iOe}from"https";import{join as cQ}from"path";import{readFileSync as eOe}from"fs";import{dirname as tOe,join as nOe}from"path";import{fileURLToPath as rOe}from"url";function Qr(){try{return"5.119.
|
|
1875
|
+
`),eQ=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,v0=30,K0e=1024,G0e=8e3,q0e="haiku";async function z0e(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=X0e(n,K0e),o=new AbortController,i=setTimeout(()=>o.abort(),t.timeoutMs??G0e),s=t.signal?Q0e([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,s):a=await bl({token:t.token,model:t.model??q0e,system:W0e,user:r,maxTokens:32,signal:s})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(i)}let l=V0e(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=j0e(t.worktreePath);return await Y0e(l,c)}function V0e(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(eQ.test(t)&&t.length<=v0)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>v0)break;o=s}return eQ.test(o)?o:null}async function Y0e(e,t){if(!await J0e(nQ(t,e)))return e;let n=H0e(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,v0-5)}-${n}`}async function J0e(e){try{return await U0e.access(e),!0}catch{return!1}}function X0e(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 Q0e(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 rQ(e){let t,n,r=nQ(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await z0e(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=`${Lh(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return tQ(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 tQ(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 tQ(e,t){e&&e.setCwd(t),Z0e(t)}function Z0e(e){try{process.chdir(e)}catch{}}ut();It();ol();Yr();K();import{spawn as iQ}from"child_process";import{existsSync as sQ,mkdirSync as oOe,readFileSync as aQ,unlinkSync as oQ,writeFileSync as lQ}from"fs";import{get as iOe}from"https";import{join as cQ}from"path";import{readFileSync as eOe}from"fs";import{dirname as tOe,join as nOe}from"path";import{fileURLToPath as rOe}from"url";function Qr(){try{return"5.119.3"}catch{}try{let e=tOe(rOe(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(eOe(nOe(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}j();B();var sOe=64*1024,aOe=10800*1e3,lOe=800,cOe=3600*1e3,uOe="update-check.json",dOe="pending-update.json";function k0(){return cQ(tl(),uOe)}function Cf(){return cQ(tl(),dOe)}function T0(){let e=tl();sQ(e)||oOe(e,{recursive:!0})}function uQ(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 dQ(){try{let e=aQ(k0(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function pQ(){try{T0();let e=`
|
|
1869
1876
|
const https = require('https');
|
|
1870
1877
|
const fs = require('fs');
|
|
1871
1878
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var T_=Object.defineProperty;var ke=(t,e)=>()=>(t&&(e=t(t=0)),e);var wp=(t,e)=>{for(var n in e)T_(t,n,{get:e[n],enumerable:!0})};function yr(t){return br.find(e=>e.name===t)}function os(t){return process.env[t]!==void 0}var Sp=ke(()=>{"use strict";C()});var br,h,C=ke(()=>{"use strict";Sp();br=[{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 | max | 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:"XAI_API_KEY",description:"xAI API key for the xai provider (Grok models) in API-key mode. Metered; distinct from SuperGrok / SuperGrok Heavy / X Premium+ OAuth.",type:"string",required:!1,category:"auth",secret:!0},{name:"AFK_XAI_BASE_URL",description:"Base URL for xAI API-key mode. Default https://api.x.ai/v1. The OpenAI SDK appends /chat/completions.",type:"string",required:!1,example:"https://api.x.ai/v1",category:"model"},{name:"AFK_XAI_OAUTH_BASE_URL",description:"Base URL for xAI SuperGrok / SuperGrok Heavy / X Premium+ OAuth inference. Default https://cli-chat-proxy.grok.com/v1 (subscription path). Some accounts work on https://api.x.ai/v1 with OAuth \u2014 override if needed. Distinct from AFK_XAI_BASE_URL (API-key mode).",type:"string",required:!1,example:"https://cli-chat-proxy.grok.com/v1",category:"model"},{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 | xai | xai-oauth). Overrides the model-name heuristic. Same surface as the --provider CLI flag; CLI flag wins when both are set.",type:"string",required:!1,example:"openai-compatible",category:"model"},{name:"EXA_API_KEY",description:"Exa (exa.ai) search API key, enabling web_scrape search mode. Free tier (20k requests/month) available at https://exa.ai. When unset, search mode returns an actionable error; markdown and raw modes are unaffected.",type:"string",required:!1,category:"auth",secret:!0},{name:"TELEGRAM_BOT_TOKEN",description:"Telegram bot token from @BotFather. Required to run the Telegram bot surface.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_BOT_TOKEN",description:"Alternative env var name for the Telegram bot token, accepted by the setup wizard.",type:"string",required:!1,category:"telegram",secret:!0},{name:"AFK_TELEGRAM_ALLOWED_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs allowed to interact with the bot. Required when the bot is running.",type:"string",required:!1,example:"123456789,987654321",category:"telegram"},{name:"AFK_TELEGRAM_TAG_ONLY_CHAT_IDS",description:"Comma-separated list of Telegram chat IDs where the bot answers only when addressed (a reply to the bot, an @mention of the bot, or a text_mention resolving to the bot). Slash-commands are unaffected; chats not listed behave as usual. The afk.config.json telegram.tagOnlyChats block takes precedence. Requires Telegram privacy mode OFF (BotFather /setprivacy Disable) for non-addressed group messages to reach the bot.",type:"string",required:!1,example:"-100987654321,123456789",category:"telegram"},{name:"AFK_TELEGRAM_PRIMARY_CHAT_ID",description:"Default chat ID for outbound notifications (primary-mode routing). When unset, notifications go to the first private/DM chat in AFK_TELEGRAM_ALLOWED_CHAT_IDS. The afk.config.json telegram.notify block takes precedence.",type:"string",required:!1,example:"123456789",category:"telegram"},{name:"AFK_TELEGRAM_NOTIFY_MODE",description:"Outbound notification fan-out: primary (default \u2014 one chat), broadcast (every allowed chat), or custom (afk.config.json telegram.notify.targets). The afk.config.json telegram.notify.mode takes precedence.",type:"string",required:!1,example:"broadcast",category:"telegram"},{name:"TELEGRAM_DATA_DIR",description:"Override the directory where Telegram bot state is stored. Defaults to ~/.afk/state/telegram/.",type:"string",required:!1,category:"telegram"},{name:"TELEGRAM_VERBOSE",description:"Set to a truthy value ('1'/'true'/'yes'/'on', case-insensitive) to log per-message details from the Telegram bot \u2014 chat IDs, message text, latency.",type:"boolean",required:!1,example:"true",category:"telegram"},{name:"TMUX",description:"OS-level tmux session identifier. Set automatically by tmux to the socket path and session info (e.g. /tmp/tmux-501/default,12345,0) inside any tmux pane. Not set by AFK. Read by configureColor() to detect a tmux environment; for truecolor support on Node \u2264 24, set FORCE_COLOR=3 in your shell or ~/.afk/config/afk.env.",type:"string",required:!1,example:"/tmp/tmux-501/default,12345,0",category:"process"},{name:"AFK_TELEGRAM_TRACE",description:"Set to 1 to dump raw bridge traffic between the agent and the Telegram bot \u2014 debugging only.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_TELEGRAM_CWD",description:"Override the working directory used by the Telegram bot when spawning agent sessions.",type:"string",required:!1,category:"telegram"},{name:"AFK_HOME",description:"Override the AFK home directory. Default: ~/.afk/.",type:"string",required:!1,default:"~/.afk",example:"/opt/afk",category:"paths"},{name:"AFK_STATE_DIR",description:"Override the entire AFK state tier (sessions/, todos/, transcripts/, memory/, daemon/, etc.), not just one subdirectory. Must be an absolute path (not /). Default: $AFK_HOME/state/.",type:"string",required:!1,category:"paths"},{name:"AFK_FRAMEWORK_DIR",description:"Override the AFK agent-framework directory used for telemetry and briefs. Default: $AFK_HOME/agent-framework/.",type:"string",required:!1,category:"paths"},{name:"AFK_COMPANION_PRIMER",description:'Opt-in: absolute path to a single companion-primer file. When set, its content is bounded (capped, fenced as <companion-primer>) and appended to the system prompt at session start for top-level sessions (chat/REPL/telegram/daemon), as lower-authority "reflections, not facts" context. Unset (default) = no-op. Only the one named file is ever read \u2014 never a directory or repo walk.',type:"string",required:!1,example:"/Users/me/Projects/afk-companion/PRIMER.md",category:"paths"},{name:"HOME",description:"Standard Unix home directory. Used as the fallback when AFK_HOME is unset.",type:"string",required:!1,category:"process"},{name:"PATH",description:"System PATH. Read for executable resolution (git, gh, etc.) in tool handlers.",type:"string",required:!1,category:"process"},{name:"AFK_DAEMON_CWD",description:"Working directory used by the daemon process for spawned agent sessions.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK",description:"Default task description for the daemon. Falls back to afk.config.json daemon.task.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_TASK_ID",description:"Task identifier the daemon uses to scope its state directory and telemetry.",type:"string",required:!1,category:"daemon"},{name:"AFK_DAEMON_HOST",description:"Bind address for the daemon control HTTP surface. Defaults to 127.0.0.1 (loopback only). The control surface is unauthenticated, so bind a non-loopback address such as 0.0.0.0 only on a trusted or firewalled network. Overridden by the --host flag.",type:"string",required:!1,category:"daemon"},{name:"AFK_SESSIONSTART_COOLDOWN_MS",description:"Cooldown in milliseconds between SessionStart trigger fires in the daemon. Prevents thundering-herd on rapid restarts.",type:"number",required:!1,category:"daemon"},{name:"AFK_WEB_PORT",description:"Port for the `afk web` browser surface. Defaults to 4141; falls back to an ephemeral port when taken. Overridden by --port.",type:"number",required:!1,example:"4141",category:"daemon"},{name:"AFK_WEB_HOST",description:"Bind address for the `afk web` browser surface. Defaults to 127.0.0.1. Unlike the daemon control surface, a non-loopback bind is REFUSED unless AFK_WEB_TOKEN (or --token) is also set, because this surface can submit prompts and approve tool use. Overridden by --host.",type:"string",required:!1,example:"127.0.0.1",category:"daemon"},{name:"AFK_WEB_TOKEN",description:"Bearer token for the `afk web` surface. When unset, a random per-run token is minted and printed in the startup URL. Setting this explicitly is also what permits a non-loopback bind.",type:"string",required:!1,category:"daemon",secret:!0},{name:"AFK_WORKTREE_AUTONAME",description:"Auto-rename worktree branches based on the first user message in interactive mode. 1 = on (default), 0 = off.",type:"boolean",required:!1,default:"1",example:"0",category:"worktree"},{name:"AFK_WORKTREE_BRANCH_PREFIX",description:"Branch-name prefix for AFK-managed worktrees. Default afk/. Set to empty string to drop the prefix.",type:"string",required:!1,default:"afk/",example:"wt/",category:"worktree"},{name:"AFK_WORKTREE_BASE",description:"Override the base git ref for worktrees created with --worktree. By default AFK bases worktrees on the remote's default branch (e.g. origin/main), fetched fresh. Set this to pin a different ref, or to HEAD to base on the local checkout. Overridden per-session by --worktree-base.",type:"string",required:!1,example:"origin/main",category:"worktree"},{name:"AFK_WORKTREE_ON_EXIT",description:"Clean-worktree quit policy for interactive --worktree sessions: ask, keep, or remove.",type:"string",required:!1,example:"ask",category:"worktree"},{name:"AFK_WORKTREE_BOOT_PRUNE",description:"When set, the daemon prunes stale worktrees at boot in addition to the cron-driven sweep.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_PRUNE_DISABLE",description:"Disable the worktree prune job entirely. Useful for long-running tests.",type:"boolean",required:!1,category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_CLEAN",description:"Maximum age (in days) before a clean worktree is auto-pruned. Default 14.",type:"number",required:!1,default:"14",category:"worktree"},{name:"AFK_WORKTREE_MAX_AGE_DIRTY",description:"Maximum age (in days) before a dirty worktree is auto-pruned. Default 30.",type:"number",required:!1,default:"30",category:"worktree"},{name:"AFK_WORKTREE_SWEEP_ROOT",description:"Override the root directory under which AFK worktrees are tracked for pruning.",type:"string",required:!1,category:"worktree"},{name:"AFK_ALLOW_PROJECT_MCP",description:"Opt-in to loading + spawning MCP servers declared in <cwd>/.mcp.json. Fail-closed: when unset (or 0), project-local servers are NOT spawned; set to a truthy value (1/true/yes/on) to load them. A project-local .mcp.json spawns arbitrary commands on session start, so it is off by default to prevent code execution when entering an untrusted repo (issue #571). Skipped servers are listed in a startup warning with the opt-in instruction.",type:"boolean",required:!1,example:"1",category:"mcp"},{name:"AFK_AUTO_ROUTING",description:"Auto-route bare slash inputs to matching skills. Applies to interactive, chat, telegram, and daemon surfaces.",type:"boolean",required:!1,example:"true",category:"routing"},{name:"AFK_INTERNAL",description:'Tier gate. Set to exactly `1` to unlock \u2014 only the literal string "1" unlocks (other truthy values like "true"/"yes" leave the tier locked). When unlocked, skills tagged `audience: \'internal\'` (e.g. /audit-fit, harvest/distill plugins) become visible at end-user surfaces (slash-command list, --help, tab-complete, system-prompt skill manifest). Default unset = public tier \u2014 internal skills are hidden. Not an access-control boundary; it gates surfacing, not the underlying registry.',type:"boolean",required:!1,example:"1",category:"routing"},{name:"AFK_SHELL_PASSTHROUGH",description:"Enable the interactive REPL `!cmd` / `!&cmd` shell-passthrough feature. On by default. Set to 0, false, off, or no (case-insensitive) to disable, so inputs beginning with ! are sent to the model as literal text instead of being executed as shell commands. Equivalent to the --no-shell-passthrough flag.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BG_AUTO_DELIVER",description:"Auto-deliver background subagent results into the model context on the next user turn (interactive REPL). On by default. Set to 0, false, off, or no (case-insensitive) to disable, restoring the manual /bgsub:join retrieval flow.",type:"boolean",required:!1,default:"1",example:"0",category:"misc"},{name:"AFK_BANNER_PLAIN",description:"Suppress the ANSI-colored banner at REPL startup. Useful for non-TTY captures and CI logs.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_PLAIN_OUTPUT",description:"Force the interactive REPL to fully behave like a non-TTY surface for rendering purposes, even when stdout/stdin ARE a TTY: append-only plain-stdout output instead of the TerminalCompositor live overlay (both the persistent between-turn compositor AND the per-turn StreamRenderer overlay), AND the input surface downgrades to the simple non-TTY line reader instead of the fancy compositor-backed input box. Same code path already used for non-TTY surfaces (pipes, CI). Full opt-out escape hatch for tmux/SSH/multiplexer sessions where cursor-up redraws and DECSTBM scroll regions misbehave \u2014 trades the live overlay and fancy input UX for reliability. Opt-in \u2014 default TTY behavior (live overlay + fancy input) is unchanged unless this var is set. Truthy values: 1, true (case-insensitive).",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SPINNER_TIPS",description:"Show rotating tips in the loading spinner during long calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_GOBLIN_SPINNER",description:"Goblin-themed working spinner (olive frames + goblin verbs) while the agent runs tools. 1 = on (default), 0 = classic dim spinner.",type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_GOBLIN_MASCOT",description:"Reacting goblin mini-sprite in the reserved footer band while the agent runs tools (3 rows, animated). 1 = on, unset/0 = off (default). Claims terminal rows, so it is opt-in.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_TERM_TITLE",description:'Set the terminal/tab title (OSC 2) to reflect afk state \u2014 "afk \u2014 <cwd> \xB7 running" during a turn, "afk \u2014 <cwd>" when idle, cleared on exit. 1 = on (default when stdout is a TTY), 0 = leave the title alone. TTY-only.',type:"boolean",required:!1,example:"0",category:"misc"},{name:"AFK_NOTIFY",description:"Emit a desktop completion notification (OSC 9) on turn completion, for terminals that map OSC 9 to system notifications (iTerm2, kitty, WezTerm). Opt-in and off by default (intrusive). 1 = on. TTY-only.",type:"boolean",required:!1,example:"1",category:"misc"},{name:"AFK_SHOW_DIFFS",description:"Show inline diffs in the tool-lane output for edit/write tool calls. 1 = on, 0 = off.",type:"boolean",required:!1,category:"misc"},{name:"AFK_SKILL_STREAM_VERBOSE",description:"Verbose streaming output when a skill is dispatched. Logs sub-agent setup, intermediate events, and final result.",type:"boolean",required:!1,category:"debug"},{name:"FORCE_COLOR",description:"Standard Node convention. Force-enable ANSI color output even when stdout is not a TTY.",type:"string",required:!1,example:"1",category:"process"},{name:"NO_COLOR",description:"Standard convention (https://no-color.org). When set to any non-empty value, disables ANSI color output.",type:"string",required:!1,example:"1",category:"process"},{name:"AFK_THEME",description:"TUI color palette for the interactive REPL and all CLI rendering: dark | light | umber | auto. Display-only \u2014 swaps the semantic color palette, never behavior (cost/latency unaffected). auto detects from COLORFGBG and falls back to dark; umber matches the Umber terminal, is dark-only, and is never chosen by auto. Overridden per-launch by --theme and mutable mid-session via /theme. Precedence: --theme flag > this env > config theme > auto-detect > dark. Invalid values are ignored (dark).",type:"string",required:!1,default:"dark",example:"light",category:"misc"},{name:"AFK_TEXT_MEASURE",description:"Maximum line length (columns) for unbordered streamed text in the interactive REPL: assistant prose, thinking blocks, tool-lane text, and subagent text. Display-only \u2014 affects wrapping, never behavior. Bordered elements (cards, error boxes) already cap at 100; this applies the same ceiling to the unbordered surfaces, which previously scaled to the full terminal width. Accepts a positive integer (minimum 20), or full | off | none | 0 to disable capping and restore full-width wrapping. Unparseable or below-minimum values fall back to the default. No-op on terminals at or below the measure, so narrow terminals are unaffected.",type:"string",required:!1,default:"100",example:"full",category:"misc"},{name:"COLORFGBG",description:'Terminal-set "foreground;background" color hint (e.g. "15;0"), read only for AFK_THEME=auto detection. The trailing field is the background color index; >= 7 is treated as a light background, otherwise dark. Not set by AFK \u2014 emitted by some terminals (rxvt, Konsole, iTerm2). Absent or unparseable => dark.',type:"string",required:!1,example:"15;0",category:"process"},{name:"COLORTERM",description:"OS-level terminal color-depth hint. Accepted values: truecolor or 24bit (24-bit color), 256color (256-color). Set by the outer terminal emulator, not by AFK. Read by chalk's supports-color to set its initial color level; also read by configureColor() to recommend FORCE_COLOR=3 for tmux truecolor users on Node \u2264 24.",type:"string",required:!1,example:"truecolor",category:"process"},{name:"AFK_DEBUG",description:"Enable verbose debug logging across the codebase. Accepts 1 to enable.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_DEBUG_CLIPBOARD",description:"Debug bracketed-paste and image-paste handling in the interactive REPL.",type:"boolean",required:!1,category:"debug"},{name:"AFK_DEBUG_COMPOSITOR",description:"Gate compositor phase-boundary traces to stderr; any truthy value enables.",type:"boolean",required:!1,category:"debug"},{name:"AFK_TRACE_DISABLED",description:"Disable the agent trace subsystem entirely. Set to 1 to skip trace file writes.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_RETENTION_DISABLE",description:"Disable the witness-tree retention sweep entirely, so no session directory is ever evicted.",type:"boolean",required:!1,example:"1",category:"debug"},{name:"AFK_WITNESS_MAX_AGE_DAYS",description:"Evict a witness session directory once its newest content is older than this many days. Default 30.",type:"number",required:!1,default:"30",category:"debug"},{name:"AFK_WITNESS_MAX_BYTES",description:"Aggregate byte cap for the witness tree; oldest session directories are evicted first once exceeded. Default 2147483648 (2 GiB).",type:"number",required:!1,default:"2147483648",category:"debug"},{name:"AFK_WAVE_MANIFEST_DISABLED",description:"Disable the wave manifest system entirely. When set to 1, no manifest is written for parallel subagent waves, and no resumption offer is made at session start.",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{name:"AFK_WAVE_MANIFEST_TTL_HOURS",description:"Time-to-live for wave manifests in hours. Manifests older than this are deleted on reconciliation and by the witness sweep. Default 48 (two days).",type:"number",required:!1,default:"48",example:"24",category:"misc"},{name:"AFK_WAVE_RESUME_UNATTENDED",description:"When set to 1, surface wave resumption offers even on non-interactive surfaces (daemon, one-shot chat). By default, offers are only made on interactive surfaces (REPL, Telegram).",type:"boolean",required:!1,default:"0",example:"1",category:"misc"},{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_RATE_LIMIT_ADMISSION_DISABLED",description:"Bypass the process-wide rate-limit admission gate (issue #941). Set to 1 to skip pre-request capacity checks. Default 0 (gate active). OAuth subscription accounts already pass through automatically when no per-minute headers are returned.",type:"boolean",required:!1,default:"0",example:"1",category:"model"},{name:"AFK_RATE_LIMIT_STAGGER_MAX_MS",description:"Jitter ceiling (ms) for the rate-limit admission bucket: each waiter at a window boundary wakes at reset + random(0..ceiling) to avoid re-storming the API. Default 500. Set to 0 in tests for deterministic timing.",type:"number",required:!1,default:"500",example:"0",category:"model"},{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"}],h={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 XAI_API_KEY(){return process.env.XAI_API_KEY},get AFK_XAI_BASE_URL(){return process.env.AFK_XAI_BASE_URL},get AFK_XAI_OAUTH_BASE_URL(){return process.env.AFK_XAI_OAUTH_BASE_URL},get AFK_LOCAL_API_KEY(){return process.env.AFK_LOCAL_API_KEY},get AFK_LOCAL_BASE_URL(){return process.env.AFK_LOCAL_BASE_URL},get AFK_OPENAI_BASE_URL(){return process.env.AFK_OPENAI_BASE_URL},get AFK_OPENAI_USE_RESPONSES(){return process.env.AFK_OPENAI_USE_RESPONSES},get AFK_OPENAI_CHATGPT_OAUTH(){return process.env.AFK_OPENAI_CHATGPT_OAUTH},get AFK_PROVIDER(){return process.env.AFK_PROVIDER},get EXA_API_KEY(){return process.env.EXA_API_KEY},get TELEGRAM_BOT_TOKEN(){return process.env.TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_BOT_TOKEN(){return process.env.AFK_TELEGRAM_BOT_TOKEN},get AFK_TELEGRAM_ALLOWED_CHAT_IDS(){return process.env.AFK_TELEGRAM_ALLOWED_CHAT_IDS},get AFK_TELEGRAM_TAG_ONLY_CHAT_IDS(){return process.env.AFK_TELEGRAM_TAG_ONLY_CHAT_IDS},get AFK_TELEGRAM_PRIMARY_CHAT_ID(){return process.env.AFK_TELEGRAM_PRIMARY_CHAT_ID},get AFK_TELEGRAM_NOTIFY_MODE(){return process.env.AFK_TELEGRAM_NOTIFY_MODE},get TELEGRAM_DATA_DIR(){return process.env.TELEGRAM_DATA_DIR},get TELEGRAM_VERBOSE(){return process.env.TELEGRAM_VERBOSE},get TMUX(){return process.env.TMUX},get AFK_TELEGRAM_TRACE(){return process.env.AFK_TELEGRAM_TRACE},get AFK_TELEGRAM_CWD(){return process.env.AFK_TELEGRAM_CWD},get AFK_HOME(){return process.env.AFK_HOME},get AFK_STATE_DIR(){return process.env.AFK_STATE_DIR},get AFK_FRAMEWORK_DIR(){return process.env.AFK_FRAMEWORK_DIR},get HOME(){return process.env.HOME},get PATH(){return process.env.PATH},get AFK_DAEMON_CWD(){return process.env.AFK_DAEMON_CWD},get AFK_DAEMON_TASK(){return process.env.AFK_DAEMON_TASK},get AFK_DAEMON_TASK_ID(){return process.env.AFK_DAEMON_TASK_ID},get AFK_DAEMON_HOST(){return process.env.AFK_DAEMON_HOST},get AFK_SESSIONSTART_COOLDOWN_MS(){return process.env.AFK_SESSIONSTART_COOLDOWN_MS},get AFK_WEB_PORT(){return process.env.AFK_WEB_PORT},get AFK_WEB_HOST(){return process.env.AFK_WEB_HOST},get AFK_WEB_TOKEN(){return process.env.AFK_WEB_TOKEN},get AFK_WORKTREE_AUTONAME(){return process.env.AFK_WORKTREE_AUTONAME},get AFK_WORKTREE_BRANCH_PREFIX(){return process.env.AFK_WORKTREE_BRANCH_PREFIX},get AFK_WORKTREE_BASE(){return process.env.AFK_WORKTREE_BASE},get AFK_WORKTREE_ON_EXIT(){return process.env.AFK_WORKTREE_ON_EXIT},get AFK_WORKTREE_BOOT_PRUNE(){return process.env.AFK_WORKTREE_BOOT_PRUNE},get AFK_WORKTREE_PRUNE_DISABLE(){return process.env.AFK_WORKTREE_PRUNE_DISABLE},get AFK_WORKTREE_MAX_AGE_CLEAN(){return process.env.AFK_WORKTREE_MAX_AGE_CLEAN},get AFK_WORKTREE_MAX_AGE_DIRTY(){return process.env.AFK_WORKTREE_MAX_AGE_DIRTY},get AFK_WORKTREE_SWEEP_ROOT(){return process.env.AFK_WORKTREE_SWEEP_ROOT},get AFK_ALLOW_PROJECT_MCP(){return process.env.AFK_ALLOW_PROJECT_MCP},get AFK_AUTO_ROUTING(){return process.env.AFK_AUTO_ROUTING},get AFK_INTERNAL(){return process.env.AFK_INTERNAL},get AFK_SHELL_PASSTHROUGH(){return process.env.AFK_SHELL_PASSTHROUGH},get AFK_BG_AUTO_DELIVER(){return process.env.AFK_BG_AUTO_DELIVER},get AFK_BANNER_PLAIN(){return process.env.AFK_BANNER_PLAIN},get AFK_PLAIN_OUTPUT(){return process.env.AFK_PLAIN_OUTPUT},get AFK_SPINNER_TIPS(){return process.env.AFK_SPINNER_TIPS},get AFK_GOBLIN_SPINNER(){return process.env.AFK_GOBLIN_SPINNER},get AFK_GOBLIN_MASCOT(){return process.env.AFK_GOBLIN_MASCOT},get AFK_TERM_TITLE(){return process.env.AFK_TERM_TITLE},get AFK_NOTIFY(){return process.env.AFK_NOTIFY},get AFK_SHOW_DIFFS(){return process.env.AFK_SHOW_DIFFS},get AFK_SKILL_STREAM_VERBOSE(){return process.env.AFK_SKILL_STREAM_VERBOSE},get FORCE_COLOR(){return process.env.FORCE_COLOR},get NO_COLOR(){return process.env.NO_COLOR},get AFK_THEME(){return process.env.AFK_THEME},get AFK_TEXT_MEASURE(){return process.env.AFK_TEXT_MEASURE},get COLORFGBG(){return process.env.COLORFGBG},get COLORTERM(){return process.env.COLORTERM},get AFK_DEBUG(){return process.env.AFK_DEBUG},get AFK_DEBUG_CLIPBOARD(){return process.env.AFK_DEBUG_CLIPBOARD},get AFK_DEBUG_COMPOSITOR(){return process.env.AFK_DEBUG_COMPOSITOR},get AFK_TRACE_DISABLED(){return process.env.AFK_TRACE_DISABLED},get AFK_WITNESS_RETENTION_DISABLE(){return process.env.AFK_WITNESS_RETENTION_DISABLE},get AFK_WITNESS_MAX_AGE_DAYS(){return process.env.AFK_WITNESS_MAX_AGE_DAYS},get AFK_WITNESS_MAX_BYTES(){return process.env.AFK_WITNESS_MAX_BYTES},get AFK_SESSION_LEDGER_DISABLED(){return process.env.AFK_SESSION_LEDGER_DISABLED},get AFK_RUN_RECEIPT_DISABLED(){return process.env.AFK_RUN_RECEIPT_DISABLED},get AFK_CAPTURE_SUBAGENT_PROMPTS(){return process.env.AFK_CAPTURE_SUBAGENT_PROMPTS},get AFK_CAPTURE_SUBAGENT_OUTPUT(){return process.env.AFK_CAPTURE_SUBAGENT_OUTPUT},get DEBUG(){return process.env.DEBUG},get AGENT_AFK_ASCII(){return process.env.AGENT_AFK_ASCII},get AGENT_SURFACE(){return process.env.AGENT_SURFACE},get CI(){return process.env.CI},get NODE_ENV(){return process.env.NODE_ENV},get VITEST(){return process.env.VITEST},get NO_UPDATE_NOTIFIER(){return process.env.NO_UPDATE_NOTIFIER},get AFK_SESSION_ID(){return process.env.AFK_SESSION_ID},get AFK_BROWSER_HEADLESS(){return process.env.AFK_BROWSER_HEADLESS},get AFK_BROWSER_ALLOWED_DOMAINS(){return process.env.AFK_BROWSER_ALLOWED_DOMAINS},get AFK_BROWSER_BLOCKED_DOMAINS(){return process.env.AFK_BROWSER_BLOCKED_DOMAINS},get AFK_BROWSER_DOM_SNAPSHOTS(){return process.env.AFK_BROWSER_DOM_SNAPSHOTS},get AFK_BROWSER_BACKEND(){return process.env.AFK_BROWSER_BACKEND},get AFK_BROWSER_CONFIG(){return process.env.AFK_BROWSER_CONFIG},get AFK_BROWSER_DEFAULT_PROFILE(){return process.env.AFK_BROWSER_DEFAULT_PROFILE},get AFK_WRITE_DENYLIST(){return process.env.AFK_WRITE_DENYLIST},get AFK_READ_DENYLIST(){return process.env.AFK_READ_DENYLIST},get AFK_WRITE_DIFF(){return process.env.AFK_WRITE_DIFF},get AFK_RATE_LIMIT_ADMISSION_DISABLED(){return process.env.AFK_RATE_LIMIT_ADMISSION_DISABLED},get AFK_RATE_LIMIT_STAGGER_MAX_MS(){return process.env.AFK_RATE_LIMIT_STAGGER_MAX_MS},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},get AFK_WAVE_MANIFEST_DISABLED(){return process.env.AFK_WAVE_MANIFEST_DISABLED},get AFK_WAVE_MANIFEST_TTL_HOURS(){return process.env.AFK_WAVE_MANIFEST_TTL_HOURS},get AFK_WAVE_RESUME_UNATTENDED(){return process.env.AFK_WAVE_RESUME_UNATTENDED}};(function(){for(let e of br){if(!e.secret)continue;let n=Object.getOwnPropertyDescriptor(h,e.name);n&&Object.defineProperty(h,e.name,{...n,enumerable:!1})}})()});function E_(){return h.AFK_DEBUG==="1"||h.DEBUG==="1"}function P(...t){E_()&&console.log(...t)}var oe=ke(()=>{"use strict";C()});import{existsSync as vp,mkdirSync as R_,renameSync as x_,cpSync as I_,rmSync as C_}from"fs";import{join as B,dirname as Dc,basename as P_,isAbsolute as Fc}from"path";import{homedir as Ap}from"os";import{fileURLToPath as M_}from"url";function ce(){let t=h.AFK_HOME;if(t!==void 0&&t!==""){if(!Fc(t)||t==="/")throw new Error(`AFK_HOME must be an absolute path that is not /, got: ${t}`);return t}return B(Ap(),".afk")}function Fe(){let t=h.AFK_FRAMEWORK_DIR;if(t!==void 0&&t!==""){if(!Fc(t)||t==="/")throw new Error(`AFK_FRAMEWORK_DIR must be an absolute path that is not /, got: ${t}`);return t}return B(ce(),"agent-framework")}function ss(){return B(Fe(),"forge-telemetry.jsonl")}function _p(){return B(Fe(),"briefs")}function Tp(){return B(Fe(),"facets")}function wr(){return B(ce(),"skills")}function Sn(){return B(ce(),"plugins")}function Ep(t=process.cwd()){return B(t,".afk")}function Rp(t=process.cwd()){return B(Ep(t),"skills")}function xp(t=process.cwd()){return B(Ep(t),"plugins")}function Ip(t=process.cwd()){return B(t,".afk","plans")}function is(){return B(Sn(),".index.json")}function Lc(){return B(Sr(),"schedules.json")}function Cp(){let t=M_(import.meta.url),e=Dc(t);return B(e,"bundled-plugins")}function Sr(){return B(ce(),"config")}function pe(){let t=h.AFK_STATE_DIR;if(t!==void 0&&t!==""){if(!Fc(t)||t==="/")throw new Error(`AFK_STATE_DIR must be an absolute path that is not /, got: ${t}`);return t}return B(ce(),"state")}function Ie(){return B(pe(),"sessions")}function as(){return B(pe(),"presence")}function cs(){return B(pe(),"memory")}function ls(){return B(pe(),"session-grants.jsonl")}function Pp(){return B(ce(),"farms")}function Mp(t){return B(Pp(),t)}function ds(t){if(!O_.test(t))throw new Error(`Invalid AFK_SESSION_ID: must match /^[a-zA-Z0-9_-]+$/, got: ${JSON.stringify(t)}`)}function vr(){return B(pe(),"witness")}function Rt(t){return ds(t),B(vr(),t)}function Op(t){return B(Rt(t),"inbound-attachments")}function Dp(t){return B(Rt(t),"prompts")}function Fp(t){return B(Rt(t),"outputs")}function vn(t){return!t||t.startsWith("in-memory:")?null:P_(Dc(t))}function Lp(t="default"){return B(pe(),"daemon",`agent-afk@${t}`)}function Np(){return B(pe(),"worktree-sweep.lock")}function us(){return B(pe(),"worktree-roots.json")}function Nc(){return B(Sr(),"afk.env")}function kn(){return B(Sr(),"afk.config.json")}function ps(){return B(Ap(),".afk.config.json")}function D_(){return B(ce(),"sessions")}function F_(t,e){if(t!==e&&vp(t)&&!vp(e))try{R_(Dc(e),{recursive:!0});try{x_(t,e)}catch(n){if(n.code==="EXDEV")try{I_(t,e,{recursive:!0}),C_(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 Up(){F_(D_(),Ie())}function Uc(t){if(typeof t!="string"||t.length===0)throw new Error("Invalid browser profile: must be a non-empty string");if(t.length>kp)throw new Error(`Invalid browser profile: exceeds ${kp} chars`);if(!L_.test(t))throw new Error(`Invalid browser profile: ${JSON.stringify(t)} contains characters outside [A-Za-z0-9_-]`)}function N_(){return B(pe(),"browser")}function U_(t){return Uc(t),B(N_(),t)}function Bc(t){return B(U_(t),"storageState.json")}function An(t){return typeof t=="string"&&t.length>0&&t.length<=$_&&B_.test(t)}function kr(t){if(!An(t))throw new Error(`Invalid session id for ledger path: ${JSON.stringify(t)}`);return B(Ie(),t)}function Ar(t){return B(kr(t),"events.jsonl")}function Bp(t){return B(kr(t),"session.key")}function fs(){return B(pe(),"waves")}function ms(t){return B(fs(),`${t}.json`)}var O_,L_,kp,B_,$_,D=ke(()=>{"use strict";C();O_=/^[a-zA-Z0-9_-]+$/;L_=/^[A-Za-z0-9_-]+$/,kp=128;B_=/^[A-Za-z0-9_-]+$/,$_=128});import{readFileSync as VC}from"node:fs";import{join as JC}from"path";function YC(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Xg(t,e){return YC(e).test(t)}function eP(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(QC.has(e))return!0;if(ZC.has(e))return!1}return!1}function zg(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function tP(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 Vg(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Uc(e),e}function nP(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function rP(t){try{return VC(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function oP(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=Vg(e.defaultProfile)),n}function Jg(t){let e=t?.env??h,n=t?.readFileSync??rP,r=t?.surface??e.AGENT_SURFACE,o=eP(e.AFK_BROWSER_HEADLESS,r),s=zg(e.AFK_BROWSER_ALLOWED_DOMAINS),i=zg(e.AFK_BROWSER_BLOCKED_DOMAINS),a=nP(e.AFK_BROWSER_DOM_SNAPSHOTS),c=tP(e.AFK_BROWSER_BACKEND),l=Vg(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():JC(Sr(),"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=oP(d,m);return g.configPath=p,g}function di(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(Xg(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Xg(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var QC,ZC,ui=ke(()=>{"use strict";C();D();QC=new Set(["daemon","subagent","telegram","afk"]),ZC=new Set(["repl","interactive","cli"])});import{existsSync as sP,readFileSync as iP}from"node:fs";import{createRequire as aP}from"node:module";import{dirname as cP,join as lP}from"node:path";function Zg(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<uP&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function xe(t){let e=Zg(t);return Qg.some(n=>e.includes(n))}function pP(){try{let e=aP(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(iP(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=lP(cP(e),o);return sP(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function so(){return Yg??=pP()??dP,Yg}function Xl(t){return t.includes("install chromium")}function He(t,e){let n=Zg(t),r=e?.latched===!0?` ${fP}`:"";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: ${so()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${so()}). Or pick a different tool.${r}`}function zl(t,e,n=!1){if(!xe(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
3
3
|
|
|
4
|
-
${He(t,{headless:e,latched:n})}`,{cause:t})}var Qg,dP,uP,Yg,fP,Vl=ke(()=>{"use strict";Qg=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],dP="pnpm exec playwright install chromium",uP=4;fP="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import un from"node:fs";import pi from"node:path";import{randomBytes as mP}from"node:crypto";import{chromium as gP}from"playwright";function hP(){try{return"5.119.2"}catch{}try{let t=pi.resolve(import.meta.dirname,"../../../package.json"),e=un.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var yP,fi,eh=ke(()=>{"use strict";Vl();D();oe();yP=hP(),fi=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=gP.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=zl(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(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${yP}`}}loadStorageState(e){let n=Bc(e);try{if(!un.existsSync(n))return;let r=JSON.parse(un.readFileSync(n,"utf8"));return P("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){P("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Bc(e);if(!un.existsSync(r))return;let o=await n.storageState(),s=pi.join(pi.dirname(r),`.${pi.basename(r)}.${process.pid}.${mP(4).toString("hex")}.tmp`);un.writeFileSync(s,JSON.stringify(o),{mode:384}),un.chmodSync(s,384),un.renameSync(s,r),P("[browser/vault] saved session",{profile:e,file:r})}catch(r){P("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as bP}from"crypto";function th(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&wP.test(t.label))}function nh(t){return bP("sha256").update(t,"utf8").digest("hex").slice(0,8)}function rh(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var wP,mi=ke(()=>{"use strict";wP=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as SP}from"node:crypto";function vP(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function kP(t,e,n){return`el_${SP("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function AP(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function oh(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ih(t,e){let n=t.role??"",r=t.name??"";sh.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])ih(s,e)}async function _P(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},ah).catch(()=>[])}async function TP(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},ah).catch(()=>[])}function EP(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function gi(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=EP(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=_P(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],ih(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await TP(t)).filter(W=>sh.has(W.role??"")));let v=new Map;for(let T of p){let W=oh(T.name),Q=v.get(W);(!Q||Q.bbox.w===0&&T.bbox.w>0)&&v.set(W,T)}let _=y.map(T=>({ax:T,dom:v.get(oh(T.name??""))})),w=r?_:_.filter(T=>T.dom?T.dom.bbox.w>0||T.dom.bbox.h>0:!0);w.sort((T,W)=>{let Q=T.dom?.bbox.y??0,O=W.dom?.bbox.y??0;if(Q!==O)return Q-O;let L=T.dom?.bbox.x??0,F=W.dom?.bbox.x??0;return L-F}),w.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=w.slice(0,n).map((T,W)=>{let Q=T.ax.role??"generic",O=T.ax.name??"",L=kP(Q,O,W),F=T.dom?.bbox??{x:0,y:0,w:0,h:0},M=T.dom?.type??null,G=null;T.ax.value!==void 0&&T.ax.value!==null&&(G=String(T.ax.value)),T.ax.checked!==void 0&&(G=String(T.ax.checked)),th({role:Q,kind:M})&&(G="[redacted]");let U={disabled:T.ax.disabled??!1};T.ax.checked!==void 0&&(U.checked=T.ax.checked===!0||T.ax.checked==="mixed"),T.ax.selected!==void 0&&(U.selected=T.ax.selected),T.ax.expanded!==void 0&&(U.expanded=T.ax.expanded);let z;T.dom?.testId?z=`[data-testid="${T.dom.testId}"]`:T.dom?.id&&(z=`#${T.dom.id}`);let Z={id:L,role:Q,label:vP(O),kind:M,value:G,state:U,bbox:F};return z!==void 0&&(Z.selector=z),Z}),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 I=AP(f),S=`obs_${e.observationCounter.toString(36)}`,x=new Date().toISOString();return{observationId:S,url:m,title:g,textSummary:I,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:x}}var sh,ah,ch=ke(()=>{"use strict";mi();sh=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);ah="a[href], button, input, select, textarea, [role], [tabindex], label"});async function lh(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Jl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>lh(t,s)))).filter(o=>o!==null)}async function RP(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Yl(t,e,n){switch(e.kind){case"element_id":return xP(t,e,n);case"selector":return IP(t,e);case"semantic":return CP(t,e)}}async function xP(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Jl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function IP(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Jl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function CP(t,e){return e.role!==void 0?PP(t,e.text,e.role):MP(t,e.text,e)}async function PP(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Jl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function MP(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await RP(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let y=p[g];if(y===void 0)continue;let b=await lh(y.locator,y.index);if(b!==null){let v=`${b.role}:${b.label}:${g}`,_=0;for(let w=0;w<v.length;w++)_=_*31+v.charCodeAt(w)>>>0;f.push({...b,id:`el_${_.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var dh=ke(()=>{"use strict"});async function Ql(t,e,n,r){let o=t.url();if(o===n)return null;let s=di(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 uh=ke(()=>{"use strict";ui()});import{randomBytes as OP}from"crypto";import{mkdir as DP,stat as FP,writeFile as LP}from"fs/promises";import{join as Zl}from"path";import{gzip as NP}from"zlib";import{promisify as UP}from"util";function BP(t){return Zl(Rt(t),"browser")}function $P(t){return Zl(BP(t),"screenshots")}function HP(){return new Date().toISOString().replace(/[:.]/g,"-")}function jP(){return OP(3).toString("hex")}async function ed(t,e,n){if(e.length>ph)throw new Error(`writeScreenshotSidecar: buffer exceeds ${ph} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=$P(t);await DP(r,{recursive:!0});let o=`${HP()}-${jP()}-${n}.png`,s=Zl(r,o);await LP(s,e);let{size:i}=await FP(s);return{path:s,bytes:i}}var PX,ph,fh=ke(()=>{"use strict";D();mi();PX=UP(NP);ph=5*1024*1024});var gh={};wp(gh,{PlaywrightProvider:()=>td});function mh(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 td,hh=ke(()=>{"use strict";eh();ch();dh();ui();uh();fh();td=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new fi(e)}async open(e){let n=di(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await Ql(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 gi(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 gi(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 Yl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${mh(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(y){l=y}else l=g}let u=await Ql(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await gi(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Yl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${mh(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 ed(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await ed(n,o,r);return s}catch{return null}}}});var fn={};wp(fn,{__resetBrowserRegistryForTests:()=>XP,browserProviderActive:()=>GP,closeBrowserProvider:()=>nd,getBrowserProvider:()=>KP,peekBrowserProvider:()=>qP});function yh(){Promise.resolve(nd()).then(()=>{process.exit(130)})}function bh(){Promise.resolve(nd()).then(()=>{process.exit(143)})}function wh(){rt=null}function WP(){hi||(process.on("SIGINT",yh),process.on("SIGTERM",bh),process.on("exit",wh),hi=!0)}function Sh(){hi&&(process.removeListener("SIGINT",yh),process.removeListener("SIGTERM",bh),process.removeListener("exit",wh),hi=!1)}async function KP(t){return rt!==null?rt:(pn!==null||(pn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(hh(),gh)),n=Jg(t),r=new e(n);return WP(),rt=r,pn=null,r})()),pn)}async function nd(){if(rt===null)return;let t=rt;rt=null,pn=null,Sh(),await t.shutdown()}function GP(){return rt!==null}function qP(){return rt}function XP(){rt=null,pn=null,Sh()}var rt,pn,hi,mn=ke(()=>{"use strict";ui();rt=null,pn=null,hi=!1});oe();C();D();import{randomBytes as tT}from"node:crypto";import{mkdir as nT,writeFile as rT}from"node:fs/promises";import{join as oT}from"node:path";oe();var H_=256,$p=new WeakMap,_r=new Map;function j_(t){return t instanceof Error?t.message:String(t)}function W_(t,e){if(typeof e=="object"&&e!==null){let r=$p.get(e);return r||(r=new Set,$p.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(_r.has(n))return!1;if(_r.set(n,!0),_r.size>H_){let r=_r.keys().next().value;r!==void 0&&_r.delete(r)}return!0}function he(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${j_(r)}`;if(!W_(t,e)){P(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}C();import{mkdirSync as G_,appendFileSync as q_,existsSync as X_}from"fs";import{resolve as z_}from"path";import{dirname as V_}from"path";function $c(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>Hc(e)||K_(e)?e:"[REDACTED]")}function Hc(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function K_(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var J_=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
4
|
+
${He(t,{headless:e,latched:n})}`,{cause:t})}var Qg,dP,uP,Yg,fP,Vl=ke(()=>{"use strict";Qg=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],dP="pnpm exec playwright install chromium",uP=4;fP="This session already latched the failure, so browser tools keep fast-failing with this same error \u2014 after installing, call browser_close once to retry."});import un from"node:fs";import pi from"node:path";import{randomBytes as mP}from"node:crypto";import{chromium as gP}from"playwright";function hP(){try{return"5.119.3"}catch{}try{let t=pi.resolve(import.meta.dirname,"../../../package.json"),e=un.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var yP,fi,eh=ke(()=>{"use strict";Vl();D();oe();yP=hP(),fi=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=gP.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=zl(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(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${yP}`}}loadStorageState(e){let n=Bc(e);try{if(!un.existsSync(n))return;let r=JSON.parse(un.readFileSync(n,"utf8"));return P("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){P("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Bc(e);if(!un.existsSync(r))return;let o=await n.storageState(),s=pi.join(pi.dirname(r),`.${pi.basename(r)}.${process.pid}.${mP(4).toString("hex")}.tmp`);un.writeFileSync(s,JSON.stringify(o),{mode:384}),un.chmodSync(s,384),un.renameSync(s,r),P("[browser/vault] saved session",{profile:e,file:r})}catch(r){P("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as bP}from"crypto";function th(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&wP.test(t.label))}function nh(t){return bP("sha256").update(t,"utf8").digest("hex").slice(0,8)}function rh(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var wP,mi=ke(()=>{"use strict";wP=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as SP}from"node:crypto";function vP(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function kP(t,e,n){return`el_${SP("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function AP(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function oh(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function ih(t,e){let n=t.role??"",r=t.name??"";sh.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])ih(s,e)}async function _P(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},ah).catch(()=>[])}async function TP(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let g=s.type;g==="checkbox"?l="checkbox":g==="radio"?l="radio":g==="button"||g==="submit"||g==="reset"?l="button":g==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},ah).catch(()=>[])}function EP(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function gi(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=EP(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=_P(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,g]=await Promise.all([i,a,c,l,d]),y,b=!1;u!==null?(y=[],ih(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await TP(t)).filter(W=>sh.has(W.role??"")));let v=new Map;for(let T of p){let W=oh(T.name),Q=v.get(W);(!Q||Q.bbox.w===0&&T.bbox.w>0)&&v.set(W,T)}let _=y.map(T=>({ax:T,dom:v.get(oh(T.name??""))})),w=r?_:_.filter(T=>T.dom?T.dom.bbox.w>0||T.dom.bbox.h>0:!0);w.sort((T,W)=>{let Q=T.dom?.bbox.y??0,O=W.dom?.bbox.y??0;if(Q!==O)return Q-O;let L=T.dom?.bbox.x??0,F=W.dom?.bbox.x??0;return L-F}),w.length>200&&o.push("page has 200+ interactive elements; consider scoping");let k=w.slice(0,n).map((T,W)=>{let Q=T.ax.role??"generic",O=T.ax.name??"",L=kP(Q,O,W),F=T.dom?.bbox??{x:0,y:0,w:0,h:0},M=T.dom?.type??null,G=null;T.ax.value!==void 0&&T.ax.value!==null&&(G=String(T.ax.value)),T.ax.checked!==void 0&&(G=String(T.ax.checked)),th({role:Q,kind:M})&&(G="[redacted]");let U={disabled:T.ax.disabled??!1};T.ax.checked!==void 0&&(U.checked=T.ax.checked===!0||T.ax.checked==="mixed"),T.ax.selected!==void 0&&(U.selected=T.ax.selected),T.ax.expanded!==void 0&&(U.expanded=T.ax.expanded);let z;T.dom?.testId?z=`[data-testid="${T.dom.testId}"]`:T.dom?.id&&(z=`#${T.dom.id}`);let Z={id:L,role:Q,label:vP(O),kind:M,value:G,state:U,bbox:F};return z!==void 0&&(Z.selector=z),Z}),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 I=AP(f),S=`obs_${e.observationCounter.toString(36)}`,x=new Date().toISOString();return{observationId:S,url:m,title:g,textSummary:I,interactive:k,status:{httpStatus:e.httpStatus??null,loadingState:R,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:x}}var sh,ah,ch=ke(()=>{"use strict";mi();sh=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);ah="a[href], button, input, select, textarea, [role], [tabindex], label"});async function lh(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function Jl(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>lh(t,s)))).filter(o=>o!==null)}async function RP(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function Yl(t,e,n){switch(e.kind){case"element_id":return xP(t,e,n);case"selector":return IP(t,e);case"semantic":return CP(t,e)}}async function xP(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await Jl(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function IP(t,e){let n=t.locator(e.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:e};if(r===1)return{outcome:"resolved",locator:n};let o=await Jl(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function CP(t,e){return e.role!==void 0?PP(t,e.text,e.role):MP(t,e.text,e)}async function PP(t,e,n){let r=t.getByRole(n,{name:e}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:e,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await Jl(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function MP(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await RP(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let g=u[0];return g===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:g.locator.nth(g.index)}}let p=u.slice(0,5),f=[];for(let g=0;g<p.length;g++){let y=p[g];if(y===void 0)continue;let b=await lh(y.locator,y.index);if(b!==null){let v=`${b.role}:${b.label}:${g}`,_=0;for(let w=0;w<v.length;w++)_=_*31+v.charCodeAt(w)>>>0;f.push({...b,id:`el_${_.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var dh=ke(()=>{"use strict"});async function Ql(t,e,n,r){let o=t.url();if(o===n)return null;let s=di(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 uh=ke(()=>{"use strict";ui()});import{randomBytes as OP}from"crypto";import{mkdir as DP,stat as FP,writeFile as LP}from"fs/promises";import{join as Zl}from"path";import{gzip as NP}from"zlib";import{promisify as UP}from"util";function BP(t){return Zl(Rt(t),"browser")}function $P(t){return Zl(BP(t),"screenshots")}function HP(){return new Date().toISOString().replace(/[:.]/g,"-")}function jP(){return OP(3).toString("hex")}async function ed(t,e,n){if(e.length>ph)throw new Error(`writeScreenshotSidecar: buffer exceeds ${ph} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=$P(t);await DP(r,{recursive:!0});let o=`${HP()}-${jP()}-${n}.png`,s=Zl(r,o);await LP(s,e);let{size:i}=await FP(s);return{path:s,bytes:i}}var PX,ph,fh=ke(()=>{"use strict";D();mi();PX=UP(NP);ph=5*1024*1024});var gh={};wp(gh,{PlaywrightProvider:()=>td});function mh(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 td,hh=ke(()=>{"use strict";eh();ch();dh();ui();uh();fh();td=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new fi(e)}async open(e){let n=di(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await Ql(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 gi(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 gi(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 Yl(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${mh(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(g){if(g instanceof Error&&/navigation|net::ERR/i.test(g.message))try{await d()}catch(y){l=y}else l=g}let u=await Ql(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await gi(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await Yl(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${mh(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 ed(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await ed(n,o,r);return s}catch{return null}}}});var fn={};wp(fn,{__resetBrowserRegistryForTests:()=>XP,browserProviderActive:()=>GP,closeBrowserProvider:()=>nd,getBrowserProvider:()=>KP,peekBrowserProvider:()=>qP});function yh(){Promise.resolve(nd()).then(()=>{process.exit(130)})}function bh(){Promise.resolve(nd()).then(()=>{process.exit(143)})}function wh(){rt=null}function WP(){hi||(process.on("SIGINT",yh),process.on("SIGTERM",bh),process.on("exit",wh),hi=!0)}function Sh(){hi&&(process.removeListener("SIGINT",yh),process.removeListener("SIGTERM",bh),process.removeListener("exit",wh),hi=!1)}async function KP(t){return rt!==null?rt:(pn!==null||(pn=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(hh(),gh)),n=Jg(t),r=new e(n);return WP(),rt=r,pn=null,r})()),pn)}async function nd(){if(rt===null)return;let t=rt;rt=null,pn=null,Sh(),await t.shutdown()}function GP(){return rt!==null}function qP(){return rt}function XP(){rt=null,pn=null,Sh()}var rt,pn,hi,mn=ke(()=>{"use strict";ui();rt=null,pn=null,hi=!1});oe();C();D();import{randomBytes as tT}from"node:crypto";import{mkdir as nT,writeFile as rT}from"node:fs/promises";import{join as oT}from"node:path";oe();var H_=256,$p=new WeakMap,_r=new Map;function j_(t){return t instanceof Error?t.message:String(t)}function W_(t,e){if(typeof e=="object"&&e!==null){let r=$p.get(e);return r||(r=new Set,$p.set(e,r)),r.has(t)?!1:(r.add(t),!0)}let n=`${t}\0${String(e)}`;if(_r.has(n))return!1;if(_r.set(n,!0),_r.size>H_){let r=_r.keys().next().value;r!==void 0&&_r.delete(r)}return!0}function he(t,e,n,r){try{let o=`[afk] ${t} artifact write failed (${n}): ${j_(r)}`;if(!W_(t,e)){P(o);return}console.error(`${o} \u2014 further failures in this subsystem for this session are logged only under AFK_DEBUG=1.`)}catch{}}C();import{mkdirSync as G_,appendFileSync as q_,existsSync as X_}from"fs";import{resolve as z_}from"path";import{dirname as V_}from"path";function $c(t){return t.replace(/\bauthorization:\s*bearer\s+\S+/gi,"Authorization: Bearer [REDACTED]").replace(/\bsk-ant-[A-Za-z0-9_-]{20,}/g,"[REDACTED]").replace(/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g,"[REDACTED]").replace(/\b(?:AKIA|ASIA|AROA|AIDA|AGPA|AIPA|ANPA|ANVA|APKA|ABIA|ACCA)[A-Z0-9]{16}\b/g,"[REDACTED]").replace(/(?<![/.\w])[A-Za-z0-9+/=_-]{32,}(?![/.\w])/g,e=>Hc(e)||K_(e)?e:"[REDACTED]")}function Hc(t){if(!t.includes("/")||/[+=]/.test(t))return!1;let e=n=>n.length>=32&&!n.includes(".")&&/[A-Za-z]/.test(n)&&/[0-9]/.test(n);return!t.split("/").some(e)}function K_(t){if(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(t))return!0;let e=/^([A-Za-z_][A-Za-z0-9_]*)=(?:[0-9a-f]{40}|[0-9a-f]{64})$/.exec(t);return e!==null&&/^(?:ref|sha|commit|base)$/i.test(e[1]??"")}var J_=`# AFK PROMPT DUMP \u2014 May contain secrets. Inspect before sharing.
|
|
5
5
|
`,Y_=/key|token|secret|password|credential|auth/i;function Hp(t){let e=t[1],n=t[2],r=n[0],o=(r==='"'||r==="'")&&n.at(-1)===r?n.slice(1,-1):n,s=/(?:^|_)(?:PATH|FILE)(?:_|$)/i.test(e),i=o.startsWith("/")||o.startsWith("~/"),c=o.split("/").filter(Boolean).some(l=>/[A-Z0-9.\-]/.test(l));return s&&i&&c&&Hc(o)?`${e}=${n}`:`${e}=<REDACTED length=${n.length}>`}var Q_=[[/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,Hp],[/([A-Z_]{3,}(?:KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTH)[A-Z_]*)=([^\s]{16,})/g,Hp]];function Tr(t){let e=t;for(let[n,r]of Q_)e=e.replace(n,(...o)=>{let s=o.slice(0,o.length-2);return r(s)});return e}function jc(t){return typeof t=="string"?Tr(t):Array.isArray(t)?t.map(jc):t}function Z_(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))Y_.test(s)&&typeof i=="string"?o[s]=`<REDACTED length=${i.length}>`:o[s]=i;n.env=o}return"system"in e&&(n.system=jc(e.system)),"systemPrompt"in e&&(n.systemPrompt=jc(e.systemPrompt)),n}function eT(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 jp(t){let e=h.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=eT(r),s={timestamp:new Date().toISOString(),prompt:t.prompt,options:Z_(t.options),provenance:t.provenance,resolution:o};if(e==="1"||e.toLowerCase()==="true"||e.toLowerCase()==="stderr"){let c=JSON.stringify(s,null,2)+`
|
|
7
7
|
`;process.stderr.write(c);return}let i=z_(e),a=V_(i);try{G_(a,{recursive:!0});let l=(!X_(i)?J_:"")+JSON.stringify(s)+`
|
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 KH,cm=g(()=>{"use strict";KH=new Set(["script","style","noscript","template","svg"])});function XH(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 Dk(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function zH(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 Fk(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??XH,c=n.signal??void 0,l;for(let d=0;d<=o;d++){if(c?.aborted)throw c.reason??new Error("aborted");try{let u=await t(e,n);if(!qH.has(u.status)||d===o)return u;let p=zH(u,i)??Dk(d,s,i);$("[web/retryFetch] retrying",{url:e,attempt:d,status:u.status,waitMs:p}),await u.body?.cancel().catch(()=>{}),await a(p,c)}catch(u){if(c?.aborted||(l=u,d===o))throw u;let p=Dk(d,s,i);$("[web/retryFetch] retrying after error",{url:e,attempt:d,waitMs:p}),await a(p,c)}}throw l??new Error("retryFetch: exhausted without a result")}var qH,Lk=g(()=>{"use strict";fe();qH=new Set([429,502,503,504])});import{BlockList as VH,isIP as dm}from"node:net";import{lookup as JH}from"node:dns/promises";import{Agent as YH}from"undici";function Uk(){let t=v.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return t==="1"||t==="true"}function tj(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function lm(t){let e=dm(t);return e===0?!1:ej.check(t,e===4?"ipv4":"ipv6")}async function $k(t){return JH(t,{all:!0,verbatim:!0})}async function um(t,e={}){if(e.allowPrivateHosts??Uk())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=tj(n.hostname),o=(a,c)=>`refusing to fetch ${c} \u2014 internal/private address ${a} (loopback, link-local, cloud metadata, or RFC1918 space). Set AFK_WEB_ALLOW_PRIVATE_HOSTS=1 to allow private-host access.`;if(dm(r)!==0)return lm(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let s=e.lookupFn??$k,i;try{i=await s(r)}catch{return{allowed:!0}}for(let a of i)if(lm(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Vs(t,e={}){let n=await um(t,e);if(!n.allowed)throw new _t(n.reason)}async function zc(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<=Nk;i++){await Vs(s,o);let a={...n,redirect:"manual",...t===globalThis.fetch&&!(r.allowPrivateHosts??Uk())?{dispatcher:nj}:{}},c=await Fk(t,s,a,r.retry??{});if(!rj.has(c.status))return c;let l=c.headers.get("location");if(l===null||l.trim()==="")return c;let d;try{d=new URL(l,c.url||s).toString()}catch{return c}await c.body?.cancel().catch(()=>{}),s=d}throw new _t(`too many redirects (>${Nk}) starting from ${e}`)}var QH,ZH,ej,_t,nj,Nk,rj,pm=g(()=>{"use strict";F();Lk();QH=[["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]],ZH=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],ej=(()=>{let t=new VH;for(let[e,n]of QH)t.addSubnet(e,n,"ipv4");for(let[e,n]of ZH)t.addSubnet(e,n,"ipv6");return t})(),_t=class extends Error{constructor(e){super(e),this.name="EgressBlockedError"}};nj=new YH({connect:{lookup(t,e,n){$k(t).then(r=>{let o=r.find(i=>lm(i.address));if(o!==void 0){n(new _t(`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,dm(s.address))},r=>n(r,"",0))}}});Nk=20,rj=new Set([301,302,303,307,308])});import{readFileSync as oj}from"node:fs";import{join as sj}from"path";function ij(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function Bk(t,e){return ij(e).test(t)}function lj(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(aj.has(e))return!0;if(cj.has(e))return!1}return!1}function Hk(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function dj(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 jk(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Ep(e),e}function uj(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function pj(t){try{return oj(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function fj(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=jk(e.defaultProfile)),n}function Wk(t){let e=t?.env??v,n=t?.readFileSync??pj,r=t?.surface??e.AGENT_SURFACE,o=lj(e.AFK_BROWSER_HEADLESS,r),s=Hk(e.AFK_BROWSER_ALLOWED_DOMAINS),i=Hk(e.AFK_BROWSER_BLOCKED_DOMAINS),a=uj(e.AFK_BROWSER_DOM_SNAPSHOTS),c=dj(e.AFK_BROWSER_BACKEND),l=jk(e.AFK_BROWSER_DEFAULT_PROFILE),d={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:c,configPath:null,defaultProfile:l},u=e.AFK_BROWSER_CONFIG,p=u!==void 0&&u.trim()!==""?u.trim():sj(Xt(),"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 h=fj(d,m);return h.configPath=p,h}function Vc(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(Bk(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>Bk(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var aj,cj,Jc=g(()=>{"use strict";F();H();aj=new Set(["daemon","subagent","telegram","afk"]),cj=new Set(["repl","interactive","cli"])});import{existsSync as mj,readFileSync as gj}from"node:fs";import{createRequire as hj}from"node:module";import{dirname as yj,join as bj}from"node:path";function qk(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<Sj&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function We(t){let e=qk(t);return Gk.some(n=>e.includes(n))}function vj(){try{let e=hj(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(gj(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=bj(yj(e),o);return mj(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function Js(){return Kk??=vj()??wj,Kk}function fm(t){return t.includes("install chromium")}function dt(t,e){let n=qk(t),r=e?.latched===!0?` ${kj}`:"";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: ${Js()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${Js()}). Or pick a different tool.${r}`}function mm(t,e,n=!1){if(!We(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
213
213
|
|
|
214
|
-
${dt(t,{headless:e,latched:n})}`,{cause:t})}var Gk,wj,Sj,Kk,kj,gm=g(()=>{"use strict";Gk=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],wj="pnpm exec playwright install chromium",Sj=4;kj="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 lr from"node:fs";import Yc from"node:path";import{randomBytes as Aj}from"node:crypto";import{chromium as _j}from"playwright";function Tj(){try{return"5.119.2"}catch{}try{let t=Yc.resolve(import.meta.dirname,"../../../package.json"),e=lr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Ej,Qc,Xk=g(()=>{"use strict";gm();H();fe();Ej=Tj(),Qc=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=_j.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=mm(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(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${Ej}`}}loadStorageState(e){let n=Rp(e);try{if(!lr.existsSync(n))return;let r=JSON.parse(lr.readFileSync(n,"utf8"));return $("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){$("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Rp(e);if(!lr.existsSync(r))return;let o=await n.storageState(),s=Yc.join(Yc.dirname(r),`.${Yc.basename(r)}.${process.pid}.${Aj(4).toString("hex")}.tmp`);lr.writeFileSync(s,JSON.stringify(o),{mode:384}),lr.chmodSync(s,384),lr.renameSync(s,r),$("[browser/vault] saved session",{profile:e,file:r})}catch(r){$("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as Rj}from"crypto";function zk(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&xj.test(t.label))}function Vk(t){return Rj("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Jk(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var xj,Zc=g(()=>{"use strict";xj=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Ij}from"node:crypto";function Cj(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Pj(t,e,n){return`el_${Ij("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Mj(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Yk(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Zk(t,e){let n=t.role??"",r=t.name??"";Qk.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Zk(s,e)}async function Oj(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},eA).catch(()=>[])}async function Dj(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?l="checkbox":h==="radio"?l="radio":h==="button"||h==="submit"||h==="reset"?l="button":h==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},eA).catch(()=>[])}function Fj(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function el(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=Fj(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Oj(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,h]=await Promise.all([i,a,c,l,d]),y,w=!1;u!==null?(y=[],Zk(u,y)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,y=(await Dj(t)).filter(L=>Qk.has(L.role??"")));let A=new Map;for(let I of p){let L=Yk(I.name),z=A.get(L);(!z||z.bbox.w===0&&I.bbox.w>0)&&A.set(L,I)}let _=y.map(I=>({ax:I,dom:A.get(Yk(I.name??""))})),k=r?_:_.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,L)=>{let z=I.dom?.bbox.y??0,P=L.dom?.bbox.y??0;if(z!==P)return z-P;let B=I.dom?.bbox.x??0,N=L.dom?.bbox.x??0;return B-N}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((I,L)=>{let z=I.ax.role??"generic",P=I.ax.name??"",B=Pj(z,P,L),N=I.dom?.bbox??{x:0,y:0,w:0,h:0},M=I.dom?.type??null,U=null;I.ax.value!==void 0&&I.ax.value!==null&&(U=String(I.ax.value)),I.ax.checked!==void 0&&(U=String(I.ax.checked)),zk({role:z,kind:M})&&(U="[redacted]");let j={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(j.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(j.selected=I.ax.selected),I.ax.expanded!==void 0&&(j.expanded=I.ax.expanded);let J;I.dom?.testId?J=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(J=`#${I.dom.id}`);let te={id:B,role:z,label:Cj(P),kind:M,value:U,state:j,bbox:N};return J!==void 0&&(te.selector=J),te}),C="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?C="loading":I==="interactive"?C="navigating":C="idle"}catch{C="navigating"}C!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let x=Mj(f),S=`obs_${e.observationCounter.toString(36)}`,R=new Date().toISOString();return{observationId:S,url:m,title:h,textSummary:x,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:C,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:R}}var Qk,eA,tA=g(()=>{"use strict";Zc();Qk=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);eA="a[href], button, input, select, textarea, [role], [tabindex], label"});async function nA(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function hm(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>nA(t,s)))).filter(o=>o!==null)}async function Lj(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function ym(t,e,n){switch(e.kind){case"element_id":return Nj(t,e,n);case"selector":return Uj(t,e);case"semantic":return $j(t,e)}}async function Nj(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await hm(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Uj(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 hm(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function $j(t,e){return e.role!==void 0?Bj(t,e.text,e.role):Hj(t,e.text,e)}async function Bj(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 hm(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Hj(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await Lj(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=u.slice(0,5),f=[];for(let h=0;h<p.length;h++){let y=p[h];if(y===void 0)continue;let w=await nA(y.locator,y.index);if(w!==null){let A=`${w.role}:${w.label}:${h}`,_=0;for(let k=0;k<A.length;k++)_=_*31+A.charCodeAt(k)>>>0;f.push({...w,id:`el_${_.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var rA=g(()=>{"use strict"});async function bm(t,e,n,r){let o=t.url();if(o===n)return null;let s=Vc(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 oA=g(()=>{"use strict";Jc()});import{randomBytes as jj}from"crypto";import{mkdir as Wj,stat as Kj,writeFile as Gj}from"fs/promises";import{join as wm}from"path";import{gzip as qj}from"zlib";import{promisify as Xj}from"util";function zj(t){return wm(It(t),"browser")}function Vj(t){return wm(zj(t),"screenshots")}function Jj(){return new Date().toISOString().replace(/[:.]/g,"-")}function Yj(){return jj(3).toString("hex")}async function Sm(t,e,n){if(e.length>sA)throw new Error(`writeScreenshotSidecar: buffer exceeds ${sA} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=Vj(t);await Wj(r,{recursive:!0});let o=`${Jj()}-${Yj()}-${n}.png`,s=wm(r,o);await Gj(s,e);let{size:i}=await Kj(s);return{path:s,bytes:i}}var bre,sA,iA=g(()=>{"use strict";H();Zc();bre=Xj(qj);sA=5*1024*1024});var cA={};wp(cA,{PlaywrightProvider:()=>vm});function aA(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 vm,lA=g(()=>{"use strict";Xk();tA();rA();Jc();oA();iA();vm=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Qc(e)}async open(e){let n=Vc(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await bm(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 el(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 el(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 ym(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${aA(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(y){l=y}else l=h}let u=await bm(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await el(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await ym(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${aA(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 Sm(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Sm(n,o,r);return s}catch{return null}}}});var ur={};wp(ur,{__resetBrowserRegistryForTests:()=>nW,browserProviderActive:()=>eW,closeBrowserProvider:()=>km,getBrowserProvider:()=>Zj,peekBrowserProvider:()=>tW});function dA(){Promise.resolve(km()).then(()=>{process.exit(130)})}function uA(){Promise.resolve(km()).then(()=>{process.exit(143)})}function pA(){$t=null}function Qj(){tl||(process.on("SIGINT",dA),process.on("SIGTERM",uA),process.on("exit",pA),tl=!0)}function fA(){tl&&(process.removeListener("SIGINT",dA),process.removeListener("SIGTERM",uA),process.removeListener("exit",pA),tl=!1)}async function Zj(t){return $t!==null?$t:(dr!==null||(dr=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(lA(),cA)),n=Wk(t),r=new e(n);return Qj(),$t=r,dr=null,r})()),dr)}async function km(){if($t===null)return;let t=$t;$t=null,dr=null,fA(),await t.shutdown()}function eW(){return $t!==null}function tW(){return $t}function nW(){$t=null,dr=null,fA()}var $t,dr,tl,pr=g(()=>{"use strict";Jc();$t=null,dr=null,tl=!1});async function mA(t,e){try{return await Pk(t,e)}catch(n){return $("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function cW(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(pr(),ur));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}async function gA(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??cW,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await zc(n,t,{headers:aW,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(iW.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(sW.test(p)&&!oW.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await mA(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof _t||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(s===null||s.textLength<200)&&s!==null){let u=am({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Vs(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>Vs(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await Vs(u.finalUrl,o);let p=await mA(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=am({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 _t)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=l instanceof Error?l.message:`HTTP ${c??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${c??"error"}).`)}var oW,sW,iW,aW,hA=g(()=>{"use strict";Mk();cm();pm();fe();oW=/(text\/html|application\/xhtml\+xml)/i,sW=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,iW=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,aW={"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 uW(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(lW,{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),dW),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=ne(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function yA(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?uW({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 bA(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
214
|
+
${dt(t,{headless:e,latched:n})}`,{cause:t})}var Gk,wj,Sj,Kk,kj,gm=g(()=>{"use strict";Gk=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],wj="pnpm exec playwright install chromium",Sj=4;kj="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 lr from"node:fs";import Yc from"node:path";import{randomBytes as Aj}from"node:crypto";import{chromium as _j}from"playwright";function Tj(){try{return"5.119.3"}catch{}try{let t=Yc.resolve(import.meta.dirname,"../../../package.json"),e=lr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Ej,Qc,Xk=g(()=>{"use strict";gm();H();fe();Ej=Tj(),Qc=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=_j.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=mm(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(c){s=c,await a.abort("blockedbyclient")}});let i=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",i,{once:!0});try{let a=await o.newPage(),c;try{c=await a.goto(e,{timeout:n.timeoutMs,waitUntil:n.waitUntil})}catch(p){throw s??p}if(s!==void 0)throw s;let l=await a.content();if(s!==void 0)throw s;let d=a.url(),u=c!==null?c.status():null;return{html:l,finalUrl:d,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",i),await o.close().catch(()=>{})}}getConsoleErrorCount(e){return this.sessions.get(e)?.consoleErrors??0}getLastHttpStatus(e){return this.sessions.get(e)?.lastHttpStatus??null}hasOpenDialog(e){return this.sessions.get(e)?.openDialog!==void 0}async dismissDialog(e,n=!0){let r=this.sessions.get(e);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(e){this.clearLaunchFailure();let n=this.sessions.get(e);n!==void 0&&(this.sessions.delete(e),await this.saveStorageState(this.config.defaultProfile,n.context),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.clearLaunchFailure(),this.shutdownComplete)return;this.shutdownComplete=!0;let e=[...this.sessions.keys()];if(await Promise.all(e.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${Ej}`}}loadStorageState(e){let n=Rp(e);try{if(!lr.existsSync(n))return;let r=JSON.parse(lr.readFileSync(n,"utf8"));return $("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){$("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Rp(e);if(!lr.existsSync(r))return;let o=await n.storageState(),s=Yc.join(Yc.dirname(r),`.${Yc.basename(r)}.${process.pid}.${Aj(4).toString("hex")}.tmp`);lr.writeFileSync(s,JSON.stringify(o),{mode:384}),lr.chmodSync(s,384),lr.renameSync(s,r),$("[browser/vault] saved session",{profile:e,file:r})}catch(r){$("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as Rj}from"crypto";function zk(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&xj.test(t.label))}function Vk(t){return Rj("sha256").update(t,"utf8").digest("hex").slice(0,8)}function Jk(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var xj,Zc=g(()=>{"use strict";xj=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as Ij}from"node:crypto";function Cj(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Pj(t,e,n){return`el_${Ij("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function Mj(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function Yk(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Zk(t,e){let n=t.role??"",r=t.name??"";Qk.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])Zk(s,e)}async function Oj(t){return t.evaluate(e=>{let n=Array.from(document.querySelectorAll(e)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let d=window.getComputedStyle(i);if(d.display==="none"||d.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),c=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a==="input"?o.type||null:o.getAttribute("type");r.push({name:c,tagName:a,type:l,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},eA).catch(()=>[])}async function Dj(t){return t.evaluate(e=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(e)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",c=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),l=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?l="checkbox":h==="radio"?l="radio":h==="button"||h==="submit"||h==="reset"?l="button":h==="search"?l="searchbox":l="textbox"}if(!l)continue;let d="value"in s?s.value:void 0,u=d!==void 0?String(d):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,m={role:l,name:c,disabled:p};u!==void 0&&(m.value=u),f!==void 0&&(m.checked=f),o.push(m)}return o},eA).catch(()=>[])}function Fj(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function el(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=Fj(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Oj(t),c=t.evaluate(()=>document.body?.innerText??"").catch(()=>""),l=Promise.resolve(t.url()),d=t.title().catch(()=>""),[u,p,f,m,h]=await Promise.all([i,a,c,l,d]),y,w=!1;u!==null?(y=[],Zk(u,y)):(o.push("observation skipped accessibility tree (returned null)"),w=!0,y=(await Dj(t)).filter(L=>Qk.has(L.role??"")));let A=new Map;for(let I of p){let L=Yk(I.name),z=A.get(L);(!z||z.bbox.w===0&&I.bbox.w>0)&&A.set(L,I)}let _=y.map(I=>({ax:I,dom:A.get(Yk(I.name??""))})),k=r?_:_.filter(I=>I.dom?I.dom.bbox.w>0||I.dom.bbox.h>0:!0);k.sort((I,L)=>{let z=I.dom?.bbox.y??0,P=L.dom?.bbox.y??0;if(z!==P)return z-P;let B=I.dom?.bbox.x??0,N=L.dom?.bbox.x??0;return B-N}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((I,L)=>{let z=I.ax.role??"generic",P=I.ax.name??"",B=Pj(z,P,L),N=I.dom?.bbox??{x:0,y:0,w:0,h:0},M=I.dom?.type??null,U=null;I.ax.value!==void 0&&I.ax.value!==null&&(U=String(I.ax.value)),I.ax.checked!==void 0&&(U=String(I.ax.checked)),zk({role:z,kind:M})&&(U="[redacted]");let j={disabled:I.ax.disabled??!1};I.ax.checked!==void 0&&(j.checked=I.ax.checked===!0||I.ax.checked==="mixed"),I.ax.selected!==void 0&&(j.selected=I.ax.selected),I.ax.expanded!==void 0&&(j.expanded=I.ax.expanded);let J;I.dom?.testId?J=`[data-testid="${I.dom.testId}"]`:I.dom?.id&&(J=`#${I.dom.id}`);let te={id:B,role:z,label:Cj(P),kind:M,value:U,state:j,bbox:N};return J!==void 0&&(te.selector=J),te}),C="idle";try{let I=await t.evaluate(()=>document.readyState);I==="loading"?C="loading":I==="interactive"?C="navigating":C="idle"}catch{C="navigating"}C!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),w&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let x=Mj(f),S=`obs_${e.observationCounter.toString(36)}`,R=new Date().toISOString();return{observationId:S,url:m,title:h,textSummary:x,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:C,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:R}}var Qk,eA,tA=g(()=>{"use strict";Zc();Qk=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);eA="a[href], button, input, select, textarea, [role], [tabindex], label"});async function nA(t,e){try{let n=await t.nth(e).evaluate(i=>{let a=i,c=a.getAttribute("role")??a.tagName.toLowerCase(),l=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",d=a.getBoundingClientRect();return{role:c,label:l,x:Math.round(d.x),y:Math.round(d.y),w:Math.round(d.width),h:Math.round(d.height)}}),r=`${n.role}:${n.label}:${e}`,o=0;for(let i=0;i<r.length;i++)o=o*31+r.charCodeAt(i)>>>0;return{id:`el_${o.toString(16).padStart(6,"0").slice(0,6)}`,role:n.role,label:n.label,kind:null,value:null,state:{disabled:!1},bbox:{x:n.x,y:n.y,w:n.w,h:n.h}}}catch{return null}}async function hm(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>nA(t,s)))).filter(o=>o!==null)}async function Lj(t){let e=new Set,n=[];for(let{loc:r,count:o}of t)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let c=a,l=c.getBoundingClientRect();return`${c.tagName}@${Math.round(l.x)},${Math.round(l.y)}`})}catch{continue}e.has(i)||(e.add(i),n.push({key:i,locator:r,index:s}))}return n}async function ym(t,e,n){switch(e.kind){case"element_id":return Nj(t,e,n);case"selector":return Uj(t,e);case"semantic":return $j(t,e)}}async function Nj(t,e,n){let r=n.get(e.elementId);if(r===void 0)return{outcome:"not_found",query:e};if(r.selector!==void 0){let c=t.locator(r.selector);if(await c.count()===1)return{outcome:"resolved",locator:c}}let o=t.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:e};if(s===1)return{outcome:"resolved",locator:o};let i=await hm(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Uj(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 hm(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function $j(t,e){return e.role!==void 0?Bj(t,e.text,e.role):Hj(t,e.text,e)}async function Bj(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 hm(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Hj(t,e,n){let r=t.getByRole("button",{name:e}),o=t.getByRole("link",{name:e}),s=t.getByLabel(e,{exact:!1}),[i,a,c]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+c===0)return{outcome:"not_found",query:n};let d=[];i>0&&d.push({loc:r,count:i}),a>0&&d.push({loc:o,count:a}),c>0&&d.push({loc:s,count:c});let u=await Lj(d);if(u.length===0)return{outcome:"not_found",query:n};if(u.length===1){let h=u[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=u.slice(0,5),f=[];for(let h=0;h<p.length;h++){let y=p[h];if(y===void 0)continue;let w=await nA(y.locator,y.index);if(w!==null){let A=`${w.role}:${w.label}:${h}`,_=0;for(let k=0;k<A.length;k++)_=_*31+A.charCodeAt(k)>>>0;f.push({...w,id:`el_${_.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var rA=g(()=>{"use strict"});async function bm(t,e,n,r){let o=t.url();if(o===n)return null;let s=Vc(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 oA=g(()=>{"use strict";Jc()});import{randomBytes as jj}from"crypto";import{mkdir as Wj,stat as Kj,writeFile as Gj}from"fs/promises";import{join as wm}from"path";import{gzip as qj}from"zlib";import{promisify as Xj}from"util";function zj(t){return wm(It(t),"browser")}function Vj(t){return wm(zj(t),"screenshots")}function Jj(){return new Date().toISOString().replace(/[:.]/g,"-")}function Yj(){return jj(3).toString("hex")}async function Sm(t,e,n){if(e.length>sA)throw new Error(`writeScreenshotSidecar: buffer exceeds ${sA} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=Vj(t);await Wj(r,{recursive:!0});let o=`${Jj()}-${Yj()}-${n}.png`,s=wm(r,o);await Gj(s,e);let{size:i}=await Kj(s);return{path:s,bytes:i}}var bre,sA,iA=g(()=>{"use strict";H();Zc();bre=Xj(qj);sA=5*1024*1024});var cA={};wp(cA,{PlaywrightProvider:()=>vm});function aA(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 vm,lA=g(()=>{"use strict";Xk();tA();rA();Jc();oA();iA();vm=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Qc(e)}async open(e){let n=Vc(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let{sessionId:r}=e,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(e.url,{timeout:e.timeoutMs??3e4,waitUntil:e.waitFor??"load"})}catch(u){a=u}let c=o.url();if(!(a!==null&&(c===""||c==="about:blank"))){let u=await bm(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 el(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 el(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 ym(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${aA(e.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:c}=a,l=null,d=async()=>{switch(e.action){case"click":await c.click({timeout:i});break;case"fill":await c.fill(e.value??"");break;case"press":await c.press(e.value??"");break;case"select":await c.selectOption(e.value??"");break;case"hover":await c.hover({timeout:i});break;case"scroll_to":await c.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await c.waitFor({timeout:i,state:"visible"});break}};try{await d()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await d()}catch(y){l=y}else l=h}let u=await bm(r,this.config,s,()=>this.close({sessionId:n}));if(u!==null)return u;let p=null;(e.screenshot===!0||l!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await el(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),m=`browser_act:${e.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,m),l!==null)throw l;return f}async render(e){return this.launcher.renderHtml(e.url,{timeoutMs:e.timeoutMs??3e4,waitUntil:e.waitFor??"load",signal:e.signal,requestGuard:e.requestGuard})}async screenshot(e){let{sessionId:n}=e,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(e.target!==void 0){let d=await ym(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${aA(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 Sm(n,s,"browser_screenshot"),c=0,l=0;if(e.fullPage===!0)try{let d=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));c=d.w,l=d.h}catch{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}else{let d=r.viewportSize();c=d?.width??0,l=d?.height??0}return{path:i,bytes:a,width:c,height:l,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(e){throw new Error("browser_extract not implemented in Phase 1")}async close(e){await this.launcher.closeSession(e.sessionId),this.sessions.delete(e.sessionId)}describe(e){let n=this.sessions.get(e);if(n===void 0)return null;let r=this.launcher.getPage(e);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(e){let n=this.sessions.get(e);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(e,r),r}updateSessionFromObservation(e,n,r,o,s){e.knownElements=new Map(n.map(i=>[i.id,i])),e.currentUrl=r,e.currentTitle=o,e.lastAction=s,e.lastActionAt=new Date().toISOString()}async captureScreenshot(e,n,r){try{let o=await e.screenshot({fullPage:!1}),{path:s}=await Sm(n,o,r);return s}catch{return null}}}});var ur={};wp(ur,{__resetBrowserRegistryForTests:()=>nW,browserProviderActive:()=>eW,closeBrowserProvider:()=>km,getBrowserProvider:()=>Zj,peekBrowserProvider:()=>tW});function dA(){Promise.resolve(km()).then(()=>{process.exit(130)})}function uA(){Promise.resolve(km()).then(()=>{process.exit(143)})}function pA(){$t=null}function Qj(){tl||(process.on("SIGINT",dA),process.on("SIGTERM",uA),process.on("exit",pA),tl=!0)}function fA(){tl&&(process.removeListener("SIGINT",dA),process.removeListener("SIGTERM",uA),process.removeListener("exit",pA),tl=!1)}async function Zj(t){return $t!==null?$t:(dr!==null||(dr=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(lA(),cA)),n=Wk(t),r=new e(n);return Qj(),$t=r,dr=null,r})()),dr)}async function km(){if($t===null)return;let t=$t;$t=null,dr=null,fA(),await t.shutdown()}function eW(){return $t!==null}function tW(){return $t}function nW(){$t=null,dr=null,fA()}var $t,dr,tl,pr=g(()=>{"use strict";Jc();$t=null,dr=null,tl=!1});async function mA(t,e){try{return await Pk(t,e)}catch(n){return $("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function cW(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(pr(),ur));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}async function gA(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??cW,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await zc(n,t,{headers:aW,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(iW.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(sW.test(p)&&!oW.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await mA(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof _t||u instanceof Error&&u.message.startsWith("web_scrape markdown mode received binary"))throw u;l=u}if(!(s===null||s.textLength<200)&&s!==null){let u=am({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Vs(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>Vs(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await Vs(u.finalUrl,o);let p=await mA(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=am({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 _t)throw u;if(s===null){let p=u instanceof Error?u.message:String(u),f=l instanceof Error?l.message:`HTTP ${c??"error"}`,m=new Error(`web_scrape could not retrieve ${t}: fetch failed (${f}) and render failed (${p}).`);throw m.cause=u,m}}if(s!==null)return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${t} (HTTP ${c??"error"}).`)}var oW,sW,iW,aW,hA=g(()=>{"use strict";Mk();cm();pm();fe();oW=/(text\/html|application\/xhtml\+xml)/i,sW=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,iW=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,aW={"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 uW(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(lW,{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),dW),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=ne(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function yA(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?uW({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 bA(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 lW,dW,wA=g(()=>{"use strict";At();lW="https://api.exa.ai/search",dW=10});function nl(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 fr=g(()=>{"use strict";gm()});function yW(t){if(!t||typeof t!="object")return{error:"Invalid input: expected an object"};let e=t,n=e.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof e.query!="string"||e.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=e.query}else{if(typeof e.url!="string"||e.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let c;try{c=new URL(e.url)}catch{return{error:`Invalid input: "${e.url}" is not a valid absolute URL`}}if(c.protocol!=="http:"&&c.protocol!=="https:")return{error:`Invalid input: protocol "${c.protocol}" not supported (http/https only)`};o=c.toString()}let i=pW;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,fW)}let a=mW;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,gW)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Am(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:Yt(t,e),truncated:!0}}function bW(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=yW(o);if("error"in i)return{content:i.error,isError:!0};if(s.aborted){let u=s.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let a=new AbortController,c=()=>{a.abort(s.reason)},l,d=()=>{let u=a.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(s.addEventListener("abort",c,{once:!0}),l=setTimeout(()=>{a.abort(new Error(`web_scrape timeout after ${i.timeoutMs}ms`))},i.timeoutMs),i.url!==void 0){let p=await um(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 h={method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:a.signal};p=await zc(e,i.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:h instanceof _t?{content:`web_scrape blocked: ${h.message}`,isError:!0}:{content:`web_scrape network error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}if(!p.ok)return{content:`web_scrape HTTP ${p.status} ${p.statusText||""}`.trimEnd()+` for ${i.url}`,isError:!0};let f;try{f=await p.text()}catch(h){return{content:`web_scrape read error: ${h instanceof Error?h.message:String(h)}`,isError:!0}}let m=Am(f,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let p=await gA(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=Am(Ok(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 _t)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),m=We(p)&&!fm(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${Js()}\`)`:"";return{content:`web_scrape markdown error: ${f}${m}`,isError:!0}}let u=yA({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:hW,timeoutMs:i.timeoutMs,signal:a.signal}),f=Am(bA(i.query,p),i.maxBytes);return{content:f.content,...f.truncated?{truncated:!0}:{}}}catch(p){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${p instanceof Error?p.message:String(p)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),s.removeEventListener("abort",c)}}}var pW,fW,mW,gW,hW,SA,vA=g(()=>{"use strict";hA();wA();pm();yn();cm();fr();pW=3e4,fW=12e4,mW=1e5,gW=1e6,hW=10;SA=bW()});import{existsSync as AA,mkdirSync as wW,readFileSync as SW,renameSync as vW,unlinkSync as kW,writeFileSync as AW}from"node:fs";import{dirname as kA,join as _W}from"node:path";import{randomBytes as TW}from"node:crypto";function eo(t){let e=t??Ap();if(!AA(e))return[];try{let n=SW(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 rl(t,e){let n=e??Ap();wW(kA(n),{recursive:!0});let r=_W(kA(n),`.schedules.json.${process.pid}.${TW(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{AW(r,o,"utf-8"),vW(r,n)}catch(s){try{AA(r)&&kW(r)}catch{}throw s}}function _A(t,e){let n=eo(e),r=n.map(c=>c.id),o=EW(t.name),s=RW(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),rl(n,e),a}function TA(t,e){let n=eo(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(rl(o,e),!0)}function EA(t,e){return eo(e).find(n=>n.id===t)}function EW(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function RW(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}var RA=g(()=>{"use strict";H()});import{existsSync as xW,readFileSync as IW}from"node:fs";import{join as CW}from"node:path";async function Ys(t,e,n){let r;try{let o=CW(Fb("default"),"port");if(!xW(o))return{synced:!1,detail:"daemon-not-detected (no port file)"};let s=IW(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 _m,xA=g(()=>{"use strict";H();_m="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 PW}from"node:fs";import{readFile as MW}from"node:fs/promises";var IA,CA,PA,MA,OA=g(()=>{"use strict";RA();H();xA();IA=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=_A({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 Ys("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 Ys("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:_m}})}},CA=async(t,e)=>{let n=eo();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})))}},PA=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=ka();if(!PW(s))return{content:JSON.stringify([])};let i;try{let l=await MW(s);i=(l.length>1048576?l.subarray(l.length-1048576):l).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
|
|
@@ -1003,7 +1003,7 @@ ${y}`:c,sessionId:this.initSessionId},yield*this.finishTurn(p!==null?{...a,stopR
|
|
|
1003
1003
|
|
|
1004
1004
|
`+a})}if(r!==null){let a=r===Rt?Td:jl;o.push({role:"user",content:a})}let s=r!==null?void 0:this.activeOpenAITools(),i={controller:e,traceWriter:this.traceWriter,initSessionId:this.initSessionId,currentModel:this.currentModel,isClosed:()=>this.closed};if(this.wireMode==="responses"){let a=this.opts.auth.source==="chatgpt-oauth";if(a&&cd(this.currentModel))return yield{type:"error",error:new Error(`Model "${this.currentModel}" can't run on a ChatGPT subscription \u2014 the ChatGPT/Codex backend only supports OpenAI gpt-5.x models. This usually means a subagent or skill requested a Claude model. Pass a gpt-5.x model to it (e.g. model: "gpt-5.5"); for an auto-dispatched agent you can't pass a model to (e.g. git-investigator), set AFK_DEFAULT_SUBAGENT_MODEL to a gpt-5.x id. Or run it on a provider configured with the matching API key.`)},null;let c=fd({model:this.currentModel,messages:o,activeTools:s,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort,isChatGptBackend:a});return yield*ih(i,{createStream:async l=>await this.client.responses.create(c,{signal:l}),translate:(l,d)=>ad(l,d,this.initSessionId),clarifyError:l=>this.clarifyResponsesError(l,a)})}else{let a=XR({model:this.currentModel,messages:o,activeTools:s,maxOutputTokens:this.opts.config.maxOutputTokens,effort:this.opts.config.effort});return yield*ih(i,{createStream:async c=>await this.client.chat.completions.create(a,{signal:c}),translate:(c,l)=>AR(c,l,this.initSessionId),clarifyError:c=>c instanceof Error?c:new Error(String(c))})}}async*dispatchAndAppend(e,n,r){return yield*ex({state:e,signal:n,vision:r,toolDispatcher:this.toolDispatcher,traceWriter:this.traceWriter,priorTurns:this.priorTurns,sessionId:this.initSessionId,subagentId:this.opts.config.subagentId})}async interrupt(e="interrupted"){this.abort.requestAbort(e)}async compact(){let e=await this.compactHistory("manual");return e.compacted&&(this.lastUsage=null),e}async compactHistory(e){let n=this.priorTurns.length;if(this.opts.auth.apiKey===null)return{compacted:!1,reason:"no-usable-auth",messagesBefore:n,messagesAfter:n};if(this.wireMode==="responses"&&this.responsesCompactionUnavailable){let s=bo(v.AFK_MICROCOMPACT_TOOL_RESULT_BYTES,v.AFK_MICROCOMPACT_KEEP_LAST),{blocksCleared:i,bytesReclaimed:a}=Vg(this.priorTurns,s);return i>0?{compacted:!1,reason:"microcompacted",messagesBefore:n,messagesAfter:this.priorTurns.length,microcompaction:{blocksCleared:i,bytesReclaimed:a}}:{compacted:!1,reason:"responses-compaction-unavailable",messagesBefore:n,messagesAfter:n}}let r=v.AFK_COMPACT_MODEL??this.currentModel,o=Ss(_e(this.lastUsage??{}),Jt(this.currentModel));return BR({priorTurns:this.priorTurns,usedFraction:o,shrinkAtFraction:$R(),summarize:(s,i)=>this.wireMode==="responses"?this.summarizeViaResponses(s,i,r):gd({client:this.client,model:r,system:hi,user:wi(s),maxTokens:1024,signal:i}),isClosed:this.closed,isIdle:this.abort.isIdle(),beginAbort:()=>this.abort.begin(),clearAbort:s=>this.abort.clear(s),trigger:e,traceWriter:this.traceWriter})}async summarizeViaResponses(e,n,r){try{return await VR({client:this.client,model:r,system:hi,user:wi(e),isChatGptBackend:this.opts.auth.source==="chatgpt-oauth",maxTokens:1024,signal:n})}catch(o){if(!n.aborted&&dx(o)){this.responsesCompactionUnavailable=!0;let s=Cn(o);G(this.traceWriter,{phase:"compaction_disabled",metadata:{wire:"responses",reason:"responses-compaction-unavailable",error:o instanceof Error?o.message:String(o),...s!==void 0?{status:s}:{}}})}throw o}}async setModel(e){e!==void 0&&(this.currentModel=Ae(e)??e)}async setPermissionMode(e){this.currentPermissionMode=Jg(e);let n=bt(this.currentPermissionMode);this.toolDispatcher?.setAllowAll?.(n),this.onPermissionMode?.(this.currentPermissionMode)}setCwd(e){this.toolDispatcher?.setResolveBase?.(e),this.onCwdChange?.(e)}async supportedCommands(){return nd()}async supportedModels(){return[{value:"gpt-5.6",displayName:"GPT-5.6 (Sol)",description:"OpenAI flagship \u2014 alias for gpt-5.6-sol"},{value:"gpt-5.6-sol",displayName:"GPT-5.6 Sol",description:"Frontier capability"},{value:"gpt-5.6-terra",displayName:"GPT-5.6 Terra",description:"Balanced intelligence/cost"},{value:"gpt-5.6-luna",displayName:"GPT-5.6 Luna",description:"Fast, high-volume workloads"},{value:"gpt-5.5",displayName:"GPT-5.5",description:"Prior flagship (ChatGPT backend)"},{value:"gpt-4o",displayName:"GPT-4o",description:"OpenAI flagship multimodal"},{value:"gpt-4o-mini",displayName:"GPT-4o mini",description:"Fast/cheap GPT-4o"},{value:"gpt-4.1",displayName:"GPT-4.1",description:"Long-context GPT-4"},{value:"gpt-4.1-mini",displayName:"GPT-4.1 mini",description:"Fast 4.1 variant"},{value:"o1",displayName:"o1",description:"Reasoning model"},{value:"o1-mini",displayName:"o1 mini",description:"Fast reasoning"},{value:"o3-mini",displayName:"o3 mini",description:"Newer reasoning, faster"}]}async supportedAgents(){return[]}async getContextUsage(){let e=this.lastUsage,n=yt(this.currentModel),r;if(e&&n>0){let i=_e(e);r=Math.min(100,Math.max(0,i/n*100))}let{totalTokens:o,apiUsage:s}=bs(e);return{tools:[],agents:[],isAutoCompactEnabled:this.autoCompactThreshold!==void 0,apiUsage:s,totalTokens:o,...r!==void 0?{percentage:r}:{},maxTokens:n}}async mcpServerStatus(){return this.opts.mcpManager?this.opts.mcpManager.getServerStates().map(e=>({name:e.serverName,status:e.status})):[]}async accountInfo(){return{authSource:this.opts.auth.source}}async rewindFiles(e,n){return{canRewind:!1,error:`${ah} provider does not support file checkpoint rewind yet.`}}close(){this.closed=!0,this.abort.requestAbort("closed"),this.abort.markClosed(),$(`\u{1F7E2} ${ah}: closed`)}}});var lh,Ie,E2,ko=g(()=>{"use strict";_l();wc();Pc();lc();Hr();Ym();hr();at();Ct();Cg();xn();ch();hd();Le();ig();fi();ch();lh="openai-compatible",Ie=class{name=lh;providerOpts;memoryStore;schemas;_defaultHeaders;_sharedReadRoots;_sharedWriteRoots;_currentPermissionMode="default";_initialResolveBase;_presenceSessionId=null;_mintedSessionId=null;constructor(e={}){this.providerOpts=e,this._defaultHeaders=e.defaultHeaders,this.memoryStore=e.memoryStore??new Xe;let n=[...Ft];e.subagentExecutor&&n.push(e.subagentExecutor.describeAgentTool?.()??Qe),e.skillExecutor&&n.push(tr),e.composeExecutor&&n.push(nr),e.readOnlyMemory===!0?n.push(Mr):n.push(...pn),n.push(St);for(let r of e.customTools??[])n.some(o=>o.name===r.schema.name)||n.push(r.schema);this.schemas=n}setEndpointDefaults(e){e.baseURL!==void 0&&(this.providerOpts.baseURL=e.baseURL),e.defaultHeaders!==void 0&&(this._defaultHeaders=e.defaultHeaders)}query(e){let n=e.config,r=n.permissionMode??"default";this._currentPermissionMode=r,this.ensureSharedRoots(n.cwd),n.readRoots&&this._sharedReadRoots&&this._sharedReadRoots.length<=1&&(this._sharedReadRoots.length=0,this._sharedReadRoots.push(...n.readRoots)),n.writeRoots&&this._sharedWriteRoots&&this._sharedWriteRoots.length<=1&&(this._sharedWriteRoots.length=0,this._sharedWriteRoots.push(...n.writeRoots));let o,s=typeof n.model=="string"?n.model:String(n.model),i=n.cwd??process.cwd(),a=Es({surface:this.providerOpts.surface??"cli",getCwd:()=>i,modelName:s,providerName:lh,permissionMode:r,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},...n.phaseRole!==void 0?{phaseRole:n.phaseRole}:{},getEnabledToolNames:()=>o instanceof Lt?o.toolDefs.map(k=>k.name):[],getMcpTools:()=>this.providerOpts.mcpManager?.getMcpTools()??[],getSubagents:()=>this.providerOpts.subagentExecutor?this.providerOpts.subagentExecutor.getSubagentsLite():{active:[],backgroundJobs:[]}});o=this.providerOpts.tools?Rs(this.providerOpts.tools,a):this.buildDispatcher(r,{...n.cwd!==void 0?{cwd:n.cwd}:{},...this._sharedReadRoots!==void 0?{readRoots:this._sharedReadRoots}:{},...this._sharedWriteRoots!==void 0?{writeRoots:this._sharedWriteRoots}:{},...n.sessionId!==void 0?{sessionId:n.sessionId}:{},...n.parentSessionId!==void 0?{parentSessionId:n.parentSessionId}:{},...n.subagentId!==void 0?{subagentId:n.subagentId}:{},...n.subagentToolOutputCapBytes!==void 0?{subagentToolOutputCapBytes:n.subagentToolOutputCapBytes}:{},...n.traceWriter!==void 0?{traceWriter:n.traceWriter}:{},runtimeStateSource:a,...n.isSkillDispatch?{isSkillDispatch:!0}:{},...n.isNonInteractive?{isNonInteractive:!0}:{},...n.hookRegistry!==void 0?{hookRegistry:n.hookRegistry}:{},...n.planExitControls!==void 0?{planExitControls:n.planExitControls}:{}});let c=si({sessionId:n.sessionId,resume:n.resume,depth:n.depth,parentSessionId:n.parentSessionId,surface:this.providerOpts.surface??"cli",memoized:this._mintedSessionId});this._mintedSessionId=c.memoized;let l={};c.id!==void 0&&(l.sessionIdOverride=c.id);let d=n.openaiBaseUrl??this.providerOpts.baseURL;d!==void 0&&(l.baseURL=d),this._defaultHeaders!==void 0&&(l.defaultHeaders=this._defaultHeaders),l.toolDispatcher=o,l.onPermissionMode=k=>{this._currentPermissionMode=k},this.providerOpts.mcpManager!==void 0&&(l.mcpManager=this.providerOpts.mcpManager),this._presenceSessionId=ii({depth:n.depth,parentSessionId:n.parentSessionId,sessionId:c.id,currentPresenceSessionId:this._presenceSessionId,runtimeStateSource:a,surface:this.providerOpts.surface??"cli",cwd:n.cwd,providerName:lh,model:s});let u=ed(n.isSkillDispatch),p=td(this.providerOpts.readOnlyMemory),f=this.providerOpts.skillExecutor?Cd(void 0,{...typeof n.cwd=="string"&&n.cwd.length>0?{cwd:n.cwd}:{},...typeof n.skillDispatchName=="string"&&n.skillDispatchName.length>0?{excludeName:n.skillDispatchName}:{}}):"",m=typeof n.hotMemory=="string"?n.hotMemory:"",h=typeof n.systemPrompt=="string"?n.systemPrompt:void 0,y=k=>{let E=[u];return h!==void 0&&h.length>0&&E.push(h),E.push(p),m.length>0&&E.push(m),E.push(k),f.length>0&&E.push(f),E.join(`
|
|
1005
1005
|
|
|
1006
|
-
`)},w=()=>Ts({cwd:i,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:a.getWorkspace()}),A={...n,systemPrompt:y(w())},_=k=>{i=k,A.systemPrompt=y(w())};return l.onCwdChange=_,px(A,e.prompt,l)}buildDispatcher(e,n){let r=Sl(e,n.cwd),o=cs(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[d,u]of o)this.providerOpts.readOnlyMemory===!0&&d!=="memory_search"||r.set(d,u);n.runtimeStateSource&&r.set("get_runtime_state",Wr(n.runtimeStateSource));for(let d of this.providerOpts.customTools??[])r.has(d.schema.name)||r.set(d.schema.name,d.handler);let s=n.planExitControls;s&&r.set(pt,kl(s));let i=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[d,u]of this.providerOpts.mcpManager.getMcpHandlers())r.set(d,u);let a=n.isSkillDispatch?this.schemas.filter(d=>d.name!=="ask_question"&&d.name!=="terminal_font_size"):n.isNonInteractive?this.schemas.filter(d=>d.name!=="ask_question"):this.schemas,c={handlers:r,schemas:[...a,...i,...s?[vl]:[]],hookRegistry:Al(n.hookRegistry,this.providerOpts.hookRegistry)},l=bc(this.providerOpts.mcpManager?yc(this.providerOpts.permissions,this.providerOpts.mcpManager.getMcpToolWireNames()):this.providerOpts.permissions,(this.providerOpts.customTools??[]).map(d=>d.schema.name));return l!==void 0&&(c.permissions=l),this.providerOpts.subagentExecutor!==void 0&&(c.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(c.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(c.composeExecutor=this.providerOpts.composeExecutor),this.providerOpts.canUseTool!==void 0&&(c.canUseTool=this.providerOpts.canUseTool),n.cwd!==void 0&&(c.cwd=n.cwd),n.readRoots!==void 0&&(c.readRoots=n.readRoots),n.writeRoots!==void 0&&(c.writeRoots=n.writeRoots),n.sessionId!==void 0&&(c.sessionId=n.sessionId),n.parentSessionId!==void 0&&(c.parentSessionId=n.parentSessionId),n.subagentId!==void 0&&(c.subagentId=n.subagentId),n.subagentToolOutputCapBytes!==void 0&&(c.maxOutputBytes=n.subagentToolOutputCapBytes),n.traceWriter!==void 0&&(c.traceWriter=n.traceWriter),this.providerOpts.readOnlyBash===!0&&(c.readOnlyBash=!0),c.allowAll=bt(e),c.sessionGrantManager=this,new Lt(c)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e)}}grantManager=new hn({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>bt(this._currentPermissionMode)});addReadRoot(e,n="slash",r){this.grantManager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grantManager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grantManager.revokeRoot(e,n,r)}getGrants(){return this.grantManager.getGrants()}close(){this.memoryStore.close()}async complete(e){let n={model:e.model??"gpt-4o-mini",system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.apiKey!==void 0&&(n.apiKey=e.apiKey);let r=e.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),this._defaultHeaders!==void 0&&(n.defaultHeaders=this._defaultHeaders),e.signal&&(n.signal=e.signal),gd(n)}},E2=new Ie});function Mn(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}function Pd(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":Mn(R2,t)?"read":Mn(x2,t)?"write":Mn(I2,t)?"shell":Mn(fx,t)?"subagent":Mn(mx,t)?"skill":Mn(gx,t)?"dag":Mn(C2,t)?"web":P2.has(t)?"browser":Mn(M2,t)?"planning":O2.has(t)?"schedule":"other"}var R2,x2,I2,fx,mx,gx,Jpe,C2,P2,M2,O2,dh,hx,Ti=g(()=>{"use strict";Tc();R2=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness"]),x2=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","memory_update","procedure_write","terminal_font_size","config_set"]),I2=new Set(["Bash","BashOutput","KillBash","bash"]),fx=new Set(["Agent","Task","agent"]),mx=new Set(["Skill","skill"]),gx=new Set(["Compose","compose"]),Jpe=new Set([...fx,...gx,...mx]),C2=new Set(["WebFetch","WebSearch","send_telegram","web_scrape"]),P2=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),M2=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),O2=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);dh=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness",...Fe],hx=[...dh,"web_scrape","agent"]});function yx(t,e){return`Skill tool not available at nesting depth ${t} (max ${e}). ${uh}`}function bx(t,e){return`Agent tool not available at nesting depth ${t} (max ${e}). ${uh}`}function wx(t,e){return`Compose tool not available at nesting depth ${t} (max ${e}). ${uh}`}var uh,Md=g(()=>{"use strict";uh="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function Sx(t){return D2.has(t)}var D2,vx=g(()=>{"use strict";D2=new Set});function kx(t){for(let e of F2)e(t)}function Ax(t){for(let e of L2)e(t)}var F2,L2,_x=g(()=>{"use strict";F2=new Set,L2=new Set});function Od(t){return N2.has(t)}function Tx(t,e=U2){return t.length<=e?t:t.slice(0,e)+"\u2026"}function Ao(t){return t.surface!==void 0?{origin:dn(t.surface),actor:un(t.depth)}:{}}var N2,U2,ph=g(()=>{"use strict";Wn();N2=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","
|
|
1006
|
+
`)},w=()=>Ts({cwd:i,...n.sessionId!==void 0?{sessionId:n.sessionId}:{},surface:this.providerOpts.surface??"cli",...n.depth!==void 0?{depth:n.depth}:{},...n.maxDepth!==void 0?{maxDepth:n.maxDepth}:{},workspace:a.getWorkspace()}),A={...n,systemPrompt:y(w())},_=k=>{i=k,A.systemPrompt=y(w())};return l.onCwdChange=_,px(A,e.prompt,l)}buildDispatcher(e,n){let r=Sl(e,n.cwd),o=cs(this.memoryStore,void 0,this.providerOpts.surface??"cli");for(let[d,u]of o)this.providerOpts.readOnlyMemory===!0&&d!=="memory_search"||r.set(d,u);n.runtimeStateSource&&r.set("get_runtime_state",Wr(n.runtimeStateSource));for(let d of this.providerOpts.customTools??[])r.has(d.schema.name)||r.set(d.schema.name,d.handler);let s=n.planExitControls;s&&r.set(pt,kl(s));let i=this.providerOpts.mcpManager?this.providerOpts.mcpManager.getMcpTools():[];if(this.providerOpts.mcpManager)for(let[d,u]of this.providerOpts.mcpManager.getMcpHandlers())r.set(d,u);let a=n.isSkillDispatch?this.schemas.filter(d=>d.name!=="ask_question"&&d.name!=="terminal_font_size"):n.isNonInteractive?this.schemas.filter(d=>d.name!=="ask_question"):this.schemas,c={handlers:r,schemas:[...a,...i,...s?[vl]:[]],hookRegistry:Al(n.hookRegistry,this.providerOpts.hookRegistry)},l=bc(this.providerOpts.mcpManager?yc(this.providerOpts.permissions,this.providerOpts.mcpManager.getMcpToolWireNames()):this.providerOpts.permissions,(this.providerOpts.customTools??[]).map(d=>d.schema.name));return l!==void 0&&(c.permissions=l),this.providerOpts.subagentExecutor!==void 0&&(c.subagentExecutor=this.providerOpts.subagentExecutor),this.providerOpts.skillExecutor!==void 0&&(c.skillExecutor=this.providerOpts.skillExecutor),this.providerOpts.composeExecutor!==void 0&&(c.composeExecutor=this.providerOpts.composeExecutor),this.providerOpts.canUseTool!==void 0&&(c.canUseTool=this.providerOpts.canUseTool),n.cwd!==void 0&&(c.cwd=n.cwd),n.readRoots!==void 0&&(c.readRoots=n.readRoots),n.writeRoots!==void 0&&(c.writeRoots=n.writeRoots),n.sessionId!==void 0&&(c.sessionId=n.sessionId),n.parentSessionId!==void 0&&(c.parentSessionId=n.parentSessionId),n.subagentId!==void 0&&(c.subagentId=n.subagentId),n.subagentToolOutputCapBytes!==void 0&&(c.maxOutputBytes=n.subagentToolOutputCapBytes),n.traceWriter!==void 0&&(c.traceWriter=n.traceWriter),this.providerOpts.readOnlyBash===!0&&(c.readOnlyBash=!0),c.allowAll=bt(e),c.sessionGrantManager=this,new Lt(c)}ensureSharedRoots(e){if(!this._sharedReadRoots){let n=e?[e]:[];this._sharedReadRoots=n.slice(),this._sharedWriteRoots=n.slice(),e&&!this._initialResolveBase&&(this._initialResolveBase=e)}}grantManager=new hn({getReadRoots:()=>this._sharedReadRoots,getWriteRoots:()=>this._sharedWriteRoots,ensureInitialized:()=>this.ensureSharedRoots(),getProtectedRoot:()=>this._initialResolveBase,getAllowAll:()=>bt(this._currentPermissionMode)});addReadRoot(e,n="slash",r){this.grantManager.addReadRoot(e,n,r)}addWriteRoot(e,n="slash",r){this.grantManager.addWriteRoot(e,n,r)}revokeRoot(e,n="slash",r){this.grantManager.revokeRoot(e,n,r)}getGrants(){return this.grantManager.getGrants()}close(){this.memoryStore.close()}async complete(e){let n={model:e.model??"gpt-4o-mini",system:e.system,user:e.user,maxTokens:e.maxTokens??64};e.apiKey!==void 0&&(n.apiKey=e.apiKey);let r=e.baseUrl??this.providerOpts.baseURL;return r!==void 0&&(n.baseURL=r),this._defaultHeaders!==void 0&&(n.defaultHeaders=this._defaultHeaders),e.signal&&(n.signal=e.signal),gd(n)}},E2=new Ie});function Mn(t,e){if(t.has(e))return!0;let n=e.charAt(0).toUpperCase()+e.slice(1);return n!==e&&t.has(n)}function Pd(t){return t.startsWith("mcp__")||t.startsWith("MCP__")?"mcp":Mn(R2,t)?"read":Mn(x2,t)?"write":Mn(I2,t)?"shell":Mn(fx,t)?"subagent":Mn(mx,t)?"skill":Mn(gx,t)?"dag":Mn(C2,t)?"web":P2.has(t)?"browser":Mn(M2,t)?"planning":O2.has(t)?"schedule":"other"}var R2,x2,I2,fx,mx,gx,Jpe,C2,P2,M2,O2,dh,hx,Ti=g(()=>{"use strict";Tc();R2=new Set(["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness"]),x2=new Set(["Write","Edit","NotebookEdit","MultiEdit","write_file","edit_file","memory_update","procedure_write","terminal_font_size","config_set"]),I2=new Set(["Bash","BashOutput","KillBash","bash"]),fx=new Set(["Agent","Task","agent"]),mx=new Set(["Skill","skill"]),gx=new Set(["Compose","compose"]),Jpe=new Set([...fx,...gx,...mx]),C2=new Set(["WebFetch","WebSearch","send_telegram","web_scrape"]),P2=new Set(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),M2=new Set(["TaskCreate","TaskUpdate","TaskList","TaskGet","TaskOutput","TaskStop","EnterPlanMode","ExitPlanMode","ToolSearch"]),O2=new Set(["create_schedule","list_schedules","get_schedule_history","cancel_schedule"]);dh=["Read","Glob","Grep","NotebookRead","LS","read_file","glob","grep","list_directory","config_get","memory_search","read_witness","search_witness",...Fe],hx=[...dh,"web_scrape","agent"]});function yx(t,e){return`Skill tool not available at nesting depth ${t} (max ${e}). ${uh}`}function bx(t,e){return`Agent tool not available at nesting depth ${t} (max ${e}). ${uh}`}function wx(t,e){return`Compose tool not available at nesting depth ${t} (max ${e}). ${uh}`}var uh,Md=g(()=>{"use strict";uh="You are too deeply nested to delegate further \u2014 perform the work inline with your own tools instead of calling skill/agent/compose."});function Sx(t){return D2.has(t)}var D2,vx=g(()=>{"use strict";D2=new Set});function kx(t){for(let e of F2)e(t)}function Ax(t){for(let e of L2)e(t)}var F2,L2,_x=g(()=>{"use strict";F2=new Set,L2=new Set});function Od(t){return N2.has(t)}function Tx(t,e=U2){return t.length<=e?t:t.slice(0,e)+"\u2026"}function Ao(t){return t.surface!==void 0?{origin:dn(t.surface),actor:un(t.depth)}:{}}var N2,U2,ph=g(()=>{"use strict";Wn();N2=new Set(["ask-gate","fanout-pace","right-size-delegation","premise-gate","long-bash-gate","exploration-gate","irreversible-action-gate","safe-destruct","plan-probe"]);U2=240});function Ex(t){let e=[],n="",r=null,o=!1;for(let s of t){if(r!==null){s===r?r=null:n+=s;continue}if(s==='"'||s==="'"){r=s,o=!0;continue}if(/\s/.test(s)){o&&(e.push(n),n="",o=!1);continue}n+=s,o=!0}return o&&e.push(n),e}function On(t,e){let n=e??"",r;return t.replace(/(\\?)\$(ARGUMENTS?\b|\{(\d+)\})/g,(o,s,i,a)=>{if(s==="\\")return o.slice(1);if(i==="ARGUMENT"||i==="ARGUMENTS")return n;let c=Number(a);return c<1?o:(r??=Ex(n),r[c-1]??o)})}var Dd=g(()=>{"use strict"});function Rx(t,e,n){let r=n&&n.trim().length>0?n.trim():"(none)";return{content:`${`[Skill "${t}" loaded into your current context \u2014 act on it now]
|
|
1007
1007
|
The instructions below are your operating procedure for THIS task. Execute them immediately, in this session, using the tools you already have. This is an instruction set, not reference material: follow it directly \u2014 do not merely summarize or describe it. No sub-agent was forked; you are the one carrying it out.
|
|
1008
1008
|
Arguments: ${r}`}
|
|
1009
1009
|
|
|
@@ -1398,13 +1398,20 @@ A goal phrased as a question \u2014 "why does X keep happening", "how come Y", "
|
|
|
1398
1398
|
|
|
1399
1399
|
These skills fire automatically at specific points in the task lifecycle. Check each condition before the relevant phase begins.
|
|
1400
1400
|
|
|
1401
|
-
- **intent-lock** \u2014 before any multi-step work, scan the request for ambiguous referents ("the text", "her Y"), unverified characterizations ("the meeting is substantive"), identity assumptions (which contact = the user), code-vs-runtime dual referents, or no task statement at all (a bare path, URL, noun phrase, or pasted trace). Emit a one-sentence interpretation lock per finding and proceed; when multiple plausible reads gate an irreversible action, escalate to Asking on an interactive surface or Blocked without acting on a non-interactive surface.
|
|
1402
1401
|
- **ground-state** \u2014 before any non-trivial implementation (multi-file edits, new features, config changes, anything that writes), invoke the \`/ground-state\` skill to run a parallel reconnaissance wave for git state, infrastructure, and memory context. Do not settle for inline \`git status\` / \`get_runtime_state\` \u2014 those are serial and miss the memory/infra dimensions the skill triangulates.
|
|
1403
|
-
- **thesis-lock** \u2014 before drafting first-person analysis or recommendations, lock the thesis to a single sentence for async correction before building on it.
|
|
1404
1402
|
- **premise-gate** \u2014 during research and analysis, check named-entity and status-claim pairs before acting on them.
|
|
1405
1403
|
|
|
1406
1404
|
Routing hints are checks, not ceremonies. Skip when the condition is trivially absent.
|
|
1407
1405
|
|
|
1406
|
+
## Behavioral checks
|
|
1407
|
+
|
|
1408
|
+
These are inline behaviors \u2014 follow them directly, do not invoke a skill.
|
|
1409
|
+
|
|
1410
|
+
- **intent-lock** \u2014 before any multi-step work, scan the request for ambiguous referents ("the text", "her Y"), unverified characterizations ("the meeting is substantive"), identity assumptions (which contact = the user), code-vs-runtime dual referents, or no task statement at all (a bare path, URL, noun phrase, or pasted trace). Emit a one-sentence interpretation lock per finding and proceed; when multiple plausible reads gate an irreversible action, escalate to Asking on an interactive surface or Blocked without acting on a non-interactive surface.
|
|
1411
|
+
- **thesis-lock** \u2014 before drafting first-person analysis or recommendations, lock the thesis to a single sentence for async correction before building on it.
|
|
1412
|
+
- **reground** \u2014 before extrapolating, composing, or synthesizing on top of a previous sub-agent's findings within the same conversation, reread at least one file the sub-agent cited in the main path. Tag every extrapolated claim that extends beyond the reread as [UNVERIFIED] naming what source would ground it. The sub-agent's prose is not a primary source \u2014 the files it cited are.
|
|
1413
|
+
- **exploration-gate** \u2014 when a session's goal is understanding-first (explore, explain, understand, figure out, walk me through) and no deliverable was explicitly named, do not pressure toward commits or file edits at session end. "No commit" is not failure on an exploration session.
|
|
1414
|
+
|
|
1408
1415
|
## Priorities
|
|
1409
1416
|
|
|
1410
1417
|
Ordered. Higher wins on conflict.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-afk",
|
|
3
|
-
"version": "5.119.
|
|
3
|
+
"version": "5.119.3",
|
|
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",
|
|
@@ -1,119 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: intent-lock
|
|
3
|
-
description: "Fires before multi-step work when the user's request contains ambiguous referents ('the text', 'her Y'), characterizations of unverified entities ('the meeting is substantive'), identity assumptions (which contact = the user), code-vs-runtime dual referents, or no task statement at all (a bare path, URL, noun phrase, or pasted trace). Emits a one-sentence interpretation lock for fast async correction; escalates when interpretation gates an irreversible action AND multiple plausible reads exist."
|
|
4
|
-
context: load
|
|
5
|
-
---
|
|
6
|
-
|
|
7
|
-
## When to invoke
|
|
8
|
-
|
|
9
|
-
Check for these signal classes before starting any multi-step task:
|
|
10
|
-
|
|
11
|
-
**Ambiguous referents** — a noun phrase that could resolve to more than one entity in context:
|
|
12
|
-
- Bare demonstratives with no prior binding: "the text", "the doc", "that email", "the file"
|
|
13
|
-
- Possessives pointing to unintroduced people: "her draft", "their proposal", "his calendar"
|
|
14
|
-
- Ordinals with unclear basis: "the first one", "the latest version", "the other branch"
|
|
15
|
-
|
|
16
|
-
**Unverified characterizations** — a status or quality claim about a named entity the agent cannot confirm:
|
|
17
|
-
- "The meeting is substantive" (agent has not read the meeting)
|
|
18
|
-
- "The PR is approved" (agent has not checked)
|
|
19
|
-
- "The last run passed" (agent has not run or read CI output)
|
|
20
|
-
|
|
21
|
-
**Identity assumptions** — who is "the user", "me", "us", "the team", or a named person when the identity matters for action:
|
|
22
|
-
- Sending to "me" when multiple contact entries exist
|
|
23
|
-
- Filing under "my account" when credentials are ambiguous
|
|
24
|
-
- "The owner" when ownership is not established in context
|
|
25
|
-
|
|
26
|
-
**Code-vs-runtime dual referent** — a term that names an entity in the active codebase AND a model runtime concept. Fires when the user is working on a tool whose vocabulary mirrors the agent's own runtime (parity-mirror projects like agent CLIs, plugin frameworks, or harness tooling):
|
|
27
|
-
- "memory" — the project's memory store OR the agent's own session memory
|
|
28
|
-
- "session" — a project's session class OR the agent's conversation
|
|
29
|
-
- "hooks" — the project's hook registry OR the agent's tool-use hooks
|
|
30
|
-
- "agent" / "subagent" — the project's agent abstraction OR the agent dispatching them
|
|
31
|
-
- "tool" / "skill" / "plugin" — the project's loadable units OR the agent's available tools
|
|
32
|
-
- "MCP" / "terminal" / "REPL" — primitives the project implements that the agent also has
|
|
33
|
-
|
|
34
|
-
**No task statement at all** — the request is a bare fragment with no imperative verb, so the referent to resolve is the *goal itself* rather than a noun inside it:
|
|
35
|
-
- A lone path, repo URL, or issue/PR link with no stated ask
|
|
36
|
-
- A bare noun phrase: "the 429s", "usage indicators", "that timeout"
|
|
37
|
-
- A continuation cue whose carried-over goal is not uniquely established: "same as before", "and the 429s?"
|
|
38
|
-
- A pasted error, log line, stack trace, or diff with no question attached
|
|
39
|
-
|
|
40
|
-
**Skip when:**
|
|
41
|
-
- Referent resolves unambiguously from immediately prior context (file was just read this turn, entity was named and confirmed, prior message established the binding).
|
|
42
|
-
- Request is reversible, exploratory, and any misread is immediately correctable without cost.
|
|
43
|
-
- User has already provided the interpretation explicitly ("I mean X by 'the text'", "agent-afk's memory", "my session", "this codebase's hooks").
|
|
44
|
-
- Single-step clarification would cost more than simply proceeding and correcting.
|
|
45
|
-
- Dual-referent term has no matching symbol in cwd — no parity risk, standard interpretation applies.
|
|
46
|
-
- Fragment's goal is fixed by the immediately prior turn (agent just proposed two options and the user named one) — the task statement carries over intact.
|
|
47
|
-
|
|
48
|
-
---
|
|
49
|
-
|
|
50
|
-
## Procedure
|
|
51
|
-
|
|
52
|
-
### Step 1 — Scan
|
|
53
|
-
|
|
54
|
-
Before acting, scan the request for signal classes above. List every ambiguous referent, unverified characterization, identity assumption, code-vs-runtime dual referent, or missing task statement found. If zero are found, skip this skill entirely.
|
|
55
|
-
|
|
56
|
-
**When the finding is a missing task statement**, reconstruct the candidate goal from ambient evidence before classifying it — recent commits, branch name, open diff, the named file's contents, the prior turn. Cite the evidence the reconstruction rests on, so a wrong read is visibly wrong rather than silently load-bearing. Resolve this in-context; dispatch one sub-agent with one focused reconstruction question only when in-context reasoning cannot produce a single confident reading, and do not permit a follow-up dispatch. The reconstructed goal is then classified by Step 2 exactly like any other finding.
|
|
57
|
-
|
|
58
|
-
### Step 2 — Classify each finding
|
|
59
|
-
|
|
60
|
-
For each finding, determine:
|
|
61
|
-
|
|
62
|
-
- **Plausible reads** — how many distinct interpretations exist given available context?
|
|
63
|
-
- **Gate type** — does this interpretation gate a reversible or irreversible action?
|
|
64
|
-
|
|
65
|
-
### Step 3 — Choose resolution mode
|
|
66
|
-
|
|
67
|
-
| Condition | Mode |
|
|
68
|
-
|-----------|------|
|
|
69
|
-
| Single plausible read, reversible action | **Lock** — emit interpretation, proceed |
|
|
70
|
-
| Single plausible read, irreversible action | **Lock** — emit interpretation, proceed (but flag) |
|
|
71
|
-
| Multiple plausible reads, reversible action | **Lock** — emit most-likely read with explicit note, proceed |
|
|
72
|
-
| Multiple plausible reads, irreversible action | **Asking** — stop, ask one question |
|
|
73
|
-
|
|
74
|
-
Use **Asking** only when the current surface can receive an answer. On a daemon, scheduled, one-shot, or other non-interactive surface, multiple plausible reads that gate an irreversible action require **Blocked** — take no action and record the exact question whose answer would unblock it.
|
|
75
|
-
|
|
76
|
-
**Multiple plausible reads** means two or more interpretations that would produce materially different outcomes. "the text" pointing to one of two equally recent documents = multiple. "the text" when only one document was discussed this session = single.
|
|
77
|
-
|
|
78
|
-
### Step 4 — Emit the lock
|
|
79
|
-
|
|
80
|
-
**Lock format (most cases):**
|
|
81
|
-
|
|
82
|
-
> Interpreting: [ambiguous phrase] → [resolved referent]. Proceeding on that basis — correct me if wrong.
|
|
83
|
-
|
|
84
|
-
One sentence. No preamble. Append to the start of the work output, not as a standalone turn. The user can correct asynchronously; work continues.
|
|
85
|
-
|
|
86
|
-
**Lock format (reconstructed goal):**
|
|
87
|
-
|
|
88
|
-
> Reading [fragment] as: [reconstructed task statement] (from [evidence]). Proceeding on that basis — correct me if wrong.
|
|
89
|
-
|
|
90
|
-
**If multiple locks needed:** stack them, one per line, before the work output.
|
|
91
|
-
|
|
92
|
-
**Asking format (irreversible + multiple reads only):**
|
|
93
|
-
|
|
94
|
-
> [One precise question that resolves the ambiguity.] (This determines [what action follows].)
|
|
95
|
-
|
|
96
|
-
One question. State what it unlocks. Do not proceed until answered.
|
|
97
|
-
|
|
98
|
-
---
|
|
99
|
-
|
|
100
|
-
## Interaction with other skills
|
|
101
|
-
|
|
102
|
-
**thesis-lock** fires on first-person thesis before drafting. Intent-lock fires on the user's *request* before any multi-step work. They are complementary: thesis-lock protects the agent's own claims; intent-lock protects the agent's reading of what the user asked.
|
|
103
|
-
|
|
104
|
-
**ground-state** fires before implementation to survey repo state. Intent-lock fires before *any* multi-step work on requests with ambiguous inputs — including non-implementation work like drafting, research, or messaging. They can both fire on the same request (ground-state runs after intent-lock resolves).
|
|
105
|
-
|
|
106
|
-
In agent-afk, the `ask_question` hook enforces the reachability rule; where that hook is absent, apply the rule inline. Never emit an unreachable question: on a non-interactive surface, proceed only on a safe assumption or end Blocked without acting when the next action is irreversible. **trajectory-check** is a user-scope skill that may not exist in this installation — reference it only if present, and never block on it. When a session-end goal-vs-execution check is wanted, invoke it with the locked statement from Step 4 as its canonical-goal input, not the original fragment. Do not reimplement that check here.
|
|
107
|
-
|
|
108
|
-
**premise-gate** checks named-entity and status-claim pairs during research and analysis. Intent-lock fires *before* work begins on the request itself. They address the same underlying hazard at different points in the pipeline: intent-lock at request intake, premise-gate during execution.
|
|
109
|
-
|
|
110
|
-
---
|
|
111
|
-
|
|
112
|
-
## Exit criteria
|
|
113
|
-
|
|
114
|
-
- Every ambiguous referent, unverified characterization, identity assumption, code-vs-runtime dual referent, and missing task statement is either locked (one-sentence interpretation emitted), escalated to Asking, or ended Blocked on a non-interactive surface.
|
|
115
|
-
- A reconstructed goal is never acted on silently — the lock names both the reading and the evidence it rests on.
|
|
116
|
-
- No multi-step work begins on a request whose interpretation gates an irreversible action when multiple plausible reads exist.
|
|
117
|
-
- On a non-interactive surface, an unresolved interpretation that gates an irreversible action ends Blocked with no action and the exact unblock question recorded.
|
|
118
|
-
- Lock statements are visible in the turn output before the work they govern.
|
|
119
|
-
- Asking state contains exactly one question and states what it unlocks.
|