agent-afk 5.169.0 → 5.169.2
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/agent/subagent/handle.d.ts +2 -0
- package/dist/cli.mjs +441 -441
- package/dist/index.mjs +2 -2
- package/dist/telegram.mjs +2 -2
- package/package.json +1 -1
package/dist/telegram.mjs
CHANGED
|
@@ -311,7 +311,7 @@ ${o}`,paths:[e,n]}:o!==null?s={content:o,paths:[n]}:r!==null?s={content:r,paths:
|
|
|
311
311
|
|
|
312
312
|
${e}`}var FG,Tg=g(()=>{"use strict";FG=new Set(["script","style","noscript","template","svg"])});function UG(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 SE(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function $G(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 vE(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??UG,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(!NG.has(u.status)||d===o)return u;let p=$G(u,i)??SE(d,s,i);O("[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=SE(d,s,i);O("[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 NG,kE=g(()=>{"use strict";se();NG=new Set([429,502,503,504])});import{BlockList as BG,isIP as xg}from"node:net";import{lookup as jG}from"node:dns/promises";import{Agent as HG}from"undici";function AE(){let t=S.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return t==="1"||t==="true"}function qG(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function Rg(t){let e=xg(t);return e===0?!1:GG.check(t,e===4?"ipv4":"ipv6")}async function EE(t){return jG(t,{all:!0,verbatim:!0})}async function Ig(t,e={}){if(e.allowPrivateHosts??AE())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=qG(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(xg(r)!==0)return Rg(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let s=e.lookupFn??EE,i;try{i=await s(r)}catch{return{allowed:!0}}for(let a of i)if(Rg(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function ki(t,e={}){let n=await Ig(t,e);if(!n.allowed)throw new kt(n.reason)}async function jl(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<=_E;i++){await ki(s,o);let a={...n,redirect:"manual",...t===globalThis.fetch&&!(r.allowPrivateHosts??AE())?{dispatcher:XG}:{}},c=await vE(t,s,a,r.retry??{});if(!zG.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 kt(`too many redirects (>${_E}) starting from ${e}`)}var WG,KG,GG,kt,XG,_E,zG,Cg=g(()=>{"use strict";L();kE();WG=[["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]],KG=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],GG=(()=>{let t=new BG;for(let[e,n]of WG)t.addSubnet(e,n,"ipv4");for(let[e,n]of KG)t.addSubnet(e,n,"ipv6");return t})(),kt=class extends Error{constructor(e){super(e),this.name="EgressBlockedError"}};XG=new HG({connect:{lookup(t,e,n){EE(t).then(r=>{let o=r.find(i=>Rg(i.address));if(o!==void 0){n(new kt(`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,xg(s.address))},r=>n(r,"",0))}}});_E=20,zG=new Set([301,302,303,307,308])});var IE={};_s(IE,{enforceDomainPolicy:()=>_t,loadBrowserConfig:()=>Pg});import{readFileSync as VG}from"node:fs";import{join as JG}from"path";function YG(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function TE(t,e){return YG(e).test(t)}function eq(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(QG.has(e))return!0;if(ZG.has(e))return!1}return!1}function RE(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function tq(t){if(t===void 0||t==="")return"auto";if(t==="playwright"||t==="agent-browser"||t==="auto")return t;throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${t}`)}function xE(t){let e=t===void 0||t.trim()===""?"default":t.trim();return Pf(e),e}function nq(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function rq(t){try{return VG(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function oq(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright"||e.backend==="agent-browser"||e.backend==="auto")n.backend=e.backend;else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: must be "playwright", "agent-browser", or "auto", got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=xE(e.defaultProfile)),n}function Pg(t){let e=t?.env??S,n=t?.readFileSync??rq,r=t?.surface??e.AGENT_SURFACE,o=eq(e.AFK_BROWSER_HEADLESS,r),s=RE(e.AFK_BROWSER_ALLOWED_DOMAINS),i=RE(e.AFK_BROWSER_BLOCKED_DOMAINS),a=nq(e.AFK_BROWSER_DOM_SNAPSHOTS),c=tq(e.AFK_BROWSER_BACKEND),l=xE(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():JG(Vt(),"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=oq(d,m);return h.configPath=p,h}function _t(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(TE(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>TE(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var QG,ZG,pr=g(()=>{"use strict";L();j();QG=new Set(["daemon","subagent","telegram","afk"]),ZG=new Set(["repl","interactive","cli"])});import{readFileSync as sq}from"node:fs";import{join as iq}from"node:path";import{homedir as aq}from"node:os";function lq(t){let e=t??cq,n;try{n=sq(e,"utf8")}catch{return null}let r;try{r=JSON.parse(n)}catch{return null}if(typeof r!="object"||r===null||Array.isArray(r))return null;let o=r;if(typeof o.url!="string"||typeof o.token!="string"||typeof o.pid!="number")return null;let s;try{s=new URL(o.url)}catch{return null}let{hostname:i,protocol:a}=s;if(!(i==="127.0.0.1"||i==="localhost"||i==="::1")||a!=="http:")throw new Error(`Agent Browser connection file contains an untrusted URL: ${o.url}. Only http://127.0.0.1 or http://localhost is permitted.`);return{url:o.url,token:o.token,pid:o.pid,version:typeof o.version=="string"?o.version:"unknown"}}function dq(t){try{return process.kill(t,0),!0}catch{return!1}}async function uq(t,e,n=2e3){try{let r=new AbortController,o=setTimeout(()=>r.abort(),n),s=await fetch(`${t}/health`,{method:"GET",headers:{Authorization:`Bearer ${e}`,Host:"127.0.0.1:8833"},signal:r.signal});return clearTimeout(o),s.ok}catch{return!1}}async function Mg(t){let e=lq(t);return e===null?{available:!1,connection:null,reason:"connection file missing or invalid"}:dq(e.pid)?await uq(e.url,e.token)?{available:!0,connection:e,reason:null}:{available:!1,connection:e,reason:`health probe failed at ${e.url}`}:{available:!1,connection:e,reason:`stale connection file: PID ${e.pid} not alive`}}var cq,CE=g(()=>{"use strict";cq=iq(aq(),".config","agent-browser","connection.json")});async function PE(t){let{config:e,surface:n}=t;if(e.backend==="playwright")return{backend:"playwright",reason:"explicit config: backend=playwright",probeMs:0,availability:null};if(e.backend==="agent-browser"){let i=Date.now(),a=await Mg(),c=Date.now()-i;if(!a.available)throw new Error(`AFK_BROWSER_BACKEND=agent-browser but Agent Browser is not available: ${a.reason}`);return{backend:"agent-browser",reason:"explicit config: backend=agent-browser",probeMs:c,availability:a}}if(n&&pq.has(n))return{backend:"playwright",reason:`auto: surface "${n}" excluded from Agent Browser`,probeMs:0,availability:null};if(e.headless)return{backend:"playwright",reason:"auto: headless mode requires Playwright",probeMs:0,availability:null};let r=Date.now(),o=await Mg(),s=Date.now()-r;return o.available?{backend:"agent-browser",reason:"auto: Agent Browser available and preferred",probeMs:s,availability:o}:{backend:"playwright",reason:`auto: Agent Browser unavailable (${o.reason})`,probeMs:s,availability:o}}var pq,ME=g(()=>{"use strict";CE();pq=new Set(["daemon","subagent"])});import{createHash as fq}from"crypto";function OE(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&mq.test(t.label))}function DE(t){return fq("sha256").update(t,"utf8").digest("hex").slice(0,8)}function FE(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var mq,Hl=g(()=>{"use strict";mq=/password|secret|token|api[_-]?key|otp|2fa/i});import{randomBytes as gq}from"crypto";import{mkdir as hq,stat as yq,writeFile as bq}from"fs/promises";import{join as Og}from"path";import{gzip as wq}from"zlib";import{promisify as Sq}from"util";function vq(t){return Og(Ct(t),"browser")}function kq(t){return Og(vq(t),"screenshots")}function _q(){return new Date().toISOString().replace(/[:.]/g,"-")}function Aq(){return gq(3).toString("hex")}async function wo(t,e,n){if(e.length>LE)throw new Error(`writeScreenshotSidecar: buffer exceeds ${LE} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=kq(t);await hq(r,{recursive:!0});let o=`${_q()}-${Aq()}-${n}.png`,s=Og(r,o);await bq(s,e);let{size:i}=await yq(s);return{path:s,bytes:i}}var rde,LE,Dg=g(()=>{"use strict";j();Hl();rde=Sq(wq);LE=5*1024*1024});var Wl,NE=g(()=>{"use strict";Wl=class{baseUrl;token;constructor(e){this.baseUrl=e.url,this.token=e.token}async call(e,n,r=3e4){let o={version:1,method:e,params:n},s=new AbortController,i=setTimeout(()=>s.abort(),r);try{let a=await fetch(`${this.baseUrl}/agent`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.token}`,Host:new URL(this.baseUrl).host},body:JSON.stringify(o),signal:s.signal});if(!a.ok){let c=await a.text().catch(()=>"");throw new Error(`Agent Browser ${e} failed (HTTP ${a.status}): ${c}`)}return await a.json()}finally{clearTimeout(i)}}async listTabs(){return(await this.call("tabs.list",null)).tabs}async openTab(e){return{tabId:(await this.call("tabs.open",{url:e},6e4)).tab_id}}async closeTab(e){await this.call("tabs.close",{tab_id:e})}async read(e,n){return this.call("page.read",{tab_id:e,mode:n?.mode??"main",...n?.query?{query:n.query}:{},...n?.budget?{budget:n.budget}:{}})}async inspect(e,n){return this.call("page.inspect",{tab_id:e,mode:n?.mode??"interactive",...n?.query?{query:n.query}:{},...n?.limit?{limit:n.limit}:{}})}async click(e,n){await this.call("page.click",{tab_id:e,element_id:n})}async fill(e,n,r){await this.call("page.fill",{tab_id:e,element_id:n,value:r})}async press(e,n,r){await this.call("page.press",{tab_id:e,key:n,...r?{element_id:r}:{}})}async select(e,n,r){await this.call("page.select",{tab_id:e,element_id:n,value:r})}async waitFor(e,n,r){await this.call("page.wait",{tab_id:e,condition:n,...r?.value?{value:r.value}:{},...r?.timeout?{timeout:r.timeout}:{}},(r?.timeout??3e4)+5e3)}async evalScript(e,n){return this.call("page.eval",{tab_id:e,script:n})}async screenshot(e){return this.call("page.screenshot",{tab_id:e})}}});function Fg(t){return{id:t.id,role:t.role,label:t.label,kind:t.kind,value:t.value,state:{disabled:t.disabled,...t.checked!==void 0?{checked:t.checked}:{},...t.selected!==void 0?{selected:t.selected}:{},...t.expanded!==void 0?{expanded:t.expanded}:{}},bbox:t.bbox,...t.selector?{selector:t.selector}:{}}}function UE(t,e){switch(e.kind){case"element_id":if(t.has(e.elementId))return e.elementId;throw new Error(`Element ${e.elementId} not found in current observation. Call browser_observe to refresh.`);case"selector":return null;case"semantic":return null}}async function Lg(t,e,n,r,o,s){switch(n){case"click":await t.click(e,r);break;case"fill":if(o===void 0)throw new Error("fill requires a value");await t.fill(e,r,o);break;case"press":if(o===void 0)throw new Error("press requires a value (key combo)");await t.press(e,o,r);break;case"select":if(o===void 0)throw new Error("select requires a value");await t.select(e,r,o);break;case"hover":throw new Error("hover is not supported by Agent Browser; use element_id from a prior observation to target clicks instead");case"scroll_to":{let i=r.replace(/\\/g,"\\\\").replace(/"/g,'\\"');await t.evalScript(e,`document.querySelector('[data-element-id="${i}"]')?.scrollIntoView({behavior:'smooth',block:'center'})`);break}case"wait_for":await t.waitFor(e,"element",{value:r,timeout:s??1e4});break;default:throw new Error(`Unknown action: ${n}`)}}async function $E(t,e){if(e.target.kind!=="semantic")throw new Error("resolveSemanticAndAct called with non-semantic target");let{elements:n}=await t.client.inspect(t.tabId,{mode:"interactive",query:e.target.text,limit:10}),r=n;if(e.target.role){let c=e.target.role.toLowerCase();r=n.filter(l=>l.role.toLowerCase()===c)}if(r.length===0)throw new Error(`No element found matching semantic target: text="${e.target.text}"`+(e.target.role?`, role="${e.target.role}"`:""));if(r.length>1)return{outcome:"ambiguous_target",query:{text:e.target.text,...e.target.role?{role:e.target.role}:{}},candidates:r.slice(0,5).map(Fg)};let s=r[0].id;await Lg(t.client,t.tabId,e.action,s,e.value,e.timeoutMs);let i=await t.client.read(t.tabId,{mode:"main"}),a=_t(i.url,t.config);return a.allowed?{elementId:s}:{outcome:"blocked_by_policy",url:i.url,reason:`action navigated to blocked domain: ${a.reason}`}}var BE=g(()=>{"use strict";pr()});var jE={};_s(jE,{AgentBrowserProvider:()=>Ng});var Ng,HE=g(()=>{"use strict";pr();Dg();NE();BE();Ng=class{name="agent-browser";config;client;sessions=new Map;constructor(e,n){this.config=e,this.client=new Wl(n)}async open(e){let n=_t(e.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:e.url,reason:n.reason};let r=this.sessions.get(e.sessionId);if(r)await this.client.evalScript(r.tabId,`window.location.href = ${JSON.stringify(e.url)}`),await this.client.waitFor(r.tabId,"load",{timeout:e.timeoutMs??3e4});else{let{tabId:i}=await this.client.openTab(e.url);await this.client.waitFor(i,"load",{timeout:e.timeoutMs??3e4}),r={tabId:i,observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null},this.sessions.set(e.sessionId,r)}let o=await this.client.read(r.tabId,{mode:"main"}),s=_t(o.url,this.config);return s.allowed?this.buildObservation(r,e.sessionId,e.screenshot,void 0,"browser_open"):(await this.client.evalScript(r.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`redirected to blocked domain: ${s.reason}`})}async observe(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);return this.buildObservation(n,e.sessionId,e.screenshot,e.maxElements,"browser_observe")}async act(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);let r=UE(n.knownElements,e.target);if(r===null){if(e.target.kind==="semantic"){let i=await $E({client:this.client,config:this.config,tabId:n.tabId},e);return"outcome"in i?i:(n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString(),this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"))}throw e.target.kind==="selector"?new Error("selector targets are not supported by Agent Browser; use element_id or semantic targets"):new Error(`Cannot resolve target: ${JSON.stringify(e.target)}`)}await Lg(this.client,n.tabId,e.action,r,e.value,e.timeoutMs),n.lastAction=`browser_act:${e.action}`,n.lastActionAt=new Date().toISOString();let o=await this.client.read(n.tabId,{mode:"main"}),s=_t(o.url,this.config);return s.allowed?this.buildObservation(n,e.sessionId,e.screenshot,void 0,"browser_act"):(await this.client.evalScript(n.tabId,"window.location.href = 'about:blank'").catch(()=>{}),{outcome:"blocked_by_policy",url:o.url,reason:`action navigated to blocked domain: ${s.reason}`})}async render(e){throw new Error("AgentBrowserProvider does not support render(). Use PlaywrightProvider for one-shot content fetches.")}async screenshot(e){let n=this.sessions.get(e.sessionId);if(!n)throw new Error(`No Agent Browser tab open for session ${e.sessionId}. Call browser_open first.`);if(e.target!==void 0||e.fullPage)throw new Error("Agent Browser does not support element or full-page screenshots; omit target and fullPage.");let r=await this.client.screenshot(n.tabId),o=Buffer.from(r.data,"base64"),s=o.length>=24?o.readUInt32BE(16):0,i=o.length>=24?o.readUInt32BE(20):0;return{path:(await wo(e.sessionId,o,"browser_screenshot")).path,bytes:o.length,width:s,height:i,dataBase64:r.data,mediaType:"image/png"}}async extract(e){throw new Error("AgentBrowserProvider does not support extract() yet.")}async close(e){let n=this.sessions.get(e.sessionId);if(n){try{await this.client.closeTab(n.tabId)}catch{}this.sessions.delete(e.sessionId)}}describe(e){let n=this.sessions.get(e);return n?{active:!0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:1}:null}async shutdown(){let e=Array.from(this.sessions.entries()).map(async([,n])=>{try{await this.client.closeTab(n.tabId)}catch{}});await Promise.all(e),this.sessions.clear()}async buildObservation(e,n,r,o,s="browser_open"){let[i,a]=await Promise.all([this.client.read(e.tabId,{mode:"main",budget:4e3}),this.client.inspect(e.tabId,{mode:"interactive",limit:o??80})]),c=a.elements.map(Fg),l=o??80,d=c.slice(0,l);e.observationCounter+=1,e.knownElements=new Map(d.map(h=>[h.id,h])),e.currentUrl=i.url,e.currentTitle=i.title;let u=[];c.length>l&&u.push(`page has ${c.length} interactive elements; showing first ${l}`);let p=null;if(r)try{let h=await this.client.screenshot(e.tabId),y=Buffer.from(h.data,"base64");p=(await wo(n,y,s)).path}catch{u.push("screenshot capture failed")}let f=`obs_${e.observationCounter.toString(36)}`,m={httpStatus:null,loadingState:"idle",hasDialog:!1,consoleErrors:0};return{observationId:f,url:i.url,title:i.title,textSummary:i.content.slice(0,4e3),interactive:d,status:m,warnings:u,screenshotPath:p,capturedAt:new Date().toISOString()}}}});import{existsSync as Eq,readFileSync as Tq}from"node:fs";import{createRequire as Rq}from"node:module";import{dirname as xq,join as Iq}from"node:path";function GE(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<Pq&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function He(t){let e=GE(t);return KE.some(n=>e.includes(n))}function Mq(){try{let e=Rq(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(Tq(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=Iq(xq(e),o);return Eq(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function _i(){return WE??=Mq()??Cq,WE}function Ug(t){return t.includes("install chromium")}function ct(t,e){let n=GE(t),r=e?.latched===!0?` ${Oq}`:"";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: ${_i()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${_i()}). Or pick a different tool.${r}`}function $g(t,e,n=!1){if(!He(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
313
313
|
|
|
314
|
-
${ct(t,{headless:e,latched:n})}`,{cause:t})}var KE,Cq,Pq,WE,Oq,Bg=g(()=>{"use strict";KE=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],Cq="pnpm exec playwright install chromium",Pq=4;Oq="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 fr from"node:fs";import Kl from"node:path";import{randomBytes as Dq}from"node:crypto";import{chromium as Fq}from"playwright";function Lq(){try{return"5.169.0"}catch{}try{let t=Kl.resolve(import.meta.dirname,"../../../package.json"),e=fr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Nq,Gl,qE=g(()=>{"use strict";Bg();j();se();Nq=Lq(),Gl=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=Fq.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=$g(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/${Nq}`}}loadStorageState(e){let n=Mf(e);try{if(!fr.existsSync(n))return;let r=JSON.parse(fr.readFileSync(n,"utf8"));return O("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){O("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Mf(e);if(!fr.existsSync(r))return;let o=await n.storageState(),s=Kl.join(Kl.dirname(r),`.${Kl.basename(r)}.${process.pid}.${Dq(4).toString("hex")}.tmp`);fr.writeFileSync(s,JSON.stringify(o),{mode:384}),fr.chmodSync(s,384),fr.renameSync(s,r),O("[browser/vault] saved session",{profile:e,file:r})}catch(r){O("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as Uq}from"node:crypto";function $q(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Bq(t,e,n){return`el_${Uq("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function jq(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function XE(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function VE(t,e){let n=t.role??"",r=t.name??"";zE.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])VE(s,e)}async function Hq(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},JE).catch(()=>[])}async function Wq(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},JE).catch(()=>[])}function Kq(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function ql(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=Kq(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Hq(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,b=!1;u!==null?(y=[],VE(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await Wq(t)).filter(P=>zE.has(P.role??"")));let k=new Map;for(let C of p){let P=XE(C.name),G=k.get(P);(!G||G.bbox.w===0&&C.bbox.w>0)&&k.set(P,C)}let _=y.map(C=>({ax:C,dom:k.get(XE(C.name??""))})),E=r?_:_.filter(C=>C.dom?C.dom.bbox.w>0||C.dom.bbox.h>0:!0);E.sort((C,P)=>{let G=C.dom?.bbox.y??0,M=P.dom?.bbox.y??0;if(G!==M)return G-M;let $=C.dom?.bbox.x??0,D=P.dom?.bbox.x??0;return $-D}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=E.slice(0,n).map((C,P)=>{let G=C.ax.role??"generic",M=C.ax.name??"",$=Bq(G,M,P),D=C.dom?.bbox??{x:0,y:0,w:0,h:0},N=C.dom?.type??null,B=null;C.ax.value!==void 0&&C.ax.value!==null&&(B=String(C.ax.value)),C.ax.checked!==void 0&&(B=String(C.ax.checked)),OE({role:G,kind:N})&&(B="[redacted]");let K={disabled:C.ax.disabled??!1};C.ax.checked!==void 0&&(K.checked=C.ax.checked===!0||C.ax.checked==="mixed"),C.ax.selected!==void 0&&(K.selected=C.ax.selected),C.ax.expanded!==void 0&&(K.expanded=C.ax.expanded);let Q;C.dom?.testId?Q=`[data-testid="${C.dom.testId}"]`:C.dom?.id&&(Q=`#${C.dom.id}`);let Ne={id:$,role:G,label:$q(M),kind:N,value:B,state:K,bbox:D};return Q!==void 0&&(Ne.selector=Q),Ne}),I="idle";try{let C=await t.evaluate(()=>document.readyState);C==="loading"?I="loading":C==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="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 x=jq(f),v=`obs_${e.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:v,url:m,title:h,textSummary:x,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:A}}var zE,JE,YE=g(()=>{"use strict";Hl();zE=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);JE="a[href], button, input, select, textarea, [role], [tabindex], label"});async function QE(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 jg(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>QE(t,s)))).filter(o=>o!==null)}async function Gq(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 Hg(t,e,n){switch(e.kind){case"element_id":return qq(t,e,n);case"selector":return Xq(t,e);case"semantic":return zq(t,e)}}async function qq(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 jg(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Xq(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 jg(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function zq(t,e){return e.role!==void 0?Vq(t,e.text,e.role):Jq(t,e.text,e)}async function Vq(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 jg(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Jq(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 Gq(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 b=await QE(y.locator,y.index);if(b!==null){let k=`${b.role}:${b.label}:${h}`,_=0;for(let E=0;E<k.length;E++)_=_*31+k.charCodeAt(E)>>>0;f.push({...b,id:`el_${_.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var ZE=g(()=>{"use strict"});async function Wg(t,e,n,r){let o=t.url();if(o===n)return null;let s=_t(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 eT=g(()=>{"use strict";pr()});var Gg={};_s(Gg,{PlaywrightProvider:()=>Kg});function tT(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 Kg,qg=g(()=>{"use strict";qE();YE();ZE();pr();eT();Dg();Kg=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Gl(e)}async open(e){let n=_t(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 Wg(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 ql(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 ql(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 Hg(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${tT(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 Wg(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 ql(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 Hg(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${tT(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 wo(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 wo(n,o,r);return s}catch{return null}}}});var gr={};_s(gr,{__resetBrowserRegistryForTests:()=>n2,browserProviderActive:()=>Zq,closeBrowserProvider:()=>zg,getBrowserProvider:()=>Qq,getLastRoutingDecision:()=>t2,peekBrowserProvider:()=>e2});function nT(){Promise.resolve(zg()).then(()=>{process.exit(130)})}function rT(){Promise.resolve(zg()).then(()=>{process.exit(143)})}function oT(){jt=null}function Yq(){Xl||(process.on("SIGINT",nT),process.on("SIGTERM",rT),process.on("exit",oT),Xl=!0)}function sT(){Xl&&(process.removeListener("SIGINT",nT),process.removeListener("SIGTERM",rT),process.removeListener("exit",oT),Xl=!1)}async function Qq(t){return jt!==null?jt:(mr!==null||(mr=(async()=>{let e=Pg(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??S.AGENT_SURFACE,r=await PE({config:e,surface:n});Xg=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(HE(),jE)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(qg(),Gg));o=new s(e)}return Yq(),jt=o,mr=null,o})()),mr)}async function zg(){if(jt===null)return;let t=jt;jt=null,mr=null,sT(),await t.shutdown()}function Zq(){return jt!==null}function e2(){return jt}function t2(){return Xg}function n2(){jt=null,mr=null,Xg=null,sT()}var jt,mr,Xl,Xg,hr=g(()=>{"use strict";pr();ME();L();jt=null,mr=null,Xl=!1,Xg=null});async function iT(t,e){try{return await yE(t,e)}catch(n){return O("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function c2(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(hr(),gr)),r=await n();try{return await r.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(qg(),Gg)),{loadBrowserConfig:i}=await Promise.resolve().then(()=>(pr(),IE)),a=i(),c=new s(a);try{return await c.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}finally{await c.shutdown()}}throw o}}async function aT(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??c2,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await jl(n,t,{headers:a2,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(i2.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(s2.test(p)&&!o2.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await iT(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof kt||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=Eg({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await ki(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>ki(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await ki(u.finalUrl,o);let p=await iT(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=Eg({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 kt)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 o2,s2,i2,a2,cT=g(()=>{"use strict";bE();Tg();Cg();se();o2=/(text\/html|application\/xhtml\+xml)/i,s2=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,i2=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,a2={"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 u2(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(l2,{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),d2),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=Z(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function lT(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?u2({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 dT(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
314
|
+
${ct(t,{headless:e,latched:n})}`,{cause:t})}var KE,Cq,Pq,WE,Oq,Bg=g(()=>{"use strict";KE=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],Cq="pnpm exec playwright install chromium",Pq=4;Oq="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 fr from"node:fs";import Kl from"node:path";import{randomBytes as Dq}from"node:crypto";import{chromium as Fq}from"playwright";function Lq(){try{return"5.169.2"}catch{}try{let t=Kl.resolve(import.meta.dirname,"../../../package.json"),e=fr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var Nq,Gl,qE=g(()=>{"use strict";Bg();j();se();Nq=Lq(),Gl=class{config;browser;sessions=new Map;launchPromise;launchFailure;shutdownComplete=!1;constructor(e){this.config=e}clearLaunchFailure(){this.launchFailure=void 0}latchLaunchFailure(e){this.launchFailure={error:e}}async ensureBrowser(){if(this.browser!==void 0&&this.browser.isConnected())return this.browser;if(this.launchFailure!==void 0)throw this.launchFailure.error;return this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=Fq.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=$g(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/${Nq}`}}loadStorageState(e){let n=Mf(e);try{if(!fr.existsSync(n))return;let r=JSON.parse(fr.readFileSync(n,"utf8"));return O("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){O("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Mf(e);if(!fr.existsSync(r))return;let o=await n.storageState(),s=Kl.join(Kl.dirname(r),`.${Kl.basename(r)}.${process.pid}.${Dq(4).toString("hex")}.tmp`);fr.writeFileSync(s,JSON.stringify(o),{mode:384}),fr.chmodSync(s,384),fr.renameSync(s,r),O("[browser/vault] saved session",{profile:e,file:r})}catch(r){O("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as Uq}from"node:crypto";function $q(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function Bq(t,e,n){return`el_${Uq("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function jq(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function XE(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function VE(t,e){let n=t.role??"",r=t.name??"";zE.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])VE(s,e)}async function Hq(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},JE).catch(()=>[])}async function Wq(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},JE).catch(()=>[])}function Kq(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function ql(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=Kq(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=Hq(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,b=!1;u!==null?(y=[],VE(u,y)):(o.push("observation skipped accessibility tree (returned null)"),b=!0,y=(await Wq(t)).filter(P=>zE.has(P.role??"")));let k=new Map;for(let C of p){let P=XE(C.name),G=k.get(P);(!G||G.bbox.w===0&&C.bbox.w>0)&&k.set(P,C)}let _=y.map(C=>({ax:C,dom:k.get(XE(C.name??""))})),E=r?_:_.filter(C=>C.dom?C.dom.bbox.w>0||C.dom.bbox.h>0:!0);E.sort((C,P)=>{let G=C.dom?.bbox.y??0,M=P.dom?.bbox.y??0;if(G!==M)return G-M;let $=C.dom?.bbox.x??0,D=P.dom?.bbox.x??0;return $-D}),E.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=E.slice(0,n).map((C,P)=>{let G=C.ax.role??"generic",M=C.ax.name??"",$=Bq(G,M,P),D=C.dom?.bbox??{x:0,y:0,w:0,h:0},N=C.dom?.type??null,B=null;C.ax.value!==void 0&&C.ax.value!==null&&(B=String(C.ax.value)),C.ax.checked!==void 0&&(B=String(C.ax.checked)),OE({role:G,kind:N})&&(B="[redacted]");let K={disabled:C.ax.disabled??!1};C.ax.checked!==void 0&&(K.checked=C.ax.checked===!0||C.ax.checked==="mixed"),C.ax.selected!==void 0&&(K.selected=C.ax.selected),C.ax.expanded!==void 0&&(K.expanded=C.ax.expanded);let Q;C.dom?.testId?Q=`[data-testid="${C.dom.testId}"]`:C.dom?.id&&(Q=`#${C.dom.id}`);let Ne={id:$,role:G,label:$q(M),kind:N,value:B,state:K,bbox:D};return Q!==void 0&&(Ne.selector=Q),Ne}),I="idle";try{let C=await t.evaluate(()=>document.readyState);C==="loading"?I="loading":C==="interactive"?I="navigating":I="idle"}catch{I="navigating"}I!=="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 x=jq(f),v=`obs_${e.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:v,url:m,title:h,textSummary:x,interactive:T,status:{httpStatus:e.httpStatus??null,loadingState:I,hasDialog:e.hasDialog??!1,consoleErrors:e.consoleErrors??0},warnings:o,screenshotPath:e.screenshotPath??null,capturedAt:A}}var zE,JE,YE=g(()=>{"use strict";Hl();zE=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);JE="a[href], button, input, select, textarea, [role], [tabindex], label"});async function QE(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 jg(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>QE(t,s)))).filter(o=>o!==null)}async function Gq(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 Hg(t,e,n){switch(e.kind){case"element_id":return qq(t,e,n);case"selector":return Xq(t,e);case"semantic":return zq(t,e)}}async function qq(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 jg(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function Xq(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 jg(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function zq(t,e){return e.role!==void 0?Vq(t,e.text,e.role):Jq(t,e.text,e)}async function Vq(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 jg(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function Jq(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 Gq(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 b=await QE(y.locator,y.index);if(b!==null){let k=`${b.role}:${b.label}:${h}`,_=0;for(let E=0;E<k.length;E++)_=_*31+k.charCodeAt(E)>>>0;f.push({...b,id:`el_${_.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var ZE=g(()=>{"use strict"});async function Wg(t,e,n,r){let o=t.url();if(o===n)return null;let s=_t(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 eT=g(()=>{"use strict";pr()});var Gg={};_s(Gg,{PlaywrightProvider:()=>Kg});function tT(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 Kg,qg=g(()=>{"use strict";qE();YE();ZE();pr();eT();Dg();Kg=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Gl(e)}async open(e){let n=_t(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 Wg(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 ql(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 ql(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 Hg(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${tT(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 Wg(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 ql(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 Hg(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${tT(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 wo(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 wo(n,o,r);return s}catch{return null}}}});var gr={};_s(gr,{__resetBrowserRegistryForTests:()=>n2,browserProviderActive:()=>Zq,closeBrowserProvider:()=>zg,getBrowserProvider:()=>Qq,getLastRoutingDecision:()=>t2,peekBrowserProvider:()=>e2});function nT(){Promise.resolve(zg()).then(()=>{process.exit(130)})}function rT(){Promise.resolve(zg()).then(()=>{process.exit(143)})}function oT(){jt=null}function Yq(){Xl||(process.on("SIGINT",nT),process.on("SIGTERM",rT),process.on("exit",oT),Xl=!0)}function sT(){Xl&&(process.removeListener("SIGINT",nT),process.removeListener("SIGTERM",rT),process.removeListener("exit",oT),Xl=!1)}async function Qq(t){return jt!==null?jt:(mr!==null||(mr=(async()=>{let e=Pg(t),n=t?.surface??(t?.env??{}).AGENT_SURFACE??S.AGENT_SURFACE,r=await PE({config:e,surface:n});Xg=r;let o;if(r.backend==="agent-browser"){let{AgentBrowserProvider:s}=await Promise.resolve().then(()=>(HE(),jE)),i=r.availability.connection;o=new s(e,i)}else{let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(qg(),Gg));o=new s(e)}return Yq(),jt=o,mr=null,o})()),mr)}async function zg(){if(jt===null)return;let t=jt;jt=null,mr=null,sT(),await t.shutdown()}function Zq(){return jt!==null}function e2(){return jt}function t2(){return Xg}function n2(){jt=null,mr=null,Xg=null,sT()}var jt,mr,Xl,Xg,hr=g(()=>{"use strict";pr();ME();L();jt=null,mr=null,Xl=!1,Xg=null});async function iT(t,e){try{return await yE(t,e)}catch(n){return O("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function c2(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(hr(),gr)),r=await n();try{return await r.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}catch(o){if(r.name==="agent-browser"){let{PlaywrightProvider:s}=await Promise.resolve().then(()=>(qg(),Gg)),{loadBrowserConfig:i}=await Promise.resolve().then(()=>(pr(),IE)),a=i(),c=new s(a);try{return await c.render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}finally{await c.shutdown()}}throw o}}async function aT(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??c2,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await jl(n,t,{headers:a2,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(i2.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(s2.test(p)&&!o2.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await iT(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof kt||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=Eg({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await ki(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>ki(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await ki(u.finalUrl,o);let p=await iT(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=Eg({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 kt)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 o2,s2,i2,a2,cT=g(()=>{"use strict";bE();Tg();Cg();se();o2=/(text\/html|application\/xhtml\+xml)/i,s2=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,i2=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,a2={"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 u2(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(l2,{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),d2),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=Z(d);u&&(c=`: ${u.length>200?u.slice(0,200)+"\u2026":u}`)}catch{}let l=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${l}${c}`)}let i;try{i=await s.json()}catch(c){throw new Error(`Exa Search response was not JSON: ${c instanceof Error?c.message:String(c)}`)}return(i.results??[]).slice(0,r).map(c=>({title:(c.title??"").trim()||"(untitled)",url:c.url??"",description:(c.highlights?.[0]??"").trim()})).filter(c=>c.url.length>0)}}}function lT(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?u2({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 dT(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
315
315
|
|
|
316
316
|
(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(`
|
|
317
317
|
`).trimEnd()}var l2,d2,uT=g(()=>{"use strict";ht();l2="https://api.exa.ai/search",d2=10});function zl(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 yr=g(()=>{"use strict";Bg()});function y2(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=p2;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,f2)}let a=m2;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,g2)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function Vg(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:tr(t,e),truncated:!0}}function b2(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=y2(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 Ig(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 jl(e,i.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:h instanceof kt?{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=Vg(f,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let p=await aT(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=Vg(wE(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 kt)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),m=He(p)&&!Ug(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${_i()}\`)`:"";return{content:`web_scrape markdown error: ${f}${m}`,isError:!0}}let u=lT({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:h2,timeoutMs:i.timeoutMs,signal:a.signal}),f=Vg(dT(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 p2,f2,m2,g2,h2,pT,fT=g(()=>{"use strict";cT();uT();Cg();wn();Tg();yr();p2=3e4,f2=12e4,m2=1e5,g2=1e6,h2=10;pT=b2()});import{existsSync as gT,mkdirSync as w2,readFileSync as S2,renameSync as v2,unlinkSync as k2,writeFileSync as _2}from"node:fs";import{dirname as mT,join as A2}from"node:path";import{randomBytes as E2}from"node:crypto";function br(t){let e=t??Ef();if(!gT(e))return[];try{let n=S2(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 Ai(t,e){let n=e??Ef();w2(mT(n),{recursive:!0});let r=A2(mT(n),`.schedules.json.${process.pid}.${E2(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{_2(r,o,"utf-8"),v2(r,n)}catch(s){try{gT(r)&&k2(r)}catch{}throw s}}function hT(t,e){let n=br(e),r=n.map(c=>c.id),o=T2(t.name),s=R2(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),Ai(n,e),a}function yT(t,e){let n=br(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(Ai(o,e),!0)}function bT(t,e){return br(e).find(n=>n.id===t)}function T2(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function R2(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}function wT(t){return{taskId:t.id,command:t.command,trigger:t.trigger??"cron",...t.cron!==void 0?{cronExpression:t.cron}:{},...t.notifyOn!==void 0?{notifyOn:t.notifyOn}:{},...t.notifyChat!==void 0?{notifyChat:t.notifyChat}:{}}}var ST=g(()=>{"use strict";j()});import{existsSync as x2,readFileSync as I2}from"node:fs";import{join as C2}from"node:path";async function So(t,e,n){let r,o;try{let s=C2(AS("default"),"port");if(!x2(s))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=I2(s,"utf-8").trim(),a=P2(i);if(!a)return{synced:!1,detail:"daemon-not-detected (invalid port file)"};({host:r,port:o}=a)}catch{return{synced:!1,detail:"daemon-not-detected (unreadable port file)"}}try{let s=r.includes(":")?`[${r}]`:r,i=await fetch(`http://${s}:${o}${e}`,{method:t,headers:{"Content-Type":"application/json"},body:n!==void 0?JSON.stringify(n):void 0,signal:AbortSignal.timeout(2e3)});return i.ok?{synced:!0,detail:"synced"}:t==="POST"&&i.status===409?{synced:!0,detail:"already-registered"}:t==="DELETE"&&i.status===404?{synced:!0,detail:"not-registered"}:{synced:!1,detail:`daemon-rejected (HTTP ${i.status})`}}catch{return{synced:!1,detail:"daemon-unreachable (stale port file or network error)"}}}function P2(t){let e=parseInt(t,10);if(String(e)===t&&!Number.isNaN(e))return e<1||e>65535?null:{host:"localhost",port:e};let n=t.lastIndexOf(":");if(n<1)return null;let r=t.slice(0,n),o=t.slice(n+1);if(!/^\d+$/.test(o))return null;let s=parseInt(o,10);return Number.isNaN(s)||s<1||s>65535||/^:+$/.test(r)?null:{host:r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,port:s}}var Jg,vT=g(()=>{"use strict";j();Jg="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 M2}from"node:fs";import{readFile as O2}from"node:fs/promises";var kT,_T,AT,ET,TT=g(()=>{"use strict";ST();j();vT();kT=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=hT({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 So("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 So("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:Jg}})}},_T=async(t,e)=>{let n=br();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})))}},AT=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=tc();if(!M2(s))return{content:JSON.stringify([])};let i;try{let l=await O2(s);i=(l.length>1048576?l.subarray(l.length-1048576):l).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
|
|
@@ -1186,7 +1186,7 @@ ${c}`:f,h=await u.runToResult(m);return p=sO(h,l),p}catch(f){let m=f instanceof
|
|
|
1186
1186
|
|
|
1187
1187
|
${n}`}:{...t,systemPrompt:n};if(r&&typeof r=="object"&&"type"in r&&r.type==="preset"){let o=r.append??"";return{...t,systemPrompt:{...r,append:o.length>0?`${o}
|
|
1188
1188
|
|
|
1189
|
-
${n}`:n}}}return{...t,systemPrompt:n}}var yO=g(()=>{"use strict"});function da(){let t=S.AFK_SUBAGENT_TIMEOUT_MS;if(t===void 0||t.trim()==="")return vb;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?vb:e}function bO(){let t=S.AFK_SUBAGENT_IDLE_TIMEOUT_MS;if(t===void 0||t.trim()==="")return kb;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?kb:e}var _b,Ab,vb,kb,bb,wO,ua=g(()=>{"use strict";L();_b=async(t,e)=>({action:"decline"}),Ab=50,vb=45*6e4;kb=8*6e4;bb=60*6e4,wO=5e3});function SO(t){let{options:e,id:n,resume:r,registry:o,effectiveChildModel:s,effectiveTimeoutMs:i,inheritedReadRoots:a,composedWriteRoots:c,childController:l,parentCwd:d,parentApiKey:u,parentBaseUrl:p,parentProvider:f,parentTraceWriter:m,parentSurface:h,parentCanUseTool:y}=t,b=r??(typeof e.config.systemPrompt=="string"?e.config.systemPrompt:""),k=t.workspaceStore?t.workspaceStore.queryRelevant(null,b):[],_=hO({...e.config,isSubagentFork:!0,model:s,resume:r,forkSession:r?!0:e.config.forkSession,subagentId:n,subagentToolOutputCapBytes:1e5,abortSignal:l.signal,apiKey:NP({childModel:s,configApiKey:e.config.apiKey,parentApiKey:u,parentProvider:f}),baseUrl:e.config.baseUrl??(q(s)==="openai-compatible"?void 0:p),isNonInteractive:e.config.isNonInteractive??!0,maxToolUseIterations:e.config.maxToolUseIterations??Ab,softDeadlineMs:e.config.softDeadlineMs??Dd(i),autoResumeOnUsageLimit:e.config.autoResumeOnUsageLimit??!1,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&d!==void 0?{cwd:d}:{},...a!==void 0?{readRoots:a}:{},...c!==void 0?{writeRoots:c}:{},...e.config.traceWriter===void 0&&m!==void 0?{traceWriter:m}:{},...e.config.surface===void 0&&h!==void 0?{surface:h}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(y!==void 0&&e.config.canUseTool===void 0?{canUseTool:y}:void 0),...e.denyElicitations===!1?{}:{onElicitation:_b},...e.phaseRole==="read-only"?{provider:gO("read-only",s)}:{}});return t.workspaceStore?gm(_,k):_}var vO=g(()=>{"use strict";ue();Rt();wn();Tu();yO();Vn();ua();An()});function kO(t){let{effectiveTraceWriter:e,id:n,parentSessionId:r,rootId:o,effectiveChildModel:s,childConfig:i,promptHead:a,effectiveAgentType:c,effectiveResolvedAgentType:l}=t,d=typeof s=="string"?s:JSON.stringify(s);return Zn(e,{transition:"started",subagentId:n,parentId:r??o,model:d,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{},...a&&a.trim()!==""?{promptHead:a.slice(0,80)}:{},...c?{agentType:c}:{},...l?{resolvedAgentType:l}:{}}),d}async function _O(t){let{modelString:e,id:n,idPrefix:r,parentSessionId:o,effectiveResolvedAgentType:s}=t;await te({event:"subagent.dispatched",subagent_id:n,id_prefix:r,model:e,parent_session_id:o,resolved_agent_type:s})}var AO=g(()=>{"use strict";V();vt()});function pa(t,e=Date.now()){if(t.type==="paused")return t.resetsAt===void 0?void 0:t.resetsAt.getTime()-e+3e4;if(t.type==="rate_limit"){let n=t.retryAfterMs;return typeof n!="number"||!Number.isFinite(n)||n<=0?void 0:n+3e4}}function EO(t){if(t.type==="paused"){let e=t.resetsAt!==void 0?t.resetsAt.toISOString():"unknown";return`paused (${t.reason}, resetsAt=${e})`}if(t.type==="rate_limit"){let e=t.retryAfterMs;return`rate_limit (retryAfterMs=${typeof e=="number"?e:"unknown"})`}}var Eb=g(()=>{"use strict"});var Tb,$5,Zu,TO=g(()=>{"use strict";Eb();Tb=120*6e4,$5=1e3,Zu=class{constructor(e,n=Tb,r){this.baseTimeoutMs=e;this.maxExtensionMs=n;this.onGrant=r}baseTimeoutMs;maxExtensionMs;pauseStartedAtMs;pauseWindowCapMs=0;closedCreditMs=0;lastPauseDescription;grantedMs=0;grantCount=0;onGrant;onEvent(e){if(e.type==="resumed"){this.closePause();return}if(e.type!=="paused"&&e.type!=="rate_limit")return;this.closeExpiredPause();let n=pa(e);if(n===void 0||n<=0)return;let r=Date.now();if(this.pauseStartedAtMs===void 0)this.pauseStartedAtMs=r,this.pauseWindowCapMs=n;else{let o=r-this.pauseStartedAtMs;this.pauseWindowCapMs=Math.max(this.pauseWindowCapMs,o+n)}this.lastPauseDescription=EO(e)}openPauseCreditMs(){if(this.pauseStartedAtMs===void 0)return 0;let e=Date.now()-this.pauseStartedAtMs;return Math.max(0,Math.min(e,this.pauseWindowCapMs))}closePause(){this.pauseStartedAtMs!==void 0&&(this.closedCreditMs+=this.openPauseCreditMs(),this.pauseStartedAtMs=void 0,this.pauseWindowCapMs=0)}closeExpiredPause(){this.pauseStartedAtMs!==void 0&&Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs&&this.closePause()}onDeadline(){let e=this.maxExtensionMs-this.grantedMs;if(!(e>0))return 0;this.closeExpiredPause();let r=this.closedCreditMs+this.openPauseCreditMs()-this.grantedMs;if(r<=0)return 0;let o=Math.min(Math.max(r,$5),e);if(this.grantedMs+=o,this.grantCount+=1,this.onGrant)try{this.onGrant({grantMs:o,totalGrantedMs:this.grantedMs,remainingCapMs:this.maxExtensionMs-this.grantedMs,grantCount:this.grantCount,pauseDescription:this.lastPauseDescription})}catch{}return o}describe(){if(this.lastPauseDescription===void 0)return;let e=[`base budget ${this.baseTimeoutMs}ms`,`pause extension granted ${this.grantedMs}ms across ${this.grantCount} extension${this.grantCount===1?"":"s"} (cap ${this.maxExtensionMs}ms${this.grantedMs>=this.maxExtensionMs?", EXHAUSTED":""})`,`last provider pause: ${this.lastPauseDescription}`];if(this.pauseStartedAtMs!==void 0){let r=Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs?"expired":"still open";e.push(`last pause ${r}, opened ${new Date(this.pauseStartedAtMs).toISOString()} (reported window ${this.pauseWindowCapMs}ms)`)}return`[pause-aware ceiling: ${e.join("; ")}]`}get totalGrantedMs(){return this.grantedMs}}});var ep,RO=g(()=>{"use strict";re();Eb();ep=class{constructor(e,n,r,o){this.controller=e;this.idleTimeoutMs=n;this.label=r;this.onFire=o;this.isEnabled()&&this.arm(this.idleTimeoutMs,"none")}controller;idleTimeoutMs;label;onFire;timer;disposed=!1;fired=!1;inFlightTools=new Set;isEnabled(){return Number.isFinite(this.idleTimeoutMs)&&this.idleTimeoutMs>0}onEvent(e){if(!(!this.isEnabled()||this.disposed||this.fired)){if(e.type==="chunk"){if(e.chunk.type==="tool_use_detail"){this.inFlightTools.add(e.chunk.toolUseId),this.clearTimer();return}if(e.chunk.type==="tool_result"){this.inFlightTools.delete(e.chunk.toolUseId),this.inFlightTools.size===0&&this.arm(this.idleTimeoutMs,e.chunk.type);return}}if(!(this.inFlightTools.size>0)){if(e.type==="paused"){this.arm(this.pausedWindowMs(e),e.type);return}if(e.type==="rate_limit"){let n=pa(e);if(n!==void 0&&n>0){this.arm(n,e.type);return}}this.arm(this.idleTimeoutMs,e.type)}}}pausedWindowMs(e){let n=pa(e);return n===void 0?this.idleTimeoutMs:Math.max(this.idleTimeoutMs,n)}arm(e,n){this.timer!==void 0&&clearTimeout(this.timer);let r=e>0?e:this.idleTimeoutMs,o=Date.now(),s=setTimeout(()=>{this.fire(Date.now()-o,n)},r);s.unref(),this.timer=s}clearTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}fire(e,n){if(!(this.fired||this.disposed)){this.fired=!0,this.timer=void 0;try{this.onFire?.({idleTimeoutMs:this.idleTimeoutMs,elapsedSinceLastProgressMs:e,lastEventType:n})}catch{}this.controller.signal.aborted||this.controller.abort(new Uc(`subagent ${this.label} idle-watchdog fired: no observable progress for ${this.idleTimeoutMs}ms (last event: ${n}). The child stream produced no output for the idle window \u2014 typically a stalled model call under provider throttling with no detectable backoff bracket. Aborting so partial output (if any) is returned; the parent should retry or fall back.`,this.idleTimeoutMs))}}dispose(){this.disposed||(this.disposed=!0,this.inFlightTools.clear(),this.clearTimer())}}});function xO(t,e){let n=e.length,r=n>0?`subagent ${t} stream cut off after ${n} tool result(s); see partialOutput.`:`subagent ${t} produced no output \u2014 stream ended without a terminal message (stream_incomplete). No findings were produced; retry or fall back.`,o=new nt(r);return n>0&&(o.toolResultsGathered=n),o}function IO(t,e){if(e.length===0)return;let n=e.reduce((s,i)=>s+(i.sizeBytes??0),0),r=e.filter(s=>s.isError).length,o=r>0?` (${r} errored)`:"";return`[Stream cut off before any assistant text was produced. Subagent ${t} completed ${e.length} tool result(s)${o} (~${n} bytes total) before the cut. The run is failed \u2014 no final answer was produced \u2014 but tool evidence is available via result.trace for recovery or retry decisions.]`}var CO=g(()=>{"use strict";re()});async function Rb(t,e,n){let r,o;t._lastStreamedContent="",t._currentTrace=Jo();let s=n??t._progressSink??Et(),i={subagentId:t.id,...t._parentId!==void 0&&{parentId:t._parentId},...t._agentType!==void 0&&{agentType:t._agentType}},a=new ep(t._controller,t._idleTimeoutMs,t.id,c=>{W(t._traceWriter,{phase:"idle_watchdog_fired",metadata:{idleTimeoutMs:c.idleTimeoutMs,elapsedSinceLastProgressMs:c.elapsedSinceLastProgressMs,lastEventType:c.lastEventType}})});try{for await(let c of t.session.sendMessageStream(e)){if(s&&s(c,i),t._logWriter?.write(c),a.onEvent(c),t._pauseCeiling?.onEvent(c),c.type==="chunk"){let l=c.chunk;l.type==="content"?t._lastStreamedContent+=l.content:l.type==="tool_use_detail"?t._currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?t._currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(t._currentTrace.thinkingPresent=!0)}if(c.type==="message")r=c.message,t._currentTrace.turnCount++;else if(c.type==="error"){o=c.error;break}else if(c.type==="done"){if(typeof c.metadata?.stopReason=="string"&&(t._lastStopReason=c.metadata.stopReason),typeof c.metadata?.usage=="object"&&c.metadata.usage!==null){let l=c.metadata.usage;t._currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}}finally{a.dispose()}if(o)throw o;if(r)return r;if(t._lastStreamedContent.length>0)return t._lastStopReason??=zo,{role:"assistant",content:t._lastStreamedContent,timestamp:new Date};if(t._lastStopReason===Tt||t._lastStopReason===At){let c=t._lastStopReason===Tt?"tool-use iteration cap":"wall-clock budget";return{role:"assistant",content:`[subagent ${t.id} reached its ${c} before producing a final message; returning a partial result]`,timestamp:new Date}}throw t._controller.signal.aborted||t._currentStatus==="cancelled"?new Error(`Subagent ${t.id} produced no terminal message`):(t._lastStopReason=zo,xO(t.id,t._currentTrace.toolResults))}async function PO(t,e,n){try{let r=await t.run(e,n);return AM(t.id,t._currentStatus,r,t._outputSchema,t._currentTrace,t._lastStopReason)}catch(r){let o=Hu(t.id,t._currentStatus,r,t._currentTrace,t._lastStopReason);if(t._lastStreamedContent.length>0)o.partialOutput=t._lastStreamedContent;else if(r instanceof nt){let s=IO(t.id,t._currentTrace.toolResults);s!==void 0&&(o.partialOutput=s)}return o}}function MO(t,e,n,r){let o;if(r){let s=t._progressSink??Et();o=(i,a)=>{r(i),s?.(i,a)}}t.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{O("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async function xb(t,e,n){if(t._stopDispatched){t._onTerminal();return}t._stopDispatched=!0;let r=await Dk(t._hookRegistry,{event:"SubagentStop",subagentId:t.id,status:e,lastMessage:t._lastMessage,agentType:t._agentType,durationMs:t._lastDurationMs,trace:t._currentTrace},t._traceWriter?{traceWriter:t._traceWriter}:{});if(r.injectContext){if(t._parentAbortSignal?.aborted)O(`Skipping SubagentStop injectContext for ${t.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)t._lastStopInjectContext=r.injectContext;else if(t._parentInputStreamRef)try{let o=t._parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){O(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}t._onTerminal()}var OO=g(()=>{"use strict";se();re();Ar();nl();V();RO();$o();An();_e();CO()});var tp,DO=g(()=>{"use strict";re();Hh();V();TO();_e();OO();tp=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,f,m,h,y=0){this.id=e;this.session=n;this._controller=r;this.abortGraph=o;this._outputSchema=s;this.timeoutMs=i;this._hookRegistry=a;this._onTerminal=c;this._parentInputStreamRef=l;this._parentAbortSignal=d;this._agentType=u;this._traceWriter=m;this.onSubagentSucceeded=h;this._idleTimeoutMs=y;this._progressSink=p,this._parentId=f}id;session;_controller;abortGraph;_outputSchema;timeoutMs;_hookRegistry;_onTerminal;_parentInputStreamRef;_parentAbortSignal;_agentType;_traceWriter;onSubagentSucceeded;_idleTimeoutMs;_currentStatus="idle";inFlight=null;_lastMessage;_lastDurationMs;latestTerminalStatus;_stopDispatched=!1;_lastStopInjectContext;_progressSink;_parentId;_currentTrace=Jo();_lastStreamedContent="";_pauseCeiling;_lastStopReason;_logWriter;get status(){return this._currentStatus}async run(e,n){if(this._currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this._lastStopReason=void 0,this._currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this._currentStatus="running";let r=Date.now(),o=Number.isFinite(this.timeoutMs)&&this.timeoutMs>0?new Zu(this.timeoutMs,Tb,i=>{W(this._traceWriter,{phase:"pause_extension_granted",metadata:{subagentId:this.id,grantMs:i.grantMs,totalGrantedMs:i.totalGrantedMs,remainingCapMs:i.remainingCapMs,grantCount:i.grantCount,...i.pauseDescription!==void 0&&{pauseDescription:i.pauseDescription}}})}):void 0;this._pauseCeiling=o;let s=Pd(Rb(this,e,n),this.timeoutMs,{controller:this._controller,label:this.id,...o!==void 0&&{extender:o}});this.inFlight=s;try{let i=await s;this._lastMessage=i.content,this._lastDurationMs=Date.now()-r,this._currentStatus="succeeded",this.latestTerminalStatus="succeeded";let a=i;this._drainingMessages=!0;try{for(;this._pendingUserMessages.length>0&&!this._controller.signal.aborted;){let l=this._pendingUserMessages.shift();a=await Rb(this,l,n),this._lastMessage=a.content,this._currentTrace.turnCount++}}catch{this._pendingUserMessages.length=0}this._drainingMessages=!1,await Zn(this._traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:Date.now()-r,turnCount:this._currentTrace.turnCount,outputBytes:Buffer.byteLength(this._lastMessage,"utf8"),...this._lastStopReason!==void 0&&{stopReason:this._lastStopReason}});let c=typeof a.metadata?.totalCostUsd=="number"?a.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this._currentTrace.usage,c),this._onTerminal(),a}catch(i){this._lastDurationMs=Date.now()-r;let a=this._controller.signal.aborted&&this._controller.signal.reason instanceof Ee&&!this.abortGraph.isCascading(this.id)?this._controller.signal.reason:void 0,c=a??i;if(this._currentStatus!=="cancelled")if(this._controller.signal.aborted&&a===void 0){let l=this._controller.signal.reason instanceof Ee;await Zn(this._traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade",...l?{timeout:!0}:{}}),this._currentStatus="cancelled",this.latestTerminalStatus="cancelled"}else await Zn(this._traceWriter,{transition:"failed",subagentId:this.id,errorClass:c instanceof Error?c.constructor.name:"Unknown",errorMessage:c instanceof Error?c.message:String(c),partialOutputBytes:Buffer.byteLength(this._lastStreamedContent,"utf8"),...a!==void 0?{failureClass:"timeout"}:{}}),this._currentStatus="failed",this.latestTerminalStatus="failed";throw this._onTerminal(),c}finally{this.inFlight=null}}async runToResult(e,n){return PO(this,e,n)}runInBackground(e,n,r){return MO(this,e,n,r)}async cancel(){if(this._currentStatus==="cancelled"||this._stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this._currentStatus="cancelled",Zn(this._traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"});try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await xb(this,e)}}async teardown(e){if(this._stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await xb(this,n,e)}}getLastStopInjectContext(){return this._lastStopInjectContext}_pendingUserMessages=[];_drainingMessages=!1;sendMessage(e){e.trim()&&((this._currentStatus==="succeeded"||this._currentStatus==="failed"||this._currentStatus==="cancelled")&&!this._drainingMessages||this._pendingUserMessages.push(e))}}});function FO(t){return Yd(Ot(t))}function LO(t,e){return t===void 0||!FO(t)||q(t)!=="openai-compatible"?{model:t}:e===void 0||FO(e)||q(e)!=="openai-compatible"?{model:t}:{model:e,coercedFrom:t}}var NO=g(()=>{"use strict";ue();Qd();Ce()});function UO(t){let{options:e,counter:n,managerHookRegistry:r,parentTraceWriter:o,parentModel:s}=t,a=`${(e.idPrefix??"subagent").replace(/[^A-Za-z0-9_-]/g,"-")}-${Date.now()}-${n}`,c=e.parent.sessionId,l=e.config.hookRegistry??r??e.parent.hookRegistry,d=e.config.traceWriter??o,u=LO(e.config.model,s),p=u.model??e.config.model,f=e.config.timeoutMs??da();return{id:a,resume:c,registry:l,effectiveTraceWriter:d,effectiveChildModel:p,coercedFrom:u.coercedFrom,effectiveTimeoutMs:f}}var $O=g(()=>{"use strict";NO();ua()});var np,BO=g(()=>{"use strict";np=class{entries=new Map;capacity;constructor(e=30){this.capacity=Math.max(1,e)}add(e,n,r){this.entries.delete(e),this.entries.set(e,{handle:n,result:r,completedAt:Date.now()}),this.evictIfNeeded()}recordHandle(e,n,r,o,s){let i=r==="succeeded"?{id:e,status:r,trace:o,...s!==void 0&&{stopReason:s}}:{id:e,status:r,error:new Error(`subagent terminated with status: ${r}`),trace:o,...s!==void 0&&{stopReason:s}};this.add(e,n,i)}get(e){return this.entries.get(e)}list(){return[...this.entries.values()].reverse()}get size(){return this.entries.size}delete(e){return this.entries.delete(e)}clear(){this.entries.clear()}evictIfNeeded(){for(;this.entries.size>this.capacity;){let e=this.entries.keys().next().value;if(e!==void 0)this.entries.delete(e);else break}}}});import*as Zo from"node:fs";var jO,HO,fa,WO=g(()=>{"use strict";L();j();jO=1048576,HO=new Set,fa=class{constructor(e,n){this.sessionLabel=e;this.subagentId=n;this.logPath=OS(e,n);let r=Cf(e);if(!HO.has(r))try{Zo.mkdirSync(r,{recursive:!0}),HO.add(r)}catch{this.errored=!0}}sessionLabel;subagentId;logPath;stream=null;errored=!1;closed=!1;streamReady=!1;pendingLines=[];readyPromise=null;readyResolve=null;bytesWritten=0;static isEnabled(){return S.AFK_SUBAGENT_LOG==="1"}write(e){if(this.errored||this.closed||this.bytesWritten>=jO)return;let n=JSON.stringify(e)+`
|
|
1189
|
+
${n}`:n}}}return{...t,systemPrompt:n}}var yO=g(()=>{"use strict"});function da(){let t=S.AFK_SUBAGENT_TIMEOUT_MS;if(t===void 0||t.trim()==="")return vb;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?vb:e}function bO(){let t=S.AFK_SUBAGENT_IDLE_TIMEOUT_MS;if(t===void 0||t.trim()==="")return kb;let e=Number.parseInt(t,10);return!Number.isFinite(e)||e<0?kb:e}var _b,Ab,vb,kb,bb,wO,ua=g(()=>{"use strict";L();_b=async(t,e)=>({action:"decline"}),Ab=50,vb=45*6e4;kb=8*6e4;bb=60*6e4,wO=5e3});function SO(t){let{options:e,id:n,resume:r,registry:o,effectiveChildModel:s,effectiveTimeoutMs:i,inheritedReadRoots:a,composedWriteRoots:c,childController:l,parentCwd:d,parentApiKey:u,parentBaseUrl:p,parentProvider:f,parentTraceWriter:m,parentSurface:h,parentCanUseTool:y}=t,b=r??(typeof e.config.systemPrompt=="string"?e.config.systemPrompt:""),k=t.workspaceStore?t.workspaceStore.queryRelevant(null,b):[],_=hO({...e.config,isSubagentFork:!0,model:s,resume:r,forkSession:r?!0:e.config.forkSession,subagentId:n,subagentToolOutputCapBytes:1e5,abortSignal:l.signal,apiKey:NP({childModel:s,configApiKey:e.config.apiKey,parentApiKey:u,parentProvider:f}),baseUrl:e.config.baseUrl??(q(s)==="openai-compatible"?void 0:p),isNonInteractive:e.config.isNonInteractive??!0,maxToolUseIterations:e.config.maxToolUseIterations??Ab,softDeadlineMs:e.config.softDeadlineMs??Dd(i),autoResumeOnUsageLimit:e.config.autoResumeOnUsageLimit??!1,...e.config.parentSessionId===void 0&&e.parent.sessionId!==void 0?{parentSessionId:e.parent.sessionId}:{},...e.config.phaseRole===void 0&&e.phaseRole!==void 0?{phaseRole:e.phaseRole}:{},...e.config.cwd===void 0&&d!==void 0?{cwd:d}:{},...a!==void 0?{readRoots:a}:{},...c!==void 0?{writeRoots:c}:{},...e.config.traceWriter===void 0&&m!==void 0?{traceWriter:m}:{},...e.config.surface===void 0&&h!==void 0?{surface:h}:{},hookRegistry:o,permissionBubbler:e.config.permissionBubbler??(y!==void 0&&e.config.canUseTool===void 0?{canUseTool:y}:void 0),...e.denyElicitations===!1?{}:{onElicitation:_b},...e.phaseRole==="read-only"?{provider:gO("read-only",s)}:{}});return t.workspaceStore?gm(_,k):_}var vO=g(()=>{"use strict";ue();Rt();wn();Tu();yO();Vn();ua();An()});function kO(t){let{effectiveTraceWriter:e,id:n,parentSessionId:r,rootId:o,effectiveChildModel:s,childConfig:i,promptHead:a,effectiveAgentType:c,effectiveResolvedAgentType:l}=t,d=typeof s=="string"?s:JSON.stringify(s);return Zn(e,{transition:"started",subagentId:n,parentId:r??o,model:d,...i.tools?.allowedTools?{allowedTools:[...i.tools.allowedTools]}:{},...a&&a.trim()!==""?{promptHead:a.slice(0,80)}:{},...c?{agentType:c}:{},...l?{resolvedAgentType:l}:{}}),d}async function _O(t){let{modelString:e,id:n,idPrefix:r,parentSessionId:o,effectiveResolvedAgentType:s}=t;await te({event:"subagent.dispatched",subagent_id:n,id_prefix:r,model:e,parent_session_id:o,resolved_agent_type:s})}var AO=g(()=>{"use strict";V();vt()});function pa(t,e=Date.now()){if(t.type==="paused")return t.resetsAt===void 0?void 0:t.resetsAt.getTime()-e+3e4;if(t.type==="rate_limit"){let n=t.retryAfterMs;return typeof n!="number"||!Number.isFinite(n)||n<=0?void 0:n+3e4}}function EO(t){if(t.type==="paused"){let e=t.resetsAt!==void 0?t.resetsAt.toISOString():"unknown";return`paused (${t.reason}, resetsAt=${e})`}if(t.type==="rate_limit"){let e=t.retryAfterMs;return`rate_limit (retryAfterMs=${typeof e=="number"?e:"unknown"})`}}var Eb=g(()=>{"use strict"});var Tb,$5,Zu,TO=g(()=>{"use strict";Eb();Tb=120*6e4,$5=1e3,Zu=class{constructor(e,n=Tb,r){this.baseTimeoutMs=e;this.maxExtensionMs=n;this.onGrant=r}baseTimeoutMs;maxExtensionMs;pauseStartedAtMs;pauseWindowCapMs=0;closedCreditMs=0;lastPauseDescription;grantedMs=0;grantCount=0;onGrant;onEvent(e){if(e.type==="resumed"){this.closePause();return}if(e.type!=="paused"&&e.type!=="rate_limit")return;this.closeExpiredPause();let n=pa(e);if(n===void 0||n<=0)return;let r=Date.now();if(this.pauseStartedAtMs===void 0)this.pauseStartedAtMs=r,this.pauseWindowCapMs=n;else{let o=r-this.pauseStartedAtMs;this.pauseWindowCapMs=Math.max(this.pauseWindowCapMs,o+n)}this.lastPauseDescription=EO(e)}openPauseCreditMs(){if(this.pauseStartedAtMs===void 0)return 0;let e=Date.now()-this.pauseStartedAtMs;return Math.max(0,Math.min(e,this.pauseWindowCapMs))}closePause(){this.pauseStartedAtMs!==void 0&&(this.closedCreditMs+=this.openPauseCreditMs(),this.pauseStartedAtMs=void 0,this.pauseWindowCapMs=0)}closeExpiredPause(){this.pauseStartedAtMs!==void 0&&Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs&&this.closePause()}onDeadline(){let e=this.maxExtensionMs-this.grantedMs;if(!(e>0))return 0;this.closeExpiredPause();let r=this.closedCreditMs+this.openPauseCreditMs()-this.grantedMs;if(r<=0)return 0;let o=Math.min(Math.max(r,$5),e);if(this.grantedMs+=o,this.grantCount+=1,this.onGrant)try{this.onGrant({grantMs:o,totalGrantedMs:this.grantedMs,remainingCapMs:this.maxExtensionMs-this.grantedMs,grantCount:this.grantCount,pauseDescription:this.lastPauseDescription})}catch{}return o}describe(){if(this.lastPauseDescription===void 0)return;let e=[`base budget ${this.baseTimeoutMs}ms`,`pause extension granted ${this.grantedMs}ms across ${this.grantCount} extension${this.grantCount===1?"":"s"} (cap ${this.maxExtensionMs}ms${this.grantedMs>=this.maxExtensionMs?", EXHAUSTED":""})`,`last provider pause: ${this.lastPauseDescription}`];if(this.pauseStartedAtMs!==void 0){let r=Date.now()-this.pauseStartedAtMs>=this.pauseWindowCapMs?"expired":"still open";e.push(`last pause ${r}, opened ${new Date(this.pauseStartedAtMs).toISOString()} (reported window ${this.pauseWindowCapMs}ms)`)}return`[pause-aware ceiling: ${e.join("; ")}]`}get totalGrantedMs(){return this.grantedMs}}});var ep,RO=g(()=>{"use strict";re();Eb();ep=class{constructor(e,n,r,o){this.controller=e;this.idleTimeoutMs=n;this.label=r;this.onFire=o;this.isEnabled()&&this.arm(this.idleTimeoutMs,"none")}controller;idleTimeoutMs;label;onFire;timer;disposed=!1;fired=!1;inFlightTools=new Set;isEnabled(){return Number.isFinite(this.idleTimeoutMs)&&this.idleTimeoutMs>0}onEvent(e){if(!(!this.isEnabled()||this.disposed||this.fired)){if(e.type==="chunk"){if(e.chunk.type==="tool_use_detail"){this.inFlightTools.add(e.chunk.toolUseId),this.clearTimer();return}if(e.chunk.type==="tool_result"){this.inFlightTools.delete(e.chunk.toolUseId),this.inFlightTools.size===0&&this.arm(this.idleTimeoutMs,e.chunk.type);return}}if(!(this.inFlightTools.size>0)){if(e.type==="paused"){this.arm(this.pausedWindowMs(e),e.type);return}if(e.type==="rate_limit"){let n=pa(e);if(n!==void 0&&n>0){this.arm(n,e.type);return}}this.arm(this.idleTimeoutMs,e.type)}}}pausedWindowMs(e){let n=pa(e);return n===void 0?this.idleTimeoutMs:Math.max(this.idleTimeoutMs,n)}arm(e,n){this.timer!==void 0&&clearTimeout(this.timer);let r=e>0?e:this.idleTimeoutMs,o=Date.now(),s=setTimeout(()=>{this.fire(Date.now()-o,n)},r);s.unref(),this.timer=s}clearTimer(){this.timer!==void 0&&(clearTimeout(this.timer),this.timer=void 0)}fire(e,n){if(!(this.fired||this.disposed)){this.fired=!0,this.timer=void 0;try{this.onFire?.({idleTimeoutMs:this.idleTimeoutMs,elapsedSinceLastProgressMs:e,lastEventType:n})}catch{}this.controller.signal.aborted||this.controller.abort(new Uc(`subagent ${this.label} idle-watchdog fired: no observable progress for ${this.idleTimeoutMs}ms (last event: ${n}). The child stream produced no output for the idle window \u2014 typically a stalled model call under provider throttling with no detectable backoff bracket. Aborting so partial output (if any) is returned; the parent should retry or fall back.`,this.idleTimeoutMs))}}dispose(){this.disposed||(this.disposed=!0,this.inFlightTools.clear(),this.clearTimer())}}});function xO(t,e){let n=e.length,r=n>0?`subagent ${t} stream cut off after ${n} tool result(s); see partialOutput.`:`subagent ${t} produced no output \u2014 stream ended without a terminal message (stream_incomplete). No findings were produced; retry or fall back.`,o=new nt(r);return n>0&&(o.toolResultsGathered=n),o}function IO(t,e){if(e.length===0)return;let n=e.reduce((s,i)=>s+(i.sizeBytes??0),0),r=e.filter(s=>s.isError).length,o=r>0?` (${r} errored)`:"";return`[Stream cut off before any assistant text was produced. Subagent ${t} completed ${e.length} tool result(s)${o} (~${n} bytes total) before the cut. The run is failed \u2014 no final answer was produced \u2014 but tool evidence is available via result.trace for recovery or retry decisions.]`}var CO=g(()=>{"use strict";re()});async function Rb(t,e,n){let r,o;t._lastStreamedContent="",t._currentTrace=Jo();let s=n??t._progressSink??Et(),i={subagentId:t.id,...t._parentId!==void 0&&{parentId:t._parentId},...t._agentType!==void 0&&{agentType:t._agentType}},a=new ep(t._controller,t._idleTimeoutMs,t.id,c=>{W(t._traceWriter,{phase:"idle_watchdog_fired",metadata:{idleTimeoutMs:c.idleTimeoutMs,elapsedSinceLastProgressMs:c.elapsedSinceLastProgressMs,lastEventType:c.lastEventType}})});try{for await(let c of t.session.sendMessageStream(e)){if(s&&s(c,i),t._logWriter?.write(c),a.onEvent(c),t._pauseCeiling?.onEvent(c),c.type==="chunk"){let l=c.chunk;l.type==="content"?t._lastStreamedContent+=l.content:l.type==="tool_use_detail"?t._currentTrace.toolCalls.push({id:l.toolUseId,name:l.toolName,inputBytes:Buffer.byteLength(l.toolInput,"utf8")}):l.type==="tool_result"?t._currentTrace.toolResults.push({toolUseId:l.toolUseId,isError:l.isError,truncated:l.truncated,sizeBytes:l.sizeBytes}):l.type==="thinking"&&(t._currentTrace.thinkingPresent=!0)}if(c.type==="message")r=c.message,t._currentTrace.turnCount++;else if(c.type==="error"){o=c.error;break}else if(c.type==="done"){if(typeof c.metadata?.stopReason=="string"&&(t._lastStopReason=c.metadata.stopReason),typeof c.metadata?.usage=="object"&&c.metadata.usage!==null){let l=c.metadata.usage;t._currentTrace.usage={inputTokens:typeof l.input_tokens=="number"?l.input_tokens:void 0,outputTokens:typeof l.output_tokens=="number"?l.output_tokens:void 0,cacheReadTokens:typeof l.cache_read_input_tokens=="number"?l.cache_read_input_tokens:void 0,cacheCreationTokens:typeof l.cache_creation_input_tokens=="number"?l.cache_creation_input_tokens:void 0}}break}}}finally{a.dispose()}if(o)throw o;if(r)return r;if(t._lastStreamedContent.length>0)return t._lastStopReason??=zo,{role:"assistant",content:t._lastStreamedContent,timestamp:new Date};if(t._lastStopReason===Tt||t._lastStopReason===At){let c=t._lastStopReason===Tt?"tool-use iteration cap":"wall-clock budget";return{role:"assistant",content:`[subagent ${t.id} reached its ${c} before producing a final message; returning a partial result]`,timestamp:new Date}}throw t._controller.signal.aborted||t._currentStatus==="cancelled"?new Error(`Subagent ${t.id} produced no terminal message`):(t._lastStopReason=zo,xO(t.id,t._currentTrace.toolResults))}async function PO(t,e,n){try{let r=await t.run(e,n);return AM(t.id,t._currentStatus,r,t._outputSchema,t._currentTrace,t._lastStopReason)}catch(r){let o=Hu(t.id,t._currentStatus,r,t._currentTrace,t._lastStopReason);if(t._lastStreamedContent.length>0)o.partialOutput=t._lastStreamedContent;else if(r instanceof nt){let s=IO(t.id,t._currentTrace.toolResults);s!==void 0&&(o.partialOutput=s)}return o}}function MO(t,e,n,r){let o;if(r){let s=t._progressSink??Et();o=(i,a)=>{r(i),s?.(i,a)}}t.runToResult(e,o).then(s=>{n?.(s)}).catch(s=>{O("runInBackground: unexpected rejection after runToResult",s),console.error("Subagent runInBackground failed unexpectedly:",s)})}async function xb(t,e,n){if(t._stopDispatched){t._onTerminal();return}t._stopDispatched=!0;let r=await Dk(t._hookRegistry,{event:"SubagentStop",subagentId:t.id,status:e,lastMessage:t._lastMessage,agentType:t._agentType,durationMs:t._lastDurationMs,trace:t._currentTrace},t._traceWriter?{traceWriter:t._traceWriter}:{});if(r.injectContext){if(t._parentAbortSignal?.aborted)O(`Skipping SubagentStop injectContext for ${t.id}: parent is aborted`);else if(n?.deferInjectContextToCaller)t._lastStopInjectContext=r.injectContext;else if(t._parentInputStreamRef)try{let o=t._parentInputStreamRef;o.queueFrameworkContext?o.queueFrameworkContext(r.injectContext):o.pushUserMessage(r.injectContext)}catch(o){O(`Failed to inject context from SubagentStop handler: ${String(o)}`)}}t._onTerminal()}var OO=g(()=>{"use strict";se();re();Ar();nl();V();RO();$o();An();_e();CO()});var tp,DO=g(()=>{"use strict";re();Hh();V();TO();_e();OO();tp=class{constructor(e,n,r,o,s,i,a,c,l,d,u,p,f,m,h,y=0){this.id=e;this.session=n;this._controller=r;this.abortGraph=o;this._outputSchema=s;this.timeoutMs=i;this._hookRegistry=a;this._onTerminal=c;this._parentInputStreamRef=l;this._parentAbortSignal=d;this._agentType=u;this._traceWriter=m;this.onSubagentSucceeded=h;this._idleTimeoutMs=y;this._progressSink=p,this._parentId=f}id;session;_controller;abortGraph;_outputSchema;timeoutMs;_hookRegistry;_onTerminal;_parentInputStreamRef;_parentAbortSignal;_agentType;_traceWriter;onSubagentSucceeded;_idleTimeoutMs;_currentStatus="idle";inFlight=null;_lastMessage;_lastDurationMs;latestTerminalStatus;_stopDispatched=!1;_lastStopInjectContext;_progressSink;_parentId;_currentTrace=Jo();_lastStreamedContent="";_pauseCeiling;_lastStopReason;_logWriter;get status(){return this._currentStatus}get durationMs(){return this._lastDurationMs}async run(e,n){if(this._currentStatus==="running")throw new Error(`Subagent ${this.id} is already running`);if(this._lastStopReason=void 0,this._currentStatus==="cancelled")throw new Error(`Subagent ${this.id} is cancelled`);this._currentStatus="running";let r=Date.now(),o=Number.isFinite(this.timeoutMs)&&this.timeoutMs>0?new Zu(this.timeoutMs,Tb,i=>{W(this._traceWriter,{phase:"pause_extension_granted",metadata:{subagentId:this.id,grantMs:i.grantMs,totalGrantedMs:i.totalGrantedMs,remainingCapMs:i.remainingCapMs,grantCount:i.grantCount,...i.pauseDescription!==void 0&&{pauseDescription:i.pauseDescription}}})}):void 0;this._pauseCeiling=o;let s=Pd(Rb(this,e,n),this.timeoutMs,{controller:this._controller,label:this.id,...o!==void 0&&{extender:o}});this.inFlight=s;try{let i=await s;this._lastMessage=i.content,this._lastDurationMs=Date.now()-r,this._currentStatus="succeeded",this.latestTerminalStatus="succeeded";let a=i;this._drainingMessages=!0;try{for(;this._pendingUserMessages.length>0&&!this._controller.signal.aborted;){let l=this._pendingUserMessages.shift();a=await Rb(this,l,n),this._lastMessage=a.content,this._currentTrace.turnCount++}}catch{this._pendingUserMessages.length=0}this._drainingMessages=!1,await Zn(this._traceWriter,{transition:"succeeded",subagentId:this.id,durationMs:Date.now()-r,turnCount:this._currentTrace.turnCount,outputBytes:Buffer.byteLength(this._lastMessage,"utf8"),...this._lastStopReason!==void 0&&{stopReason:this._lastStopReason}});let c=typeof a.metadata?.totalCostUsd=="number"?a.metadata.totalCostUsd:void 0;return this.onSubagentSucceeded?.(this._currentTrace.usage,c),this._onTerminal(),a}catch(i){this._lastDurationMs=Date.now()-r;let a=this._controller.signal.aborted&&this._controller.signal.reason instanceof Ee&&!this.abortGraph.isCascading(this.id)?this._controller.signal.reason:void 0,c=a??i;if(this._currentStatus!=="cancelled")if(this._controller.signal.aborted&&a===void 0){let l=this._controller.signal.reason instanceof Ee;await Zn(this._traceWriter,{transition:"cancelled",subagentId:this.id,source:"cascade",...l?{timeout:!0}:{}}),this._currentStatus="cancelled",this.latestTerminalStatus="cancelled"}else await Zn(this._traceWriter,{transition:"failed",subagentId:this.id,errorClass:c instanceof Error?c.constructor.name:"Unknown",errorMessage:c instanceof Error?c.message:String(c),partialOutputBytes:Buffer.byteLength(this._lastStreamedContent,"utf8"),...a!==void 0?{failureClass:"timeout"}:{}}),this._currentStatus="failed",this.latestTerminalStatus="failed";throw this._onTerminal(),c}finally{this.inFlight=null}}async runToResult(e,n){return PO(this,e,n)}runInBackground(e,n,r){return MO(this,e,n,r)}async cancel(){if(this._currentStatus==="cancelled"||this._stopDispatched)return;let e=this.latestTerminalStatus??"cancelled";this._currentStatus="cancelled",Zn(this._traceWriter,{transition:"cancelled",subagentId:this.id,source:"explicit"});try{this.abortGraph.abort(this.id,"cancelled")}catch{}try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await xb(this,e)}}async teardown(e){if(this._stopDispatched)return;let n=this.latestTerminalStatus??"cancelled";try{this.inFlight&&await this.session.interrupt()}catch{}try{await this.session.close()}finally{await xb(this,n,e)}}getLastStopInjectContext(){return this._lastStopInjectContext}_pendingUserMessages=[];_drainingMessages=!1;sendMessage(e){e.trim()&&((this._currentStatus==="succeeded"||this._currentStatus==="failed"||this._currentStatus==="cancelled")&&!this._drainingMessages||this._pendingUserMessages.push(e))}}});function FO(t){return Yd(Ot(t))}function LO(t,e){return t===void 0||!FO(t)||q(t)!=="openai-compatible"?{model:t}:e===void 0||FO(e)||q(e)!=="openai-compatible"?{model:t}:{model:e,coercedFrom:t}}var NO=g(()=>{"use strict";ue();Qd();Ce()});function UO(t){let{options:e,counter:n,managerHookRegistry:r,parentTraceWriter:o,parentModel:s}=t,a=`${(e.idPrefix??"subagent").replace(/[^A-Za-z0-9_-]/g,"-")}-${Date.now()}-${n}`,c=e.parent.sessionId,l=e.config.hookRegistry??r??e.parent.hookRegistry,d=e.config.traceWriter??o,u=LO(e.config.model,s),p=u.model??e.config.model,f=e.config.timeoutMs??da();return{id:a,resume:c,registry:l,effectiveTraceWriter:d,effectiveChildModel:p,coercedFrom:u.coercedFrom,effectiveTimeoutMs:f}}var $O=g(()=>{"use strict";NO();ua()});var np,BO=g(()=>{"use strict";np=class{entries=new Map;capacity;constructor(e=30){this.capacity=Math.max(1,e)}add(e,n,r){this.entries.delete(e),this.entries.set(e,{handle:n,result:r,completedAt:Date.now()}),this.evictIfNeeded()}recordHandle(e,n,r,o,s){let i=r==="succeeded"?{id:e,status:r,trace:o,...s!==void 0&&{stopReason:s}}:{id:e,status:r,error:new Error(`subagent terminated with status: ${r}`),trace:o,...s!==void 0&&{stopReason:s}};this.add(e,n,i)}get(e){return this.entries.get(e)}list(){return[...this.entries.values()].reverse()}get size(){return this.entries.size}delete(e){return this.entries.delete(e)}clear(){this.entries.clear()}evictIfNeeded(){for(;this.entries.size>this.capacity;){let e=this.entries.keys().next().value;if(e!==void 0)this.entries.delete(e);else break}}}});import*as Zo from"node:fs";var jO,HO,fa,WO=g(()=>{"use strict";L();j();jO=1048576,HO=new Set,fa=class{constructor(e,n){this.sessionLabel=e;this.subagentId=n;this.logPath=OS(e,n);let r=Cf(e);if(!HO.has(r))try{Zo.mkdirSync(r,{recursive:!0}),HO.add(r)}catch{this.errored=!0}}sessionLabel;subagentId;logPath;stream=null;errored=!1;closed=!1;streamReady=!1;pendingLines=[];readyPromise=null;readyResolve=null;bytesWritten=0;static isEnabled(){return S.AFK_SUBAGENT_LOG==="1"}write(e){if(this.errored||this.closed||this.bytesWritten>=jO)return;let n=JSON.stringify(e)+`
|
|
1190
1190
|
`;if(!this.stream){this.pendingLines.push(n),this.openStream();return}if(!this.streamReady){this.pendingLines.push(n);return}this.writeLine(n)}async close(){if(!this.closed)return this.closed=!0,this.readyPromise&&await this.readyPromise,new Promise(e=>{if(!this.stream||this.errored){e();return}this.stream.end(()=>e())})}openStream(){if(!this.stream){this.readyPromise=new Promise(e=>{this.readyResolve=e});try{let e=Zo.createWriteStream(this.logPath,{flags:"a",encoding:"utf8",mode:384});this.stream=e,e.once("open",()=>{this.streamReady=!0;for(let n of this.pendingLines)this.writeLine(n);this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null}),e.once("error",()=>{this.errored=!0,this.pendingLines=[],this.readyResolve?.(),this.readyResolve=null})}catch{this.errored=!0,this.readyResolve?.(),this.readyResolve=null}}}writeLine(e){this.errored||!this.stream||this.bytesWritten>=jO||(this.bytesWritten+=Buffer.byteLength(e,"utf8"),this.stream.write(e))}}});var J,he=g(()=>{"use strict";Yx();Vh();nl();Ar();Zh();cC();uC();ue();fC();vO();AO();DO();$O();BO();WO();ua();J=class{active=new Map;completed=new np;parentCanUseTool;hookRegistry;progressSink;parentApiKey;parentBaseUrl;parentProvider;parentModel;parentCwd;parentReadRoots;worktreeMainRootCache=new Map;parentTraceWriter;parentSurface;parentAbortSignal;workspaceStore;sessionLabel;abortGraph;rootId;rootController;counter=0;onSubagentSucceededCb;constructor(e={}){if(this.parentCanUseTool=e.canUseTool,this.hookRegistry=e.hookRegistry,this.progressSink=e.progressSink,this.parentApiKey=e.apiKey,this.parentBaseUrl=e.baseUrl,this.parentProvider=e.parentModel!==void 0?q(e.parentModel):void 0,this.parentModel=e.parentModel,this.parentCwd=e.cwd,this.parentReadRoots=e.parentReadRoots,this.parentTraceWriter=e.traceWriter,this.parentSurface=e.surface,this.parentAbortSignal=e.parentAbortSignal,this.onSubagentSucceededCb=e.onSubagentSucceeded,this.workspaceStore=e.workspaceStore,this.sessionLabel=e.sessionLabel,this.abortGraph=new Ad(e.traceWriter),this.rootId=`manager-root-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,this.rootController=new AbortController,this.abortGraph.register(this.rootId,this.rootController),e.parentAbortSignal){let n=e.parentAbortSignal;n.aborted?this.rootController.abort(n.reason):n.addEventListener("abort",()=>{this.rootController.signal.aborted||this.rootController.abort(n.reason)},{once:!0})}}list(){return[...this.active.values()].map(e=>({id:e.id,status:e.status}))}get(e){return this.active.get(e)??this.completed.get(e)?.handle}onChildAborted(e){return this.abortGraph.onChildAborted(this.rootId,e)}setOnSubagentSucceeded(e){this.onSubagentSucceededCb=e}setCwd(e){this.parentCwd=e,this.worktreeMainRootCache.delete(e)}setTraceWriter(e){this.parentTraceWriter=e,this.abortGraph.setTraceWriter(e)}getReadScopeInputs(){return{parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd}}async resolveMainRootForCwd(e){if(this.worktreeMainRootCache.has(e))return this.worktreeMainRootCache.get(e);let n=await aC(e);return this.worktreeMainRootCache.set(e,n),n}abortAll(e,n="user_signal"){this.abortGraph.abort(this.rootId,e,n)}async forkSubagent(e){pC(e);let{id:n,resume:r,registry:o,effectiveTraceWriter:s,effectiveChildModel:i,coercedFrom:a,effectiveTimeoutMs:c}=UO({options:e,counter:++this.counter,managerHookRegistry:this.hookRegistry,parentTraceWriter:this.parentTraceWriter,parentModel:this.parentModel});o&&await Ok(o,{event:"SubagentStart",subagentId:n,parentSessionId:e.parent.sessionId},{signal:this.rootController.signal,...s?{traceWriter:s}:{}}),a!==void 0&&process.stderr.write(`[afk] subagent: child model "${a}" cannot run on this session's OpenAI/ChatGPT backend \u2014 running it as "${i??""}" instead (set AFK_DEFAULT_SUBAGENT_MODEL to choose a different one).
|
|
1191
1191
|
`);let l=new AbortController;this.abortGraph.register(n,l),this.abortGraph.linkChild(this.rootId,n);let d=e.config.cwd??this.parentCwd,u=await lC({parentReadRoots:this.parentReadRoots,parentCwd:this.parentCwd,effectiveChildCwd:d,callerReadRoots:e.config.readRoots,callerExtraReadRoots:e.config.extraReadRoots,resolveMainRoot:E=>this.resolveMainRootForCwd(E)}),p=dC(e.config.writeRoots,d),f=SO({options:e,id:n,resume:r,registry:o,effectiveChildModel:i,effectiveTimeoutMs:c,inheritedReadRoots:u,composedWriteRoots:p,childController:l,parentCwd:this.parentCwd,parentApiKey:this.parentApiKey,parentBaseUrl:this.parentBaseUrl,parentProvider:this.parentProvider,parentTraceWriter:this.parentTraceWriter,parentSurface:this.parentSurface,parentCanUseTool:this.parentCanUseTool,workspaceStore:this.workspaceStore}),m=()=>{};f.cwd!==void 0&&(Qh(f.cwd),m=iC(f.cwd));let h,y,b,k;try{h=new _r(f);let E=e.parent.getInputStreamRef?.(),R=e.parent.abortSignal,T=this.progressSink??Et();b=e.agentType?.trim()||void 0,k=e.resolvedAgentType?.trim()||void 0;let I=e.parentId?.trim()||void 0,x=this.sessionLabel??e.parent.sessionId,v=fa.isEnabled()&&x?new fa(x,n):void 0;y=new tp(n,h,l,this.abortGraph,e.outputSchema,c,o,()=>{m(),this.completed.add(n,y,{id:n,status:y._currentStatus==="running"?"succeeded":y._currentStatus}),this.active.delete(n),this.abortGraph.dispose(n),v?.close(),this.completed.recordHandle(n,y,y._currentStatus,y._currentTrace,y._lastStopReason)},E,R,b??e.idPrefix,T,I??e.parent.sessionId,s,this.onSubagentSucceededCb,e.config.idleTimeoutMs??bO()),v&&(y._logWriter=v),this.active.set(n,y)}catch(E){throw m(),this.abortGraph.dispose(n),E}let _=kO({effectiveTraceWriter:s,id:n,parentSessionId:e.parent.sessionId,rootId:this.rootId,effectiveChildModel:i,childConfig:f,promptHead:e.promptHead,effectiveAgentType:b,effectiveResolvedAgentType:k});return await _O({modelString:_,id:n,idPrefix:e.idPrefix,parentSessionId:e.parent.sessionId,effectiveResolvedAgentType:k}),y}async kill(e){let n=this.active.get(e);return n?(await n.cancel(),!0):!1}async killAll(){await Promise.allSettled([...this.active.values()].map(e=>e.cancel()))}async abortAllAndDrain(e,n="user_signal",r=wO,o=!1){let s=[...this.active.values()];if(s.length===0)return o&&this.rootController.signal.aborted&&this.rearmRoot(),{drained:0,timedOut:!1};this.abortGraph.abort(this.rootId,e,n);let i=!1,a=new Promise(c=>setTimeout(()=>{i=!0,c()},r).unref());return await Promise.race([Promise.allSettled(s.map(c=>c.cancel())),a]),i&&console.warn(`[SubagentManager] abortAllAndDrain: ${s.length} child(ren) did not settle within ${r}ms \u2014 sealing anyway; their terminal rows may be missing`),o&&this.rearmRoot(),{drained:s.length,timedOut:i}}rearmRoot(){this.rootController=new AbortController,this.abortGraph.rearm(this.rootId,this.rootController),this.parentAbortSignal?.aborted&&this.rootController.abort(this.parentAbortSignal.reason)}async teardownAll(){await Promise.allSettled([...this.active.values()].map(e=>e.teardown()))}}});async function KO(t,e={}){let{failFast:n=!0,teardown:r=!0,maxConcurrency:o=Ys()}=e;if(t.length===0)return[];let s=new Array(t.length),i=new Set(t.map((c,l)=>l)),a=!1;return await no(t.map((c,l)=>l),o,async c=>{let l=t[c];n&&a&&await l.handle.cancel().catch(()=>{});let d=await l.handle.runToResult(l.prompt);if(s[c]=d,i.delete(c),n&&d.status!=="succeeded"){a=!0;for(let u of i){let p=t[u];p&&p.handle.status==="running"&&p.handle.cancel().catch(()=>{})}}}),r&&await Promise.allSettled(t.map(c=>c.handle.teardown())),s}var GO=g(()=>{"use strict";yl()});function qO(t){let e=new Set;for(let n of t){let r=ra(n,B5);r!==void 0&&e.add(r)}return e}var B5,XO=g(()=>{"use strict";Ko();st();ul();B5=new Set([...wt,...Me,"memory_search","agent","skill"])});import{existsSync as Nn,readdirSync as j5,readFileSync as H5}from"fs";import{join as an}from"path";function VO(t=ne()){let e=[],n=an(t,"skills");if(Nn(n))for(let r of rp(n)){let o=an(n,r,"SKILL.md");Nn(o)&&e.push({path:o,type:"skill",source:"user"})}for(let r of zO){let o=an(t,`${r}s`);if(Nn(o))for(let s of rp(o))s.endsWith(".md")&&e.push({path:an(o,s),type:r,source:"user"})}return e}function JO(t=It()){if(!Nn(t))return[];let e=[],n=nn(t);for(let r of n){let s=jy(t,r.path)?.key,i=an(r.path,"skills");if(Nn(i))for(let a of rp(i)){let c=an(i,a,"SKILL.md");if(!Nn(c))continue;let l={path:c,type:"skill",source:"plugin"};s&&(l.plugin_key=s),e.push(l)}for(let a of zO){let c=an(r.path,`${a}s`);if(Nn(c))for(let l of rp(c)){if(!l.endsWith(".md"))continue;let d={path:an(c,l),type:a,source:"plugin"};s&&(d.plugin_key=s),e.push(d)}}}return e}function YO(t=an(ne(),"settings.json")){if(!Nn(t))return[];try{let e=H5(t,"utf8"),r=JSON.parse(e).hooks;if(!r||typeof r!="object")return[];let o=[];for(let[s,i]of Object.entries(r))if(Array.isArray(i))for(let a=0;a<i.length;a++)o.push({event:s,index:a,raw:i[a]});return o}catch{return[]}}function rp(t){try{return j5(t).filter(e=>!e.startsWith("."))}catch{return[]}}var zO,QO=g(()=>{"use strict";j();Wo();zO=["command","agent"]});import{z as ce}from"zod";import{mkdir as ZO,appendFile as e0}from"fs/promises";import{join as Ib}from"path";function G5(t){return{runUserDiscovery:t!=="plugin",runPluginDiscovery:t!=="user",runHookInspector:t!=="plugin"}}function q5(t){let e=()=>{let s={};for(let i of r0)s[i]={correct:0,misfit:0,outlier:0};return s},n={user:e(),plugin:e()};for(let s of t)n[s.source][s.type][s.verdict]+=1;let r={high:0,med:1,low:2},o=t.filter(s=>s.verdict==="misfit").slice().sort((s,i)=>r[s.confidence]-r[i.confidence]);return{inventory:n,misfits:o}}function X5(t){return t.verdict==="misfit"&&t.confidence==="high"&&t.source==="user"}function z5(t){let e=t.filter(o=>o.source==="user"),n=t.filter(o=>o.source==="plugin"),r=["","## Discovered artifacts (audit only these)",""];if(r.push('### User-scope artifacts (set `"source": "user"`, omit `plugin_key`)'),e.length===0)r.push("(none discovered)");else for(let o of e)r.push(`- ${o.path}`);if(r.push(""),r.push('### Plugin-scope artifacts (set `"source": "plugin"`, copy `plugin_key` from each entry)'),n.length===0)r.push("(none discovered)");else for(let o of n){let s=o.plugin_key??"<unknown>";r.push(`- ${o.path} (plugin_key: ${s})`)}return r.join(`
|
|
1192
1192
|
`)}function V5(t,e){let n=["","## Discovered hooks (audit only these)",""];if(n.push(`Settings file (use this absolute path verbatim in each verdict's \`path\` field): \`${t}\``),n.push(""),e.length===0)return n.push("(no hooks discovered)"),n.join(`
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-afk",
|
|
3
|
-
"version": "5.169.
|
|
3
|
+
"version": "5.169.2",
|
|
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",
|