agent-afk 5.130.2 → 5.130.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/telegram.mjs
CHANGED
|
@@ -213,7 +213,7 @@ ${o}`,paths:[e,n]}:o!==null?s={content:o,paths:[n]}:r!==null?s={content:r,paths:
|
|
|
213
213
|
|
|
214
214
|
${e}`}var Rj,pm=g(()=>{"use strict";Rj=new Set(["script","style","noscript","template","svg"])});function Pj(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 rA(t,e,n){let r=Math.min(e*2**t,n);return Math.round(Math.random()*r)}function Mj(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 oA(t,e,n={},r={}){let o=r.retries??3,s=r.baseDelayMs??500,i=r.maxDelayMs??1e4,a=r.sleep??Pj,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(!Cj.has(u.status)||d===o)return u;let p=Mj(u,i)??rA(d,s,i);N("[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=rA(d,s,i);N("[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 Cj,sA=g(()=>{"use strict";se();Cj=new Set([429,502,503,504])});import{BlockList as Oj,isIP as mm}from"node:net";import{lookup as Dj}from"node:dns/promises";import{Agent as Fj}from"undici";function aA(){let t=v.AFK_WEB_ALLOW_PRIVATE_HOSTS?.trim().toLowerCase();return t==="1"||t==="true"}function $j(t){return t.startsWith("[")&&t.endsWith("]")?t.slice(1,-1):t}function fm(t){let e=mm(t);return e===0?!1:Uj.check(t,e===4?"ipv4":"ipv6")}async function cA(t){return Dj(t,{all:!0,verbatim:!0})}async function gm(t,e={}){if(e.allowPrivateHosts??aA())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=$j(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(mm(r)!==0)return fm(r)?{allowed:!1,reason:o(r,r)}:{allowed:!0};let s=e.lookupFn??cA,i;try{i=await s(r)}catch{return{allowed:!0}}for(let a of i)if(fm(a.address))return{allowed:!1,reason:o(a.address,`${r} (resolved)`)};return{allowed:!0}}async function Xs(t,e={}){let n=await gm(t,e);if(!n.allowed)throw new St(n.reason)}async function Gc(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<=iA;i++){await Xs(s,o);let a={...n,redirect:"manual",...t===globalThis.fetch&&!(r.allowPrivateHosts??aA())?{dispatcher:Bj}:{}},c=await oA(t,s,a,r.retry??{});if(!Hj.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 St(`too many redirects (>${iA}) starting from ${e}`)}var Lj,Nj,Uj,St,Bj,iA,Hj,hm=g(()=>{"use strict";L();sA();Lj=[["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]],Nj=[["::",96],["64:ff9b::",96],["fc00::",7],["fe80::",10]],Uj=(()=>{let t=new Oj;for(let[e,n]of Lj)t.addSubnet(e,n,"ipv4");for(let[e,n]of Nj)t.addSubnet(e,n,"ipv6");return t})(),St=class extends Error{constructor(e){super(e),this.name="EgressBlockedError"}};Bj=new Fj({connect:{lookup(t,e,n){cA(t).then(r=>{let o=r.find(i=>fm(i.address));if(o!==void 0){n(new St(`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,mm(s.address))},r=>n(r,"",0))}}});iA=20,Hj=new Set([301,302,303,307,308])});import{readFileSync as jj}from"node:fs";import{join as Wj}from"path";function Kj(t){let n=t.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function lA(t,e){return Kj(e).test(t)}function Xj(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(Gj.has(e))return!0;if(qj.has(e))return!1}return!1}function dA(t){return t===void 0||t.trim()===""?[]:t.split(",").map(e=>e.trim().toLowerCase()).filter(e=>e.length>0)}function zj(t){if(t===void 0||t===""||t==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${t}`)}function uA(t){let e=t===void 0||t.trim()===""?"default":t.trim();return xp(e),e}function Vj(t){if(t===void 0)return!1;let e=t.trim().toLowerCase();return e==="1"||e==="true"||e==="yes"}function Jj(t){try{return jj(t,"utf8")}catch(e){if(e.code==="ENOENT")return;throw e}}function Yj(t,e){let n={...t};if(typeof e.headless=="boolean"&&(n.headless=e.headless),Array.isArray(e.allowedDomains)&&(n.allowedDomains=e.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(e.blockedDomains)&&(n.blockedDomains=e.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof e.domSnapshots=="boolean"&&(n.domSnapshots=e.domSnapshots),e.backend==="playwright")n.backend="playwright";else if(e.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(e.backend)}`);return typeof e.defaultProfile=="string"&&(n.defaultProfile=uA(e.defaultProfile)),n}function pA(t){let e=t?.env??v,n=t?.readFileSync??Jj,r=t?.surface??e.AGENT_SURFACE,o=Xj(e.AFK_BROWSER_HEADLESS,r),s=dA(e.AFK_BROWSER_ALLOWED_DOMAINS),i=dA(e.AFK_BROWSER_BLOCKED_DOMAINS),a=Vj(e.AFK_BROWSER_DOM_SNAPSHOTS),c=zj(e.AFK_BROWSER_BACKEND),l=uA(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():Wj(jt(),"browser.json"),f=n(p);if(f===void 0)return d;let m;try{m=JSON.parse(f)}catch(y){throw new Error(`Failed to parse browser config at ${p}: ${String(y)}`)}if(typeof m!="object"||m===null||Array.isArray(m))throw new Error(`Browser config at ${p} must be a JSON object`);let h=Yj(d,m);return h.configPath=p,h}function qc(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(lA(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return e.allowedDomains.length>0&&!e.allowedDomains.some(o=>lA(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var Gj,qj,Xc=g(()=>{"use strict";L();B();Gj=new Set(["daemon","subagent","telegram","afk"]),qj=new Set(["repl","interactive","cli"])});import{existsSync as Qj,readFileSync as Zj}from"node:fs";import{createRequire as eW}from"node:module";import{dirname as tW,join as nW}from"node:path";function gA(t){if(typeof t=="string")return t;let e=[],n=t;for(let r=0;r<oW&&n instanceof Error;r++)e.push(n.message),n=n.cause;return e.length>0?e.join(" | "):String(t)}function Be(t){let e=gA(t);return mA.some(n=>e.includes(n))}function sW(){try{let e=eW(import.meta.url).resolve("playwright/package.json"),n=JSON.parse(Zj(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=nW(tW(e),o);return Qj(s)?`node ${/\s/.test(s)?`"${s}"`:s} install chromium`:void 0}catch{return}}function zs(){return fA??=sW()??rW,fA}function ym(t){return t.includes("install chromium")}function it(t,e){let n=gA(t),r=e?.latched===!0?` ${iW}`:"";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: ${zs()}.${o}${r}`}return`browser tools require the optional \`playwright\` peer dependency. Install via: pnpm add playwright (then ${zs()}). Or pick a different tool.${r}`}function bm(t,e,n=!1){if(!Be(t))return t;let r=t instanceof Error?t.message:String(t);return new Error(`${r}
|
|
215
215
|
|
|
216
|
-
${it(t,{headless:e,latched:n})}`,{cause:t})}var mA,rW,oW,fA,iW,wm=g(()=>{"use strict";mA=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],rW="pnpm exec playwright install chromium",oW=4;iW="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 nr from"node:fs";import zc from"node:path";import{randomBytes as aW}from"node:crypto";import{chromium as cW}from"playwright";function lW(){try{return"5.130.2"}catch{}try{let t=zc.resolve(import.meta.dirname,"../../../package.json"),e=nr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var dW,Vc,hA=g(()=>{"use strict";wm();B();se();dW=lW(),Vc=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=cW.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=bm(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/${dW}`}}loadStorageState(e){let n=Rp(e);try{if(!nr.existsSync(n))return;let r=JSON.parse(nr.readFileSync(n,"utf8"));return N("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){N("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Rp(e);if(!nr.existsSync(r))return;let o=await n.storageState(),s=zc.join(zc.dirname(r),`.${zc.basename(r)}.${process.pid}.${aW(4).toString("hex")}.tmp`);nr.writeFileSync(s,JSON.stringify(o),{mode:384}),nr.chmodSync(s,384),nr.renameSync(s,r),N("[browser/vault] saved session",{profile:e,file:r})}catch(r){N("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as uW}from"crypto";function yA(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&pW.test(t.label))}function bA(t){return uW("sha256").update(t,"utf8").digest("hex").slice(0,8)}function wA(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var pW,Jc=g(()=>{"use strict";pW=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as fW}from"node:crypto";function mW(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function gW(t,e,n){return`el_${fW("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function hW(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function SA(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function kA(t,e){let n=t.role??"",r=t.name??"";vA.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])kA(s,e)}async function yW(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},AA).catch(()=>[])}async function bW(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},AA).catch(()=>[])}function wW(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Yc(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=wW(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=yW(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,S=!1;u!==null?(y=[],kA(u,y)):(o.push("observation skipped accessibility tree (returned null)"),S=!0,y=(await bW(t)).filter(M=>vA.has(M.role??"")));let _=new Map;for(let C of p){let M=SA(C.name),z=_.get(M);(!z||z.bbox.w===0&&C.bbox.w>0)&&_.set(M,C)}let E=y.map(C=>({ax:C,dom:_.get(SA(C.name??""))})),k=r?E:E.filter(C=>C.dom?C.dom.bbox.w>0||C.dom.bbox.h>0:!0);k.sort((C,M)=>{let z=C.dom?.bbox.y??0,P=M.dom?.bbox.y??0;if(z!==P)return z-P;let H=C.dom?.bbox.x??0,F=M.dom?.bbox.x??0;return H-F}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((C,M)=>{let z=C.ax.role??"generic",P=C.ax.name??"",H=gW(z,P,M),F=C.dom?.bbox??{x:0,y:0,w:0,h:0},U=C.dom?.type??null,$=null;C.ax.value!==void 0&&C.ax.value!==null&&($=String(C.ax.value)),C.ax.checked!==void 0&&($=String(C.ax.checked)),yA({role:z,kind:U})&&($="[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 Fe={id:H,role:z,label:mW(P),kind:U,value:$,state:K,bbox:F};return Q!==void 0&&(Fe.selector=Q),Fe}),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"),S&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let R=hW(f),w=`obs_${e.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:w,url:m,title:h,textSummary:R,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 vA,AA,_A=g(()=>{"use strict";Jc();vA=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);AA="a[href], button, input, select, textarea, [role], [tabindex], label"});async function TA(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 Sm(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>TA(t,s)))).filter(o=>o!==null)}async function SW(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 vm(t,e,n){switch(e.kind){case"element_id":return vW(t,e,n);case"selector":return kW(t,e);case"semantic":return AW(t,e)}}async function vW(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 Sm(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function kW(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 Sm(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function AW(t,e){return e.role!==void 0?_W(t,e.text,e.role):TW(t,e.text,e)}async function _W(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 Sm(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function TW(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 SW(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 S=await TA(y.locator,y.index);if(S!==null){let _=`${S.role}:${S.label}:${h}`,E=0;for(let k=0;k<_.length;k++)E=E*31+_.charCodeAt(k)>>>0;f.push({...S,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var EA=g(()=>{"use strict"});async function km(t,e,n,r){let o=t.url();if(o===n)return null;let s=qc(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 xA=g(()=>{"use strict";Xc()});import{randomBytes as EW}from"crypto";import{mkdir as xW,stat as RW,writeFile as IW}from"fs/promises";import{join as Am}from"path";import{gzip as CW}from"zlib";import{promisify as PW}from"util";function MW(t){return Am(Tt(t),"browser")}function OW(t){return Am(MW(t),"screenshots")}function DW(){return new Date().toISOString().replace(/[:.]/g,"-")}function FW(){return EW(3).toString("hex")}async function _m(t,e,n){if(e.length>RA)throw new Error(`writeScreenshotSidecar: buffer exceeds ${RA} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=OW(t);await xW(r,{recursive:!0});let o=`${DW()}-${FW()}-${n}.png`,s=Am(r,o);await IW(s,e);let{size:i}=await RW(s);return{path:s,bytes:i}}var _oe,RA,IA=g(()=>{"use strict";B();Jc();_oe=PW(CW);RA=5*1024*1024});var PA={};Sp(PA,{PlaywrightProvider:()=>Tm});function CA(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 Tm,MA=g(()=>{"use strict";hA();_A();EA();Xc();xA();IA();Tm=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Vc(e)}async open(e){let n=qc(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 km(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 Yc(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 Yc(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 vm(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${CA(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 km(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 Yc(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 vm(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${CA(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 _m(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 _m(n,o,r);return s}catch{return null}}}});var or={};Sp(or,{__resetBrowserRegistryForTests:()=>BW,browserProviderActive:()=>UW,closeBrowserProvider:()=>Em,getBrowserProvider:()=>NW,peekBrowserProvider:()=>$W});function OA(){Promise.resolve(Em()).then(()=>{process.exit(130)})}function DA(){Promise.resolve(Em()).then(()=>{process.exit(143)})}function FA(){Dt=null}function LW(){Qc||(process.on("SIGINT",OA),process.on("SIGTERM",DA),process.on("exit",FA),Qc=!0)}function LA(){Qc&&(process.removeListener("SIGINT",OA),process.removeListener("SIGTERM",DA),process.removeListener("exit",FA),Qc=!1)}async function NW(t){return Dt!==null?Dt:(rr!==null||(rr=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(MA(),PA)),n=pA(t),r=new e(n);return LW(),Dt=r,rr=null,r})()),rr)}async function Em(){if(Dt===null)return;let t=Dt;Dt=null,rr=null,LA(),await t.shutdown()}function UW(){return Dt!==null}function $W(){return Dt}function BW(){Dt=null,rr=null,LA()}var Dt,rr,Qc,sr=g(()=>{"use strict";Xc();Dt=null,rr=null,Qc=!1});async function NA(t,e){try{return await eA(t,e)}catch(n){return N("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function qW(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(sr(),or));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}async function UA(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??qW,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await Gc(n,t,{headers:GW,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(KW.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(WW.test(p)&&!jW.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await NA(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof St||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=um({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Xs(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>Xs(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await Xs(u.finalUrl,o);let p=await NA(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=um({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 St)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 jW,WW,KW,GW,$A=g(()=>{"use strict";tA();pm();hm();se();jW=/(text\/html|application\/xhtml\+xml)/i,WW=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,KW=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,GW={"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 VW(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(XW,{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),zW),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=ee(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 BA(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?VW({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 HA(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
216
|
+
${it(t,{headless:e,latched:n})}`,{cause:t})}var mA,rW,oW,fA,iW,wm=g(()=>{"use strict";mA=["Cannot find package","ERR_MODULE_NOT_FOUND","Executable doesn't exist"],rW="pnpm exec playwright install chromium",oW=4;iW="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 nr from"node:fs";import zc from"node:path";import{randomBytes as aW}from"node:crypto";import{chromium as cW}from"playwright";function lW(){try{return"5.130.4"}catch{}try{let t=zc.resolve(import.meta.dirname,"../../../package.json"),e=nr.readFileSync(t,"utf8"),n=JSON.parse(e);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var dW,Vc,hA=g(()=>{"use strict";wm();B();se();dW=lW(),Vc=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=cW.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=bm(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/${dW}`}}loadStorageState(e){let n=Rp(e);try{if(!nr.existsSync(n))return;let r=JSON.parse(nr.readFileSync(n,"utf8"));return N("[browser/vault] restored session",{profile:e,file:n}),r}catch(r){N("[browser/vault] ignoring unreadable vault",{profile:e,file:n,err:r});return}}async saveStorageState(e,n){try{let r=Rp(e);if(!nr.existsSync(r))return;let o=await n.storageState(),s=zc.join(zc.dirname(r),`.${zc.basename(r)}.${process.pid}.${aW(4).toString("hex")}.tmp`);nr.writeFileSync(s,JSON.stringify(o),{mode:384}),nr.chmodSync(s,384),nr.renameSync(s,r),N("[browser/vault] saved session",{profile:e,file:r})}catch(r){N("[browser/vault] save failed",{profile:e,err:r})}}}});import{createHash as uW}from"crypto";function yA(t){return!!(t.role==="textbox"&&t.kind==="password"||t.label&&pW.test(t.label))}function bA(t){return uW("sha256").update(t,"utf8").digest("hex").slice(0,8)}function wA(t){let e=t.replace(/\s+/g," ").trim();return e.length<=80?e:e.slice(0,77)+"..."}var pW,Jc=g(()=>{"use strict";pW=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as fW}from"node:crypto";function mW(t){return t?t.replace(/\s+/g," ").trim().slice(0,200):""}function gW(t,e,n){return`el_${fW("sha256").update(`${t}:${e}:${n}`).digest("hex").slice(0,6)}`}function hW(t){let e=t.replace(/\s+/g," ").trim(),n=4e3;return e.length<=n?e:e.slice(0,n)+"\u2026[truncated]"}function SA(t){return t.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function kA(t,e){let n=t.role??"",r=t.name??"";vA.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&e.push(t);for(let s of t.children??[])kA(s,e)}async function yW(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},AA).catch(()=>[])}async function bW(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},AA).catch(()=>[])}function wW(t){let n=t.accessibility;return n!==null&&typeof n=="object"?n:null}async function Yc(t,e){let n=e.maxElements??80,r=e.includeHidden??!1,o=[],s=wW(t),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=yW(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,S=!1;u!==null?(y=[],kA(u,y)):(o.push("observation skipped accessibility tree (returned null)"),S=!0,y=(await bW(t)).filter(M=>vA.has(M.role??"")));let _=new Map;for(let C of p){let M=SA(C.name),z=_.get(M);(!z||z.bbox.w===0&&C.bbox.w>0)&&_.set(M,C)}let E=y.map(C=>({ax:C,dom:_.get(SA(C.name??""))})),k=r?E:E.filter(C=>C.dom?C.dom.bbox.w>0||C.dom.bbox.h>0:!0);k.sort((C,M)=>{let z=C.dom?.bbox.y??0,P=M.dom?.bbox.y??0;if(z!==P)return z-P;let H=C.dom?.bbox.x??0,F=M.dom?.bbox.x??0;return H-F}),k.length>200&&o.push("page has 200+ interactive elements; consider scoping");let T=k.slice(0,n).map((C,M)=>{let z=C.ax.role??"generic",P=C.ax.name??"",H=gW(z,P,M),F=C.dom?.bbox??{x:0,y:0,w:0,h:0},U=C.dom?.type??null,$=null;C.ax.value!==void 0&&C.ax.value!==null&&($=String(C.ax.value)),C.ax.checked!==void 0&&($=String(C.ax.checked)),yA({role:z,kind:U})&&($="[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 Fe={id:H,role:z,label:mW(P),kind:U,value:$,state:K,bbox:F};return Q!==void 0&&(Fe.selector=Q),Fe}),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"),S&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let R=hW(f),w=`obs_${e.observationCounter.toString(36)}`,A=new Date().toISOString();return{observationId:w,url:m,title:h,textSummary:R,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 vA,AA,_A=g(()=>{"use strict";Jc();vA=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);AA="a[href], button, input, select, textarea, [role], [tabindex], label"});async function TA(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 Sm(t,e){let n=Math.min(e,5);return(await Promise.all(Array.from({length:n},(o,s)=>TA(t,s)))).filter(o=>o!==null)}async function SW(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 vm(t,e,n){switch(e.kind){case"element_id":return vW(t,e,n);case"selector":return kW(t,e);case"semantic":return AW(t,e)}}async function vW(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 Sm(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function kW(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 Sm(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${e.selector}]`},candidates:o}}async function AW(t,e){return e.role!==void 0?_W(t,e.text,e.role):TW(t,e.text,e)}async function _W(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 Sm(r,o);return{outcome:"ambiguous_target",query:{text:e,role:n},candidates:s}}async function TW(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 SW(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 S=await TA(y.locator,y.index);if(S!==null){let _=`${S.role}:${S.label}:${h}`,E=0;for(let k=0;k<_.length;k++)E=E*31+_.charCodeAt(k)>>>0;f.push({...S,id:`el_${E.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:e},candidates:f}}var EA=g(()=>{"use strict"});async function km(t,e,n,r){let o=t.url();if(o===n)return null;let s=qc(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 xA=g(()=>{"use strict";Xc()});import{randomBytes as EW}from"crypto";import{mkdir as xW,stat as RW,writeFile as IW}from"fs/promises";import{join as Am}from"path";import{gzip as CW}from"zlib";import{promisify as PW}from"util";function MW(t){return Am(Tt(t),"browser")}function OW(t){return Am(MW(t),"screenshots")}function DW(){return new Date().toISOString().replace(/[:.]/g,"-")}function FW(){return EW(3).toString("hex")}async function _m(t,e,n){if(e.length>RA)throw new Error(`writeScreenshotSidecar: buffer exceeds ${RA} byte cap (received ${e.length} bytes). Refusing to write oversized screenshot.`);let r=OW(t);await xW(r,{recursive:!0});let o=`${DW()}-${FW()}-${n}.png`,s=Am(r,o);await IW(s,e);let{size:i}=await RW(s);return{path:s,bytes:i}}var _oe,RA,IA=g(()=>{"use strict";B();Jc();_oe=PW(CW);RA=5*1024*1024});var PA={};Sp(PA,{PlaywrightProvider:()=>Tm});function CA(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 Tm,MA=g(()=>{"use strict";hA();_A();EA();Xc();xA();IA();Tm=class{name="playwright";config;launcher;sessions=new Map;constructor(e){this.config=e,this.launcher=new Vc(e)}async open(e){let n=qc(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 km(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 Yc(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 Yc(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 vm(r,e.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${CA(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 km(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 Yc(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 vm(r,e.target,o.knownElements);if(d.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${CA(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 _m(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 _m(n,o,r);return s}catch{return null}}}});var or={};Sp(or,{__resetBrowserRegistryForTests:()=>BW,browserProviderActive:()=>UW,closeBrowserProvider:()=>Em,getBrowserProvider:()=>NW,peekBrowserProvider:()=>$W});function OA(){Promise.resolve(Em()).then(()=>{process.exit(130)})}function DA(){Promise.resolve(Em()).then(()=>{process.exit(143)})}function FA(){Dt=null}function LW(){Qc||(process.on("SIGINT",OA),process.on("SIGTERM",DA),process.on("exit",FA),Qc=!0)}function LA(){Qc&&(process.removeListener("SIGINT",OA),process.removeListener("SIGTERM",DA),process.removeListener("exit",FA),Qc=!1)}async function NW(t){return Dt!==null?Dt:(rr!==null||(rr=(async()=>{let{PlaywrightProvider:e}=await Promise.resolve().then(()=>(MA(),PA)),n=pA(t),r=new e(n);return LW(),Dt=r,rr=null,r})()),rr)}async function Em(){if(Dt===null)return;let t=Dt;Dt=null,rr=null,LA(),await t.shutdown()}function UW(){return Dt!==null}function $W(){return Dt}function BW(){Dt=null,rr=null,LA()}var Dt,rr,Qc,sr=g(()=>{"use strict";Xc();Dt=null,rr=null,Qc=!1});async function NA(t,e){try{return await eA(t,e)}catch(n){return N("[web/scrape] extraction failed",{url:e,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function qW(t,e){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(sr(),or));return(await n()).render({url:t,timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:e.requestGuard})}async function UA(t,e){let n=e.fetchFn??globalThis.fetch,r=e.renderFn??qW,o=e.lookupFn!==void 0?{lookupFn:e.lookupFn}:{},s=null,i="",a=t,c=null,l=null;try{let u=await Gc(n,t,{headers:GW,signal:e.signal},o);c=u.status,a=u.url||t;let p=u.headers.get("content-type")??"";if(u.ok){if(KW.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(WW.test(p)&&!jW.test(p))return{title:"",markdown:f.trim(),finalUrl:a,usedRender:!1};if(i=f,s=await NA(f,a),e.signal.aborted)throw e.signal.reason??new Error("aborted")}}catch(u){if(e.signal.aborted||u instanceof St||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=um({html:i,extractedTextLength:s.textLength});return{title:s.title,markdown:s.markdown,finalUrl:a,usedRender:!1,...u!==void 0?{advisory:u}:{}}}try{await Xs(t,o);let u=await r(t,{timeoutMs:e.timeoutMs,signal:e.signal,requestGuard:f=>Xs(f,o)});u.finalUrl!==t&&/^https?:\/\//i.test(u.finalUrl)&&await Xs(u.finalUrl,o);let p=await NA(u.html,u.finalUrl);if(e.signal.aborted)throw e.signal.reason??new Error("aborted");if(s===null||p.textLength>=s.textLength){let f=um({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 St)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 jW,WW,KW,GW,$A=g(()=>{"use strict";tA();pm();hm();se();jW=/(text\/html|application\/xhtml\+xml)/i,WW=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,KW=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,GW={"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 VW(t){let e=t.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await e(XW,{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),zW),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let c="";try{let d=await s.text(),u=ee(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 BA(t){return t.exaApiKey!==void 0&&t.exaApiKey.trim()!==""?VW({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 HA(t,e){if(e.length===0)return`# Search results for "${t}"
|
|
217
217
|
|
|
218
218
|
(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(`
|
|
219
219
|
`).trimEnd()}var XW,zW,jA=g(()=>{"use strict";wt();XW="https://api.exa.ai/search",zW=10});function Zc(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 ir=g(()=>{"use strict";wm()});function tK(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=JW;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,YW)}let a=QW;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,ZW)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function xm(t,e){return Buffer.byteLength(t,"utf8")<=e?{content:t,truncated:!1}:{content:qt(t,e),truncated:!0}}function nK(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=tK(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 gm(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 Gc(e,i.url,h,r)}catch(h){return a.signal.aborted?{content:`web_scrape aborted: ${d()}`,isError:!0}:h instanceof St?{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=xm(f,i.maxBytes);return{content:m.content,...m.truncated?{truncated:!0}:{}}}if(i.mode==="markdown")try{let p=await UA(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=xm(nA(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 St)return{content:`web_scrape blocked: ${p.message}`,isError:!0};let f=p instanceof Error?p.message:String(p),m=Be(p)&&!ym(f)?` (the render fallback needs the optional Playwright browser \u2014 run \`${zs()}\`)`:"";return{content:`web_scrape markdown error: ${f}${m}`,isError:!0}}let u=BA({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:eK,timeoutMs:i.timeoutMs,signal:a.signal}),f=xm(HA(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 JW,YW,QW,ZW,eK,WA,KA=g(()=>{"use strict";$A();jA();hm();fn();pm();ir();JW=3e4,YW=12e4,QW=1e5,ZW=1e6,eK=10;WA=nK()});import{existsSync as qA,mkdirSync as rK,readFileSync as oK,renameSync as sK,unlinkSync as iK,writeFileSync as aK}from"node:fs";import{dirname as GA,join as cK}from"node:path";import{randomBytes as lK}from"node:crypto";function ar(t){let e=t??_p();if(!qA(e))return[];try{let n=oK(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 Vs(t,e){let n=e??_p();rK(GA(n),{recursive:!0});let r=cK(GA(n),`.schedules.json.${process.pid}.${lK(4).toString("hex")}.tmp`),o=JSON.stringify(t,null,2);try{aK(r,o,"utf-8"),sK(r,n)}catch(s){try{qA(r)&&iK(r)}catch{}throw s}}function XA(t,e){let n=ar(e),r=n.map(c=>c.id),o=dK(t.name),s=uK(o,r),i=new Date().toISOString(),a={...t,notifyOn:t.notifyOn??"failure",id:s,createdAt:i,updatedAt:i};return n.push(a),Vs(n,e),a}function zA(t,e){let n=ar(e),r=n.length,o=n.filter(s=>s.id!==t);return o.length===r?!1:(Vs(o,e),!0)}function VA(t,e){return ar(e).find(n=>n.id===t)}function dK(t){return t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")}function uK(t,e){if(!e.includes(t))return t;let n=2;for(;e.includes(`${t}-${n}`);)n+=1;return`${t}-${n}`}function JA(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 YA=g(()=>{"use strict";B()});import{existsSync as pK,readFileSync as fK}from"node:fs";import{join as mK}from"node:path";async function Qr(t,e,n){let r,o;try{let s=mK(Jb("default"),"port");if(!pK(s))return{synced:!1,detail:"daemon-not-detected (no port file)"};let i=fK(s,"utf-8").trim(),a=gK(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 gK(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 Rm,QA=g(()=>{"use strict";B();Rm="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 hK}from"node:fs";import{readFile as yK}from"node:fs/promises";var ZA,e_,t_,n_,r_=g(()=>{"use strict";YA();B();QA();ZA=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=XA({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 Qr("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 Qr("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:Rm}})}},e_=async(t,e)=>{let n=ar();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})))}},t_=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=wa();if(!hK(s))return{content:JSON.stringify([])};let i;try{let l=await yK(s);i=(l.length>1048576?l.subarray(l.length-1048576):l).toString("utf-8")}catch{return{content:JSON.stringify([])}}let a=i.split(`
|
|
@@ -1260,7 +1260,7 @@ ${H}`,!0);continue}if(A.type==="chunk"&&A.chunk.type,A.type==="message"&&A.messa
|
|
|
1260
1260
|
|
|
1261
1261
|
\u{1F4A1} ${A.suggestion}`,await ge(c,t,s,y())),A.type==="notice"){let C=`
|
|
1262
1262
|
|
|
1263
|
-
_\u2139 ${A.text.replace(/[_*[\]()~`>#+\-=|{}.!]/g,"\\$&")}_`;c.accumulated+=C,await ge(c,t,s,y())}if(A.type==="paused"){await nD(A,_);continue}if(A.type==="resumed"){await rD(A,_);continue}if(A.type==="done"){await oD(A.metadata,_);break}A.type==="error"&&sD(A.error,_)}});let R=c.sentMessage;if(R&&!c.sawTerminalEvent){let w=i&&c.answerText.trim()?c.answerText:S();w.trim()&&await Yu(t,w)&&(await t.telegram.deleteMessage?.(s,R.message_id).catch(()=>{}),c.sentMessage=null)}else await iD(t,i,c.answerText,S(),R)}finally{(p.timedOut||!c.sawTerminalEvent)&&await Promise.resolve(e.interrupt?.()).catch(()=>{}),c.countdownInterval!==null&&(clearInterval(c.countdownInterval),c.countdownInterval=null),c.turnEnded=!0,h(),c.editInFlight=!1,await Promise.resolve(k.return?.(void 0)).catch(()=>{})}}catch(E){throw r?.("Streaming error:",E),E}}async function ib(t,e,n,r,o){if(!r.has(e))try{await Promise.race([n.waitForInitialization(),new Promise((a,c)=>setTimeout(()=>c(new Error("timeout")),5e3))]);let s=n.getSessionMetadata(),i=[{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"},{command:"cd",description:"Show or change session working directory"},{command:"name",description:"Show or set the session name"},{command:"usage",description:"Show Claude subscription usage"},{command:"sessions",description:"List and switch between sessions"},{command:"new",description:"Start a new session (keeps the current one)"}];if(s.slashCommands?.length)for(let a of s.slashCommands){let c=a.replace(/^\//,"");i.push({command:c,description:`SDK command: ${c}`})}if(s.skills?.length)for(let a of s.skills)i.push({command:a,description:`Run ${a} skill`});await t.telegram.setMyCommands(i,{scope:{type:"chat",chat_id:e}}),r.add(e),o(`Registered ${i.length} commands for chat ${e}`)}catch(s){o(`Could not register dynamic commands for chat ${e}:`,s)}}oe();function he(t){return[...[...t].map(r=>{if(r==="["||r==="]"||r==="@"||r==="("||r===")")return"";let o=r.codePointAt(0)??0;return o<32||o===127?" ":r}).join("").replace(/\s+/g," ").trim()].slice(0,64).join("")}function Qu(t,e){if(e!=="group"&&e!=="supergroup"||!t)return"";let n=he([t.first_name??"",t.last_name??""].join(" ")),r=t.username?he(t.username):"",o=typeof t.id=="number"&&Number.isFinite(t.id)?`id ${t.id}`:"",s=[n,r?`@${r}`:""].filter(Boolean).join(" "),i;if(s&&o)i=`${s} (${o})`;else if(s)i=s;else if(o)i=o;else return"";return`[from ${i}]: `}var gD=300;function ab(t){let n=[...t].map(o=>{if(o==="["||o==="]"||o==='"')return"";let s=o.codePointAt(0)??0;return s<32||s===127?" ":o}).join("").replace(/\s+/g," ").trim(),r=[...n];return r.length<=gD?n:r.slice(0,gD).join("")+"\u2026"}var hD="the assistant";function C5(t,e){if(t&&typeof t.id=="number"&&Number.isFinite(t.id)&&e!==void 0&&t.id===e)return hD;if(!t)return"";let n=he([t.first_name??"",t.last_name??""].join(" "));if(n&&n.toLowerCase()!==hD)return n;let r=t.username?he(t.username):"";return r?`@${r}`:""}function cb(t){let{replyToMessage:e,quote:n,botId:r}=t,o=n?.text??"";if(!e&&o.length===0)return"";let s=C5(e?.from,r),i=ab(o)||ab(e?.text??"")||ab(e?.caption??"");return i?s?`[in reply to ${s}: "${i}"] `:`[in reply to: "${i}"] `:e?s?`[in reply to ${s}'s message] `:"[in reply to an earlier message] ":""}function P5(t){let{first_name:e="",last_name:n="",username:r}=t.sender_user,o=he(`${e} ${n}`.trim()),s=r?he(r):"";return[o,s?`@${s}`:""].filter(Boolean).join(" ")}function M5(t){return he(t.sender_user_name)}function O5(t){let e=t.sender_chat,n=he(e.title??""),r=e.username?he(e.username):"";return[n,r?`@${r}`:""].filter(Boolean).join(" ")}function D5(t){let e=t.chat,n=he(e.title??""),r=e.username?he(e.username):"";return[n,r?`@${r}`:""].filter(Boolean).join(" ")}function F5(t){let e=he(`${t.first_name??""} ${t.last_name??""}`.trim()),n=t.username?he(t.username):"";return[e,n?`@${n}`:""].filter(Boolean).join(" ")}function lb(t){let e="";if(t.forward_origin){let n=t.forward_origin;n.type==="user"?e=P5(n):n.type==="hidden_user"?e=M5(n):n.type==="chat"?e=O5(n):n.type==="channel"?e=D5(n):console.warn(`[forward-provenance] unknown forward_origin.type "${n.type}" \u2014 Bot API may have added a new origin type`)}if(!e&&t.forward_from&&(e=F5(t.forward_from)),!e&&t.forward_from_chat){let n=t.forward_from_chat,r=he(n.title??""),o=n.username?he(n.username):"";e=[r,o?`@${o}`:""].filter(Boolean).join(" ")}return!e&&t.forward_sender_name&&(e=he(t.forward_sender_name)),e?`[forwarded from ${e}] `:""}Ci();function L5(t){return t.length<3?null:t.length>=4&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t[0]===71&&t[1]===73&&t[2]===70?"image/gif":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":null}async function N5(t,e){let n=t.headers.get("content-length");if(n!=null){let a=Number(n);if(Number.isFinite(a)&&a>e)return{status:"too-large",bytesRead:a}}let r=t.body;if(!r)return{status:"missing-body"};let o=r.getReader(),s=[],i=0;try{for(;;){let{done:a,value:c}=await o.read();if(a)break;if(i+=c.byteLength,i>e)return await o.cancel().catch(()=>{}),{status:"too-large",bytesRead:i};s.push(Buffer.from(c))}}finally{o.releaseLock()}return{status:"ok",bytes:Buffer.concat(s,i)}}function yD(t,e,n,r,o){if(n!==void 0&&n===r)return!0;if(!e||e.length===0)return!1;let s=o?`@${o.toLowerCase()}`:void 0;for(let i of e){if(i.type==="text_mention"){if(i.user?.id===r)return!0;continue}if(i.type==="mention"&&s&&t!==void 0&&t.slice(i.offset,i.offset+i.length).toLowerCase()===s)return!0}return!1}var Zu=class t{static MAX_QUEUE_DEPTH=5;sessionManager;messageQueues=new Map;registeredCommandChats;log;bot;claimedChats=new Map;reserveClaim(e){this.claimedChats.set(e,(this.claimedChats.get(e)??0)+1)}releaseClaim(e){let n=(this.claimedChats.get(e)??0)-1;n<=0?this.claimedChats.delete(e):this.claimedChats.set(e,n)}isClaimed(e){return(this.claimedChats.get(e)??0)>0}pendingElicitations=new Map;ledgerOriginatedPendingChats=new Set;tagOnlyChats;constructor(e,n,r,o,s=new Set){this.bot=e,this.sessionManager=n,this.registeredCommandChats=r,this.log=o,this.tagOnlyChats=s}async handlePhoto(e){let n=ie(e),r=n?.chatId,o=e.message,s=o?.photo;if(!n||!r||!s?.length){this.log(`Photo handling: missing chatId or photo array for chat ${r??"(unknown)"}`);return}if(this.tagOnlyChats.has(r)){let d=e.botInfo?.id;if(d===void 0){this.log(`[tag-only] Dropping photo in chat ${r}: bot identity unknown (botInfo missing)`);return}if(!yD(o?.caption,o?.caption_entities,o?.reply_to_message?.from?.id,d,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed photo in chat ${r}`);return}}this.log(`\u{1F4F7} Photo from chat ID: ${r}`),await e.react?.("\u{1F440}").catch(()=>{});let i=s[s.length-1];if(!i){this.log(`Photo handling: empty photo array for chat ${r}`);return}let a=5*1024*1024;if(i.file_size!=null&&i.file_size>a){this.log(`Photo handling: oversized file (${i.file_size} bytes) rejected for chat ${r}`),await e.reply("\u274C Image is too large (max 5 MB). Please send a smaller photo.");return}let c=o?.caption,l=!1;try{l=this.isClaimed(X(n)),l||this.reserveClaim(X(n));let d=await this.sessionManager.getSession(n);if(ib(this.bot,r,d,this.registeredCommandChats,this.log).catch(w=>this.log("Failed to register chat commands:",w)),(d.state!=="idle"||l)&&(this.messageQueues.get(X(n))?.length??0)>=t.MAX_QUEUE_DEPTH){await e.reply("\u23F3 Queue full. Please wait for your messages to be processed.");return}let u=await e.telegram.getFileLink(i.file_id),p=u instanceof URL?u:new URL(String(u));if(p.protocol!=="https:"||p.hostname!=="api.telegram.org"||p.port!==""&&p.port!=="443"){this.log(`Photo handling: unexpected file URL (protocol=${p.protocol} hostname=${p.hostname}) rejected for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let f=await globalThis.fetch(p.href,{signal:AbortSignal.timeout(15e3),redirect:"error"});if(!f.ok){this.log(`Photo handling: fetch failed with status ${f.status} for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let m=await N5(f,a);if(m.status==="too-large"){this.log(`Photo handling: downloaded file (${m.bytesRead} bytes) exceeds limit for chat ${r}`),await e.reply("\u274C Image is too large (max 5 MB). Please send a smaller photo.");return}if(m.status==="missing-body"){this.log(`Photo handling: fetch response had no body for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let h=m.bytes,y=["image/jpeg","image/png","image/gif","image/webp"],S=f.headers.get("content-type")??"",_=(S.split(";")[0]?.trim()??"").toLowerCase(),E;if(y.includes(_))E=_;else{let w=L5(h);if(w!==null)this.log(`Photo: sniffed ${w} (Content-Type was "${S}") for chat ${r}`),E=w;else{this.log(`Photo: unrecognised image format for chat ${r} (Content-Type: "${S}")`),await e.reply("\u274C Unsupported image format. Please send a JPEG, PNG, GIF, or WebP.");return}}let k=Qu(o?.from,e.chat?.type),x=cb({replyToMessage:o?.reply_to_message,quote:o?.quote,botId:e.botInfo?.id}),T=lb(o??{}),I=x+T+k,R=[];if(c!=null?R.push({type:"text",text:`${I}[User caption]: ${[...c].slice(0,1024).join("")}`}):I&&R.push({type:"text",text:`${I}(image, no caption)`}),await d.waitForInitialization(),d.sessionId===void 0)throw new Error("Telegram session initialized without a session id");if(await rC(R,d.sessionId,[{mediaType:E,bytes:h}]),d.state!=="idle"||l){let w=this.enqueuePhoto(n,e,R);w!==!1&&await e.reply(Ga(w));return}await this.processOne(n,e,R)}catch(d){let p=(d instanceof Error?d.message:String(d)).replace(/\/bot[^/]+\//g,"/bot[REDACTED]/");this.log("Photo handling error:",p),Xu(d)?await e.reply("\u274C Couldn't reach Telegram to fetch that image. Please try resending."):na(d)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):ra(d)?await e.reply("\u274C Couldn't download the image. Please try resending."):await e.reply(qa())}finally{l||this.releaseClaim(X(n))}}async handle(e){let n=ie(e),r=n?.chatId,o=e.message.text;if(!n||!r||!o)return;let s=X(n);if(this.log(`\u{1F4EC} Message from chat ID: ${r}`),o.startsWith("/"))return;let i=e.message,a=cb({replyToMessage:i.reply_to_message,quote:i.quote,botId:e.botInfo?.id}),c=lb(i),l=a+c+Qu(i.from,e.chat?.type)+o,d=Qu(i.from,e.chat?.type)+o,u=this.pendingElicitations.get(s);if(u){if(this.ledgerOriginatedPendingChats.has(s)){this.pendingElicitations.delete(s),this.ledgerOriginatedPendingChats.delete(s),u(d);return}let f=this.sessionManager.getSessionIfExists(n);if(f&&f.state!=="idle"){this.pendingElicitations.delete(s),u(d);return}this.log("[message] dropping stale pendingElicitation for route",s),this.pendingElicitations.delete(s)}if(this.tagOnlyChats.has(r)){let f=e.botInfo?.id;if(f===void 0){this.log(`[tag-only] Dropping message in chat ${r}: bot identity unknown (botInfo missing)`);return}let m=e.message;if(!yD(m.text,m.entities,m.reply_to_message?.from?.id,f,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed message in chat ${r}`);return}}let p=!1;try{await e.react?.("\u{1F440}").catch(()=>{}),p=this.isClaimed(X(n)),p||this.reserveClaim(X(n));let f=await this.sessionManager.getSession(n);ib(this.bot,r,f,this.registeredCommandChats,this.log).catch(h=>this.log("Failed to register chat commands:",h));let m=l;if(f.state!=="idle"||p){let h=this.enqueueMessage(n,e,m);h!==!1&&await e.reply(Ga(h));return}await this.processOne(n,e,m)}catch(f){this.log("Message handling error:",f),Xu(f)||(na(f)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):ra(f)?await e.reply("\u{1F310} Network error. Please check your connection and try again."):await e.reply(qa()))}finally{p||this.releaseClaim(X(n))}}async processClearDirect(e,n){this.reserveClaim(X(e));try{await this.sessionManager.resetSession(e),this.registeredCommandChats.delete(e.chatId),await n.reply(za())}catch(r){this.log("Clear error:",r),await n.reply(q(r))}finally{this.releaseClaim(X(e))}}async processCompactDirect(e,n){this.reserveClaim(X(e));let r=!1;try{let o=await this.sessionManager.getSession(e),s=o.hookRegistry,i=await ds(n,async()=>(s&&await s.dispatch({event:"PreCompact",sessionId:o.sessionId,trigger:"manual"}),o.compact()));if(i.reason==="session-busy"){this.enqueueCompact(e,n),r=!0;return}i.reason==="microcompacted"&&i.microcompaction?await n.reply(Vw(i.microcompaction)):i.compacted?await n.reply(Va({before:i.messagesBefore,after:i.messagesAfter,...i.tokensSavedEstimate!==void 0?{tokensSavedEstimate:i.tokensSavedEstimate}:{}})):await n.reply(Ja(i.reason??"unknown"))}catch(o){o instanceof Y?await n.reply(`Compaction skipped: ${qe(o.reason??"blocked by hook")}`):(this.log("Compact error (queued):",o),await n.reply(q(o)))}finally{r||this.drainQueue(e).catch(o=>this.log("Drain error:",o)),this.releaseClaim(X(e))}}queueFor(e){let n=X(e),r=this.messageQueues.get(n);return r||(r=[],this.messageQueues.set(n,r)),r}enqueueMessage(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"message",ctx:n,text:r}),o.length)}enqueuePhoto(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"photo",ctx:n,content:r}),o.length)}enqueueClear(e,n){this.queueFor(e).push({type:"clear",ctx:n})}enqueueCompact(e,n){this.queueFor(e).push({type:"compact",ctx:n})}async processOne(e,n,r){this.reserveClaim(X(e));let o=!1;try{let s=await this.sessionManager.getSession(e),i=typeof r=="string"?r:r.map(a=>a.type==="text"?a.text:"[image]").join(" ");await ds(n,()=>mD(n,s,r,this.log,{cleanFinal:!0,onComplete:(a,c)=>{this.sessionManager.recordTelegramTurn(e,i,a,c)}}))}catch(s){if(this.log("Message handling error:",s),(s?.message??"").includes("session is busy")){let a=typeof r=="string"?this.enqueueMessage(e,n,r):this.enqueuePhoto(e,n,r);a!==!1&&await n.reply(Ga(a)),o=!0;return}s instanceof _r?await n.reply(`\u23F1\uFE0F ${s.message}`):Xu(s)||(na(s)?await n.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):ra(s)?await n.reply("\u{1F310} Network error. Please check your connection and try again."):await n.reply(qa()))}finally{o||this.drainQueue(e).catch(s=>this.log("Drain error:",s)),this.releaseClaim(X(e))}}async drainQueue(e){let n=this.messageQueues.get(X(e));if(!n?.length)return;let r=n.shift();r.type==="message"?await this.processOne(e,r.ctx,r.text):r.type==="photo"?await this.processOne(e,r.ctx,r.content):r.type==="compact"?await this.processCompactDirect(e,r.ctx):await this.processClearDirect(e,r.ctx)}};Ns();import{Markup as ia}from"telegraf";var oa="afk:e:";var ep=/^[a-zA-Z0-9_-]{1,48}$/;function tp(t,e){if(!ep.test(t))throw new Error(`buildElicitationCallback: invalid id ${JSON.stringify(t)}`);if(!Number.isInteger(e)||e<0)throw new Error(`buildElicitationCallback: choiceIndex must be a non-negative integer, got ${e}`);let n=`${oa}${e}:${t}`,r=Buffer.byteLength(n,"utf8");if(r>64)throw new Error(`buildElicitationCallback: payload ${r} bytes exceeds Telegram's 64-byte limit (id=${t})`);return n}function bD(t){if(!t||!t.startsWith(oa)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(oa.length),n=e.indexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1),s=parseInt(r,10);return!Number.isInteger(s)||s<0||String(s)!==r||!ep.test(o)?null:{id:o,choiceIndex:s}}var sa="afk:ec:";function wD(t){if(!ep.test(t))throw new Error(`buildCustomElicitationCallback: invalid id ${JSON.stringify(t)}`);let e=`${sa}${t}`,n=Buffer.byteLength(e,"utf8");if(n>64)throw new Error(`buildCustomElicitationCallback: ${n} bytes exceeds 64-byte limit`);return e}function SD(t){if(!t||!t.startsWith(sa)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(sa.length);return ep.test(e)?e:null}Ne();eo();import{randomBytes as U5}from"node:crypto";function $5(){return`elic-${U5(8).toString("hex")}`}var vD=-1;function B5(t,e=64){if(Buffer.byteLength(t,"utf8")<=e)return t;let n=Buffer.from(t,"utf8").subarray(0,e);return new TextDecoder("utf-8",{fatal:!1}).decode(n).replace(/\uFFFD$/,"")}function np(t,e,n,r){let o=typeof n=="number"?{chatId:n}:n,s=r?.ledgerOriginated??!1,i=new Map,a=new RegExp(`^${He(oa)}\\d+:.+$`);e.action(a,async l=>{await l.answerCbQuery().catch(()=>{});let d=typeof l.callbackQuery=="object"&&"data"in l.callbackQuery?l.callbackQuery.data:void 0,u=bD(d);if(!u)return;let p=i.get(u.id);p&&l.chat?.id===p.chatId&&p.resolve(u.choiceIndex)});let c=new RegExp(`^${He(sa)}.+$`);return e.action(c,async l=>{await l.answerCbQuery().catch(()=>{});let d=typeof l.callbackQuery=="object"&&"data"in l.callbackQuery?l.callbackQuery.data:void 0,u=SD(d);if(!u)return;let p=i.get(u);p&&l.chat?.id===p.chatId&&p.resolve(vD)}),async(l,d)=>{if(d.signal.aborted)return{action:"decline"};let u=(d.sessionId!==void 0?Iw(d.sessionId):void 0)??o,p=u.chatId,f=X(u),m=cs(u);function h(k){t.pendingElicitations.set(f,k),s&&t.ledgerOriginatedPendingChats.add(f)}function y(){t.pendingElicitations.delete(f),s&&t.ledgerOriginatedPendingChats.delete(f)}let S=l.type??"text",_=l.message,E=`\u{1F4AC} <b>Question from agent</b>
|
|
1263
|
+
_\u2139 ${A.text.replace(/[_*[\]()~`>#+\-=|{}.!]/g,"\\$&")}_`;c.accumulated+=C,await ge(c,t,s,y())}if(A.type==="paused"){await nD(A,_);continue}if(A.type==="resumed"){await rD(A,_);continue}if(A.type==="done"){await oD(A.metadata,_);break}A.type==="error"&&sD(A.error,_)}});let R=c.sentMessage;if(R&&!c.sawTerminalEvent){let w=i&&c.answerText.trim()?c.answerText:S();w.trim()&&await Yu(t,w)&&(await t.telegram.deleteMessage?.(s,R.message_id).catch(()=>{}),c.sentMessage=null)}else await iD(t,i,c.answerText,S(),R)}finally{(p.timedOut||!c.sawTerminalEvent)&&await Promise.resolve(e.interrupt?.()).catch(()=>{}),c.countdownInterval!==null&&(clearInterval(c.countdownInterval),c.countdownInterval=null),c.turnEnded=!0,h(),c.editInFlight=!1,p.apiRoundInFlight=!1,p.apiRoundSince=null,await Promise.resolve(k.return?.(void 0)).catch(()=>{})}}catch(E){throw r?.("Streaming error:",E),E}}async function ib(t,e,n,r,o){if(!r.has(e))try{await Promise.race([n.waitForInitialization(),new Promise((a,c)=>setTimeout(()=>c(new Error("timeout")),5e3))]);let s=n.getSessionMetadata(),i=[{command:"start",description:"Show welcome and command list"},{command:"help",description:"Show this command list"},{command:"clear",description:"Clear conversation history"},{command:"compact",description:"Compact conversation history"},{command:"model",description:"Switch Claude model (opus/sonnet/haiku)"},{command:"cd",description:"Show or change session working directory"},{command:"name",description:"Show or set the session name"},{command:"usage",description:"Show Claude subscription usage"},{command:"sessions",description:"List and switch between sessions"},{command:"new",description:"Start a new session (keeps the current one)"}];if(s.slashCommands?.length)for(let a of s.slashCommands){let c=a.replace(/^\//,"");i.push({command:c,description:`SDK command: ${c}`})}if(s.skills?.length)for(let a of s.skills)i.push({command:a,description:`Run ${a} skill`});await t.telegram.setMyCommands(i,{scope:{type:"chat",chat_id:e}}),r.add(e),o(`Registered ${i.length} commands for chat ${e}`)}catch(s){o(`Could not register dynamic commands for chat ${e}:`,s)}}oe();function he(t){return[...[...t].map(r=>{if(r==="["||r==="]"||r==="@"||r==="("||r===")")return"";let o=r.codePointAt(0)??0;return o<32||o===127?" ":r}).join("").replace(/\s+/g," ").trim()].slice(0,64).join("")}function Qu(t,e){if(e!=="group"&&e!=="supergroup"||!t)return"";let n=he([t.first_name??"",t.last_name??""].join(" ")),r=t.username?he(t.username):"",o=typeof t.id=="number"&&Number.isFinite(t.id)?`id ${t.id}`:"",s=[n,r?`@${r}`:""].filter(Boolean).join(" "),i;if(s&&o)i=`${s} (${o})`;else if(s)i=s;else if(o)i=o;else return"";return`[from ${i}]: `}var gD=300;function ab(t){let n=[...t].map(o=>{if(o==="["||o==="]"||o==='"')return"";let s=o.codePointAt(0)??0;return s<32||s===127?" ":o}).join("").replace(/\s+/g," ").trim(),r=[...n];return r.length<=gD?n:r.slice(0,gD).join("")+"\u2026"}var hD="the assistant";function C5(t,e){if(t&&typeof t.id=="number"&&Number.isFinite(t.id)&&e!==void 0&&t.id===e)return hD;if(!t)return"";let n=he([t.first_name??"",t.last_name??""].join(" "));if(n&&n.toLowerCase()!==hD)return n;let r=t.username?he(t.username):"";return r?`@${r}`:""}function cb(t){let{replyToMessage:e,quote:n,botId:r}=t,o=n?.text??"";if(!e&&o.length===0)return"";let s=C5(e?.from,r),i=ab(o)||ab(e?.text??"")||ab(e?.caption??"");return i?s?`[in reply to ${s}: "${i}"] `:`[in reply to: "${i}"] `:e?s?`[in reply to ${s}'s message] `:"[in reply to an earlier message] ":""}function P5(t){let{first_name:e="",last_name:n="",username:r}=t.sender_user,o=he(`${e} ${n}`.trim()),s=r?he(r):"";return[o,s?`@${s}`:""].filter(Boolean).join(" ")}function M5(t){return he(t.sender_user_name)}function O5(t){let e=t.sender_chat,n=he(e.title??""),r=e.username?he(e.username):"";return[n,r?`@${r}`:""].filter(Boolean).join(" ")}function D5(t){let e=t.chat,n=he(e.title??""),r=e.username?he(e.username):"";return[n,r?`@${r}`:""].filter(Boolean).join(" ")}function F5(t){let e=he(`${t.first_name??""} ${t.last_name??""}`.trim()),n=t.username?he(t.username):"";return[e,n?`@${n}`:""].filter(Boolean).join(" ")}function lb(t){let e="";if(t.forward_origin){let n=t.forward_origin;n.type==="user"?e=P5(n):n.type==="hidden_user"?e=M5(n):n.type==="chat"?e=O5(n):n.type==="channel"?e=D5(n):console.warn(`[forward-provenance] unknown forward_origin.type "${n.type}" \u2014 Bot API may have added a new origin type`)}if(!e&&t.forward_from&&(e=F5(t.forward_from)),!e&&t.forward_from_chat){let n=t.forward_from_chat,r=he(n.title??""),o=n.username?he(n.username):"";e=[r,o?`@${o}`:""].filter(Boolean).join(" ")}return!e&&t.forward_sender_name&&(e=he(t.forward_sender_name)),e?`[forwarded from ${e}] `:""}Ci();function L5(t){return t.length<3?null:t.length>=4&&t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71?"image/png":t[0]===71&&t[1]===73&&t[2]===70?"image/gif":t.length>=12&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70&&t[8]===87&&t[9]===69&&t[10]===66&&t[11]===80?"image/webp":t[0]===255&&t[1]===216&&t[2]===255?"image/jpeg":null}async function N5(t,e){let n=t.headers.get("content-length");if(n!=null){let a=Number(n);if(Number.isFinite(a)&&a>e)return{status:"too-large",bytesRead:a}}let r=t.body;if(!r)return{status:"missing-body"};let o=r.getReader(),s=[],i=0;try{for(;;){let{done:a,value:c}=await o.read();if(a)break;if(i+=c.byteLength,i>e)return await o.cancel().catch(()=>{}),{status:"too-large",bytesRead:i};s.push(Buffer.from(c))}}finally{o.releaseLock()}return{status:"ok",bytes:Buffer.concat(s,i)}}function yD(t,e,n,r,o){if(n!==void 0&&n===r)return!0;if(!e||e.length===0)return!1;let s=o?`@${o.toLowerCase()}`:void 0;for(let i of e){if(i.type==="text_mention"){if(i.user?.id===r)return!0;continue}if(i.type==="mention"&&s&&t!==void 0&&t.slice(i.offset,i.offset+i.length).toLowerCase()===s)return!0}return!1}var Zu=class t{static MAX_QUEUE_DEPTH=5;sessionManager;messageQueues=new Map;registeredCommandChats;log;bot;claimedChats=new Map;reserveClaim(e){this.claimedChats.set(e,(this.claimedChats.get(e)??0)+1)}releaseClaim(e){let n=(this.claimedChats.get(e)??0)-1;n<=0?this.claimedChats.delete(e):this.claimedChats.set(e,n)}isClaimed(e){return(this.claimedChats.get(e)??0)>0}pendingElicitations=new Map;ledgerOriginatedPendingChats=new Set;tagOnlyChats;constructor(e,n,r,o,s=new Set){this.bot=e,this.sessionManager=n,this.registeredCommandChats=r,this.log=o,this.tagOnlyChats=s}async handlePhoto(e){let n=ie(e),r=n?.chatId,o=e.message,s=o?.photo;if(!n||!r||!s?.length){this.log(`Photo handling: missing chatId or photo array for chat ${r??"(unknown)"}`);return}if(this.tagOnlyChats.has(r)){let d=e.botInfo?.id;if(d===void 0){this.log(`[tag-only] Dropping photo in chat ${r}: bot identity unknown (botInfo missing)`);return}if(!yD(o?.caption,o?.caption_entities,o?.reply_to_message?.from?.id,d,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed photo in chat ${r}`);return}}this.log(`\u{1F4F7} Photo from chat ID: ${r}`),await e.react?.("\u{1F440}").catch(()=>{});let i=s[s.length-1];if(!i){this.log(`Photo handling: empty photo array for chat ${r}`);return}let a=5*1024*1024;if(i.file_size!=null&&i.file_size>a){this.log(`Photo handling: oversized file (${i.file_size} bytes) rejected for chat ${r}`),await e.reply("\u274C Image is too large (max 5 MB). Please send a smaller photo.");return}let c=o?.caption,l=!1;try{l=this.isClaimed(X(n)),l||this.reserveClaim(X(n));let d=await this.sessionManager.getSession(n);if(ib(this.bot,r,d,this.registeredCommandChats,this.log).catch(w=>this.log("Failed to register chat commands:",w)),(d.state!=="idle"||l)&&(this.messageQueues.get(X(n))?.length??0)>=t.MAX_QUEUE_DEPTH){await e.reply("\u23F3 Queue full. Please wait for your messages to be processed.");return}let u=await e.telegram.getFileLink(i.file_id),p=u instanceof URL?u:new URL(String(u));if(p.protocol!=="https:"||p.hostname!=="api.telegram.org"||p.port!==""&&p.port!=="443"){this.log(`Photo handling: unexpected file URL (protocol=${p.protocol} hostname=${p.hostname}) rejected for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let f=await globalThis.fetch(p.href,{signal:AbortSignal.timeout(15e3),redirect:"error"});if(!f.ok){this.log(`Photo handling: fetch failed with status ${f.status} for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let m=await N5(f,a);if(m.status==="too-large"){this.log(`Photo handling: downloaded file (${m.bytesRead} bytes) exceeds limit for chat ${r}`),await e.reply("\u274C Image is too large (max 5 MB). Please send a smaller photo.");return}if(m.status==="missing-body"){this.log(`Photo handling: fetch response had no body for chat ${r}`),await e.reply("\u274C Couldn't download the image. Please try resending.");return}let h=m.bytes,y=["image/jpeg","image/png","image/gif","image/webp"],S=f.headers.get("content-type")??"",_=(S.split(";")[0]?.trim()??"").toLowerCase(),E;if(y.includes(_))E=_;else{let w=L5(h);if(w!==null)this.log(`Photo: sniffed ${w} (Content-Type was "${S}") for chat ${r}`),E=w;else{this.log(`Photo: unrecognised image format for chat ${r} (Content-Type: "${S}")`),await e.reply("\u274C Unsupported image format. Please send a JPEG, PNG, GIF, or WebP.");return}}let k=Qu(o?.from,e.chat?.type),x=cb({replyToMessage:o?.reply_to_message,quote:o?.quote,botId:e.botInfo?.id}),T=lb(o??{}),I=x+T+k,R=[];if(c!=null?R.push({type:"text",text:`${I}[User caption]: ${[...c].slice(0,1024).join("")}`}):I&&R.push({type:"text",text:`${I}(image, no caption)`}),await d.waitForInitialization(),d.sessionId===void 0)throw new Error("Telegram session initialized without a session id");if(await rC(R,d.sessionId,[{mediaType:E,bytes:h}]),d.state!=="idle"||l){let w=this.enqueuePhoto(n,e,R);w!==!1&&await e.reply(Ga(w));return}await this.processOne(n,e,R)}catch(d){let p=(d instanceof Error?d.message:String(d)).replace(/\/bot[^/]+\//g,"/bot[REDACTED]/");this.log("Photo handling error:",p),Xu(d)?await e.reply("\u274C Couldn't reach Telegram to fetch that image. Please try resending."):na(d)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):ra(d)?await e.reply("\u274C Couldn't download the image. Please try resending."):await e.reply(qa())}finally{l||this.releaseClaim(X(n))}}async handle(e){let n=ie(e),r=n?.chatId,o=e.message.text;if(!n||!r||!o)return;let s=X(n);if(this.log(`\u{1F4EC} Message from chat ID: ${r}`),o.startsWith("/"))return;let i=e.message,a=cb({replyToMessage:i.reply_to_message,quote:i.quote,botId:e.botInfo?.id}),c=lb(i),l=a+c+Qu(i.from,e.chat?.type)+o,d=Qu(i.from,e.chat?.type)+o,u=this.pendingElicitations.get(s);if(u){if(this.ledgerOriginatedPendingChats.has(s)){this.pendingElicitations.delete(s),this.ledgerOriginatedPendingChats.delete(s),u(d);return}let f=this.sessionManager.getSessionIfExists(n);if(f&&f.state!=="idle"){this.pendingElicitations.delete(s),u(d);return}this.log("[message] dropping stale pendingElicitation for route",s),this.pendingElicitations.delete(s)}if(this.tagOnlyChats.has(r)){let f=e.botInfo?.id;if(f===void 0){this.log(`[tag-only] Dropping message in chat ${r}: bot identity unknown (botInfo missing)`);return}let m=e.message;if(!yD(m.text,m.entities,m.reply_to_message?.from?.id,f,e.botInfo?.username)){this.log(`[tag-only] Dropping un-addressed message in chat ${r}`);return}}let p=!1;try{await e.react?.("\u{1F440}").catch(()=>{}),p=this.isClaimed(X(n)),p||this.reserveClaim(X(n));let f=await this.sessionManager.getSession(n);ib(this.bot,r,f,this.registeredCommandChats,this.log).catch(h=>this.log("Failed to register chat commands:",h));let m=l;if(f.state!=="idle"||p){let h=this.enqueueMessage(n,e,m);h!==!1&&await e.reply(Ga(h));return}await this.processOne(n,e,m)}catch(f){this.log("Message handling error:",f),Xu(f)||(na(f)?await e.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):ra(f)?await e.reply("\u{1F310} Network error. Please check your connection and try again."):await e.reply(qa()))}finally{p||this.releaseClaim(X(n))}}async processClearDirect(e,n){this.reserveClaim(X(e));try{await this.sessionManager.resetSession(e),this.registeredCommandChats.delete(e.chatId),await n.reply(za())}catch(r){this.log("Clear error:",r),await n.reply(q(r))}finally{this.releaseClaim(X(e))}}async processCompactDirect(e,n){this.reserveClaim(X(e));let r=!1;try{let o=await this.sessionManager.getSession(e),s=o.hookRegistry,i=await ds(n,async()=>(s&&await s.dispatch({event:"PreCompact",sessionId:o.sessionId,trigger:"manual"}),o.compact()));if(i.reason==="session-busy"){this.enqueueCompact(e,n),r=!0;return}i.reason==="microcompacted"&&i.microcompaction?await n.reply(Vw(i.microcompaction)):i.compacted?await n.reply(Va({before:i.messagesBefore,after:i.messagesAfter,...i.tokensSavedEstimate!==void 0?{tokensSavedEstimate:i.tokensSavedEstimate}:{}})):await n.reply(Ja(i.reason??"unknown"))}catch(o){o instanceof Y?await n.reply(`Compaction skipped: ${qe(o.reason??"blocked by hook")}`):(this.log("Compact error (queued):",o),await n.reply(q(o)))}finally{r||this.drainQueue(e).catch(o=>this.log("Drain error:",o)),this.releaseClaim(X(e))}}queueFor(e){let n=X(e),r=this.messageQueues.get(n);return r||(r=[],this.messageQueues.set(n,r)),r}enqueueMessage(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"message",ctx:n,text:r}),o.length)}enqueuePhoto(e,n,r){let o=this.queueFor(e);return o.length>=t.MAX_QUEUE_DEPTH?(n.reply("\u23F3 Queue full. Please wait for your messages to be processed.").catch(()=>{}),!1):(o.push({type:"photo",ctx:n,content:r}),o.length)}enqueueClear(e,n){this.queueFor(e).push({type:"clear",ctx:n})}enqueueCompact(e,n){this.queueFor(e).push({type:"compact",ctx:n})}async processOne(e,n,r){this.reserveClaim(X(e));let o=!1;try{let s=await this.sessionManager.getSession(e),i=typeof r=="string"?r:r.map(a=>a.type==="text"?a.text:"[image]").join(" ");await ds(n,()=>mD(n,s,r,this.log,{cleanFinal:!0,onComplete:(a,c)=>{this.sessionManager.recordTelegramTurn(e,i,a,c)}}))}catch(s){if(this.log("Message handling error:",s),(s?.message??"").includes("session is busy")){let a=typeof r=="string"?this.enqueueMessage(e,n,r):this.enqueuePhoto(e,n,r);a!==!1&&await n.reply(Ga(a)),o=!0;return}s instanceof _r?await n.reply(`\u23F1\uFE0F ${s.message}`):Xu(s)||(na(s)?await n.reply("\u23F3 Rate limit reached. Please wait a moment and try again."):ra(s)?await n.reply("\u{1F310} Network error. Please check your connection and try again."):await n.reply(qa()))}finally{o||this.drainQueue(e).catch(s=>this.log("Drain error:",s)),this.releaseClaim(X(e))}}async drainQueue(e){let n=this.messageQueues.get(X(e));if(!n?.length)return;let r=n.shift();r.type==="message"?await this.processOne(e,r.ctx,r.text):r.type==="photo"?await this.processOne(e,r.ctx,r.content):r.type==="compact"?await this.processCompactDirect(e,r.ctx):await this.processClearDirect(e,r.ctx)}};Ns();import{Markup as ia}from"telegraf";var oa="afk:e:";var ep=/^[a-zA-Z0-9_-]{1,48}$/;function tp(t,e){if(!ep.test(t))throw new Error(`buildElicitationCallback: invalid id ${JSON.stringify(t)}`);if(!Number.isInteger(e)||e<0)throw new Error(`buildElicitationCallback: choiceIndex must be a non-negative integer, got ${e}`);let n=`${oa}${e}:${t}`,r=Buffer.byteLength(n,"utf8");if(r>64)throw new Error(`buildElicitationCallback: payload ${r} bytes exceeds Telegram's 64-byte limit (id=${t})`);return n}function bD(t){if(!t||!t.startsWith(oa)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(oa.length),n=e.indexOf(":");if(n<1)return null;let r=e.slice(0,n),o=e.slice(n+1),s=parseInt(r,10);return!Number.isInteger(s)||s<0||String(s)!==r||!ep.test(o)?null:{id:o,choiceIndex:s}}var sa="afk:ec:";function wD(t){if(!ep.test(t))throw new Error(`buildCustomElicitationCallback: invalid id ${JSON.stringify(t)}`);let e=`${sa}${t}`,n=Buffer.byteLength(e,"utf8");if(n>64)throw new Error(`buildCustomElicitationCallback: ${n} bytes exceeds 64-byte limit`);return e}function SD(t){if(!t||!t.startsWith(sa)||Buffer.byteLength(t,"utf8")>64)return null;let e=t.slice(sa.length);return ep.test(e)?e:null}Ne();eo();import{randomBytes as U5}from"node:crypto";function $5(){return`elic-${U5(8).toString("hex")}`}var vD=-1;function B5(t,e=64){if(Buffer.byteLength(t,"utf8")<=e)return t;let n=Buffer.from(t,"utf8").subarray(0,e);return new TextDecoder("utf-8",{fatal:!1}).decode(n).replace(/\uFFFD$/,"")}function np(t,e,n,r){let o=typeof n=="number"?{chatId:n}:n,s=r?.ledgerOriginated??!1,i=new Map,a=new RegExp(`^${He(oa)}\\d+:.+$`);e.action(a,async l=>{await l.answerCbQuery().catch(()=>{});let d=typeof l.callbackQuery=="object"&&"data"in l.callbackQuery?l.callbackQuery.data:void 0,u=bD(d);if(!u)return;let p=i.get(u.id);p&&l.chat?.id===p.chatId&&p.resolve(u.choiceIndex)});let c=new RegExp(`^${He(sa)}.+$`);return e.action(c,async l=>{await l.answerCbQuery().catch(()=>{});let d=typeof l.callbackQuery=="object"&&"data"in l.callbackQuery?l.callbackQuery.data:void 0,u=SD(d);if(!u)return;let p=i.get(u);p&&l.chat?.id===p.chatId&&p.resolve(vD)}),async(l,d)=>{if(d.signal.aborted)return{action:"decline"};let u=(d.sessionId!==void 0?Iw(d.sessionId):void 0)??o,p=u.chatId,f=X(u),m=cs(u);function h(k){t.pendingElicitations.set(f,k),s&&t.ledgerOriginatedPendingChats.add(f)}function y(){t.pendingElicitations.delete(f),s&&t.ledgerOriginatedPendingChats.delete(f)}let S=l.type??"text",_=l.message,E=`\u{1F4AC} <b>Question from agent</b>
|
|
1264
1264
|
|
|
1265
1265
|
${qe(_)}`;if(l.context&&(E=`\u{1F4AC} <b>Question from agent</b>
|
|
1266
1266
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agent-afk",
|
|
3
|
-
"version": "5.130.
|
|
3
|
+
"version": "5.130.4",
|
|
4
4
|
"description": "Open-source coding-agent harness you can actually change — own the loop (prompts, gates, routing, skills, terminal states), use any model, run long tasks while you're away.",
|
|
5
5
|
"main": "dist/index.mjs",
|
|
6
6
|
"types": "dist/index.d.ts",
|