agent-afk 4.23.2 → 4.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1073,7 +1073,7 @@ ${o}`;return s.includes("already checked out")||s.includes("is already used by w
1073
1073
  Effective base URL: ${r}`)),r}return t}function fU(){if(zf!==void 0)return zf;if(!ek){let o=[pa(process.cwd(),".env"),at(),Jw()];for(let s of o)qf(s)&&pU({path:s,override:!1});ek=!0}let e={},t=k.AFK_MODEL??k.CLAUDE_MODEL;if(t){let o=t.toLowerCase();e.model=tf(o)?o:t}if(oe(t)==="anthropic-direct"){let o=Jf();o!==void 0&&(e.apiKey=o)}let r=k.AFK_LOCAL_BASE_URL;if(r&&r.length>0&&(e.baseUrl=r,e.apiKey=k.AFK_LOCAL_API_KEY||"local"),k.AFK_MAX_TOKENS&&(e.maxTokens=parseInt(k.AFK_MAX_TOKENS,10)),k.AFK_TEMPERATURE&&(e.temperature=parseFloat(k.AFK_TEMPERATURE)),k.AFK_SYSTEM_PROMPT&&(e.systemPrompt=k.AFK_SYSTEM_PROMPT),k.AFK_AUTO_ROUTING){let o=k.AFK_AUTO_ROUTING.toLowerCase()==="true";e.autoRouting={interactive:o,chat:o,telegram:o,daemon:o}}return k.AFK_OPENAI_BASE_URL&&(e.openaiBaseUrl=mU(k.AFK_OPENAI_BASE_URL)),zf=e,e}function Vf(){if(Cs!==void 0)return Cs;let e=[pa(process.cwd(),"afk.config.json"),_t(),Wl()];for(let t of e)if(qf(t))try{let n=nk(t,"utf-8"),r=JSON.parse(n),o={},s=PS(r.models);if(typeof r.model=="string"&&r.model.length>0){let i=r.model.toLowerCase();o.model=tf(i)?i:r.model}if(typeof r.maxTokens=="number"&&(o.maxTokens=r.maxTokens),typeof r.temperature=="number"&&(o.temperature=r.temperature),r.systemPrompt&&(o.systemPrompt=r.systemPrompt),typeof r.permissionMode=="string"){let i=r.permissionMode;(i==="default"||i==="plan"||i==="autonomous"||i==="bypassPermissions")&&(o.permissionMode=i)}if(r.autoRouting&&typeof r.autoRouting=="object"){let i={};typeof r.autoRouting.interactive=="boolean"&&(i.interactive=r.autoRouting.interactive),typeof r.autoRouting.chat=="boolean"&&(i.chat=r.autoRouting.chat),typeof r.autoRouting.telegram=="boolean"&&(i.telegram=r.autoRouting.telegram),typeof r.autoRouting.daemon=="boolean"&&(i.daemon=r.autoRouting.daemon),o.autoRouting=i}if(r.daemon&&typeof r.daemon=="object"){let i={};typeof r.daemon.task=="string"&&(i.task=r.daemon.task),typeof r.daemon.taskId=="string"&&(i.taskId=r.daemon.taskId);let a=r.daemon.worktreePrune;a&&typeof a=="object"&&(i.worktreePrune={enabled:typeof a.enabled=="boolean"?a.enabled:!0,cron:typeof a.cron=="string"?a.cron:"0 4 * * *",maxAgeDaysClean:typeof a.maxAgeDaysClean=="number"?a.maxAgeDaysClean:14,maxAgeDaysDirty:typeof a.maxAgeDaysDirty=="number"?a.maxAgeDaysDirty:30,scope:typeof a.scope=="string"?a.scope:"all"}),o.daemon=i}if(r.telegram&&typeof r.telegram=="object"){let i={},a=r.telegram.notify;if(a&&typeof a=="object"){let l={};if((a.mode==="primary"||a.mode==="broadcast"||a.mode==="custom")&&(l.mode=a.mode),typeof a.primaryChatId=="number"&&Number.isFinite(a.primaryChatId)&&(l.primaryChatId=a.primaryChatId),Array.isArray(a.targets)){let c=a.targets.filter(u=>typeof u=="number"&&Number.isFinite(u));c.length>0&&(l.targets=c)}i.notify=l}o.telegram=i}if(r.updatePolicy&&["notify","auto","off"].includes(r.updatePolicy)&&(o.updatePolicy=r.updatePolicy),typeof r.autoResumeOnUsageLimit=="boolean"&&(o.autoResumeOnUsageLimit=r.autoResumeOnUsageLimit),typeof r.bgSummaries=="boolean"&&(o.bgSummaries=r.bgSummaries),typeof r.maxSummaryCallsPerSession=="number"&&(o.maxSummaryCallsPerSession=Math.min(500,Math.max(1,r.maxSummaryCallsPerSession))),r.hooks!==null&&typeof r.hooks=="object"&&!Array.isArray(r.hooks)&&(o.hooks=r.hooks),typeof r.enableShellHooks=="boolean"&&(o.enableShellHooks=r.enableShellHooks),t!==pa(process.cwd(),"afk.config.json")){let i=ua(r.importFrom);i!==void 0&&(o.importFrom=i)}if(r.interactive&&typeof r.interactive=="object"){let i={};typeof r.interactive.worktreeAutoname=="boolean"&&(i.worktreeAutoname=r.interactive.worktreeAutoname),typeof r.interactive.worktreeBranchPrefix=="string"&&(i.worktreeBranchPrefix=Hf(r.interactive.worktreeBranchPrefix,`${t}#/interactive/worktreeBranchPrefix`)),typeof r.interactive.worktreeBase=="string"&&r.interactive.worktreeBase.trim().length>0&&(Kf(r.interactive.worktreeBase,`${t}#/interactive/worktreeBase`),i.worktreeBase=r.interactive.worktreeBase),typeof r.interactive.suggestGhost=="boolean"&&(i.suggestGhost=r.interactive.suggestGhost),Object.keys(i).length>0&&(o.interactive=i)}return Cs={config:o,sourcePath:t,modelsPartial:s},Cs}catch(n){console.error(`Warning: Failed to parse ${t}:`,n)}return Cs={config:{},sourcePath:void 0,modelsPartial:{}},Cs}function gU(){if(_s!==void 0)return _s.value;let e=[pa(process.cwd(),"AFK.md"),pa(_e(),"AFK.md")];for(let t of e)if(qf(t))try{let n=nk(t,"utf-8").trim();if(n.length>0)return _s={value:{content:n,path:t}},_s.value}catch{}return _s={value:null},_s.value}function ok(){return Vf().config.telegram??{}}function Is(){return Vf().config.permissionMode??rk}function bt(e){let t=fU(),{config:n,sourcePath:r,modelsPartial:o}=Vf(),s={...da,...t,...n,...e},i;if(t.systemPrompt!==void 0)i="env:AFK_SYSTEM_PROMPT";else if(n.systemPrompt!==void 0&&r!==void 0)i=`file:${r}`;else if(s.systemPrompt===void 0){let c=gU();c!==null&&(s.systemPrompt=c.content,i=`afk-md:${c.path}`)}let a={model:s.model??da.model,maxTokens:s.maxTokens??da.maxTokens,temperature:s.temperature??da.temperature,updatePolicy:s.updatePolicy??da.updatePolicy,...s.apiKey!==void 0?{apiKey:s.apiKey}:{},...s.baseUrl!==void 0?{baseUrl:s.baseUrl}:{},...s.openaiBaseUrl!==void 0?{openaiBaseUrl:s.openaiBaseUrl}:{},...s.systemPrompt!==void 0?{systemPrompt:s.systemPrompt}:{},...i!==void 0?{systemPromptSource:i}:{},permissionMode:s.permissionMode??rk,...s.autoRouting!==void 0?{autoRouting:s.autoRouting}:{},...s.daemon!==void 0?{daemon:s.daemon}:{},...s.telegram!==void 0?{telegram:s.telegram}:{},...s.bgSummaries!==void 0?{bgSummaries:s.bgSummaries}:{},...s.maxSummaryCallsPerSession!==void 0?{maxSummaryCallsPerSession:s.maxSummaryCallsPerSession}:{},...s.interactive!==void 0?{interactive:s.interactive}:{},...s.hooks!==void 0?{hooks:s.hooks}:{},...s.enableShellHooks!==void 0?{enableShellHooks:s.enableShellHooks}:{},...s.importFrom!==void 0?{importFrom:s.importFrom}:{}},l=e?.models??Zm(o);if(sc(l),a.models=l,typeof a.model=="string"&&a.model.toLowerCase().startsWith("local-")&&(a.baseUrl===void 0||a.baseUrl.length===0))throw new Error(`Model '${a.model}' requires AFK_LOCAL_BASE_URL to be set (e.g. AFK_LOCAL_BASE_URL=http://127.0.0.1:8080). Point it at your local Anthropic-Messages-compatible server.`);return a}var da,rk,ek,zf,tk,Cs,_s,Nt=C(()=>{"use strict";$n();qt();Ve();W();Rs();ca();G();uo();da={model:"sonnet",maxTokens:4096,temperature:1,updatePolicy:"notify"},rk="bypassPermissions",ek=!1;tk=new Set});function hU(e,t){return t!==void 0&&Number.isFinite(t)&&t!==0?t:e.find(r=>r>0)??e[0]}function yU(e,t={}){let n=[...e],r=t.mode??"primary";if(r==="broadcast")return n;if(r==="custom"){let s=(t.targets??[]).filter(i=>typeof i=="number"&&Number.isFinite(i)&&i!==0);if(s.length>0)return[...new Set(s)]}let o=hU(n,t.primaryChatId);return o!==void 0?[o]:[]}function bU(e){if(!e)return;let t=e.trim();if(!/^-?\d+$/.test(t))return;let n=Number(t);return Number.isFinite(n)&&n!==0?n:void 0}function wU(e){if(!e)return;let t=e.trim().toLowerCase();return t==="primary"||t==="broadcast"||t==="custom"?t:void 0}function SU(){let e=ok().notify??{},t=e.mode??wU(k.AFK_TELEGRAM_NOTIFY_MODE),n=e.primaryChatId??bU(k.AFK_TELEGRAM_PRIMARY_CHAT_ID);return{...t!==void 0?{mode:t}:{},...n!==void 0?{primaryChatId:n}:{},...e.targets!==void 0?{targets:e.targets}:{}}}function Ps(){let e=Lv(k.AFK_TELEGRAM_ALLOWED_CHAT_IDS);return yU(e,SU())}var jc=C(()=>{"use strict";Fv();Nt();G()});function sk(e,t=4096){if(e.length<=t)return[e];let n=[],r=e;for(;r.length>0;){if(r.length<=t){n.push(r);break}let o=t,s=r.lastIndexOf(`
1074
1074
  `,t);if(s>t-500&&s>0)o=s+1;else{let i=r.slice(0,t).match(/[.!?]\s+(?=[A-Z])/g);if(i&&i.length>0){let a=i[i.length-1];if(a){let l=r.lastIndexOf(a,t);l>t-200&&l>0&&(o=l+2)}}else{let a=r.lastIndexOf(" ",t);a>t-100&&a>0&&(o=a+1)}}n.push(r.slice(0,o).trim()),r=r.slice(o).trim()}return n}var ik=C(()=>{"use strict"});var Yf={};Ll(Yf,{push:()=>Uc,pushIfConfigured:()=>wr});async function Uc(e){if(!e.token)throw new Error("push: token is required");if(e.chatId===""||e.chatId==null||e.chatId===0)throw new Error("push: chatId is required");let t=e.fetchImpl??fetch,r=`${e.apiBase??vU}/bot${e.token}/sendMessage`,o={chat_id:e.chatId,text:e.text.slice(0,4096)};e.parseMode&&(o.parse_mode=e.parseMode),e.replyMarkup&&(o.reply_markup=e.replyMarkup);let s=new AbortController,i=setTimeout(()=>s.abort(),1e4);try{let a=await t(r,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o),signal:s.signal});if(a.ok)return{ok:!0,status:a.status};let l;try{l=(await a.json()).description}catch{l=`HTTP ${a.status}`}return{ok:!1,status:a.status,...l!==void 0?{errorMessage:l}:{}}}catch(a){return{ok:!1,status:0,errorMessage:a instanceof Error?a.message:String(a)}}finally{clearTimeout(i)}}async function wr(e,t={}){let n=k.TELEGRAM_BOT_TOKEN;if(!n)return null;let r=Ps();if(r.length===0)return null;let o=sk(e),s=[];for(let i of r)for(let a=0;a<o.length;a++)s.push(await Uc({token:n,chatId:i,text:o[a]??"",...t.parseMode!==void 0?{parseMode:t.parseMode}:{},...t.replyMarkup!==void 0&&a===0?{replyMarkup:t.replyMarkup}:{},...t.fetchImpl!==void 0?{fetchImpl:t.fetchImpl}:{}}));return s}var vU,po=C(()=>{"use strict";jc();ik();G();vU="https://api.telegram.org"});function kU(e=Uc){return async(t,n)=>{if(!t||typeof t!="object")return{content:"Invalid input: expected an object",isError:!0};let o=t.message;if(typeof o!="string")return{content:"Invalid input: message must be a string",isError:!0};if(o.length===0)return{content:"Invalid input: message must be non-empty",isError:!0};if(o.length>ak)return{content:`Invalid input: message exceeds Telegram's ${ak}-character limit (got ${o.length}). Split into multiple sends or trim before calling.`,isError:!0};let s=k.TELEGRAM_BOT_TOKEN;if(!s)return{content:"Telegram is not configured: TELEGRAM_BOT_TOKEN is not set. Run the bot setup wizard or export the env var before using send_telegram.",isError:!0};let i=Ps();if(i.length===0)return{content:"Telegram is not configured: AFK_TELEGRAM_ALLOWED_CHAT_IDS is empty or unset. Add the operator chat ID(s) before using send_telegram.",isError:!0};let a=[];for(let l of i){let c=await e({token:s,chatId:l,text:o});c.ok||a.push(`chat ${l}: ${c.errorMessage??`HTTP ${c.status}`}`)}return a.length===i.length?{content:`Failed to send Telegram message to any chat. ${a.join("; ")}`,isError:!0}:a.length>0?{content:`Sent Telegram message to ${i.length-a.length}/${i.length} chat(s); ${a.length} failed: ${a.join("; ")}`}:{content:i.length===1?`Sent Telegram message to chat ${i[0]}.`:`Sent Telegram message to ${i.length} chats.`}}}var ak,lk,ck=C(()=>{"use strict";G();po();jc();ak=4096;lk=kU()});import{JSDOM as EU}from"jsdom";import{Readability as xU}from"@mozilla/readability";import TU from"turndown";function uk(e){return e.replace(/\n{3,}/g,`
1075
1075
 
1076
- `).trim()}function RU(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function pk(e,t){let r=new EU(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new xU(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=uk(Xf.turndown(s.content)),u=(s.title??"").trim()||o,d=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:u,markdown:c,textLength:d,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",l=uk(Xf.turndown(a));return{title:o,markdown:l,textLength:RU(i),usedFallback:!0}}var dk,Xf,mk=C(()=>{"use strict";dk=200,Xf=new TU({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});Xf.remove(["script","style","noscript","iframe"])});import{readFileSync as AU}from"node:fs";import{join as CU}from"path";function _U(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function fk(e,t){return _U(t).test(e)}function MU(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(IU.has(t))return!0;if(PU.has(t))return!1}return!1}function gk(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function OU(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function $U(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function DU(e){try{return AU(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function LU(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return n}function hk(e){let t=e?.env??k,n=e?.readFileSync??DU,r=e?.surface??t.AGENT_SURFACE,o=MU(t.AFK_BROWSER_HEADLESS,r),s=gk(t.AFK_BROWSER_ALLOWED_DOMAINS),i=gk(t.AFK_BROWSER_BLOCKED_DOMAINS),a=$U(t.AFK_BROWSER_DOM_SNAPSHOTS),l=OU(t.AFK_BROWSER_BACKEND),c={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null},u=t.AFK_BROWSER_CONFIG,d=u!==void 0&&u.trim()!==""?u.trim():CU(zt(),"browser.json"),p=n(d);if(p===void 0)return c;let f;try{f=JSON.parse(p)}catch(h){throw new Error(`Failed to parse browser config at ${d}: ${String(h)}`)}if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`Browser config at ${d} must be a JSON object`);let g=LU(c,f);return g.configPath=d,g}function Zf(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(fk(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>fk(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var IU,PU,Qf=C(()=>{"use strict";G();W();IU=new Set(["daemon","subagent","telegram","afk"]),PU=new Set(["repl","interactive","cli"])});import FU from"node:fs";import NU from"node:path";import{chromium as BU}from"playwright";function jU(){try{return"4.23.2"}catch{}try{let e=NU.resolve(import.meta.dirname,"../../../package.json"),t=FU.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var UU,Hc,yk=C(()=>{"use strict";UU=jU(),Hc=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=BU.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s={context:o,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),o}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",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(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await i.content(),c=i.url(),u=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${UU}`}}}});import{createHash as HU}from"crypto";function eg(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of KU)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function bk(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&WU.test(e.label))}function wk(e){return HU("sha256").update(e,"utf8").digest("hex").slice(0,8)}function Sk(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var KU,WU,ma=C(()=>{"use strict";KU=[{name:"aws-access-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"github-pat",regex:/ghp_[a-zA-Z0-9]{36}/g},{name:"openai-bearer",regex:/sk-[a-zA-Z0-9_-]{20,}/g},{name:"slack-token",regex:/xox[abp]-[a-zA-Z0-9-]{10,}/g},{name:"jwt",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g},{name:"form-password",regex:/password=[^&\s]+/gi}];WU=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as GU}from"node:crypto";function zU(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function qU(e,t,n){return`el_${GU("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function JU(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function vk(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Ek(e,t){let n=e.role??"",r=e.name??"";kk.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])Ek(s,t)}async function VU(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let u=window.getComputedStyle(i);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},xk).catch(()=>[])}async function YU(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in s?s.value:void 0,d=u!==void 0?String(u):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},xk).catch(()=>[])}function XU(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Kc(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=XU(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=VU(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,f,g,h]=await Promise.all([i,a,l,c,u]),b,y=!1;d!==null?(b=[],Ek(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await YU(e)).filter(O=>kk.has(O.role??"")));let S=new Map;for(let $ of p){let O=vk($.name),D=S.get(O);(!D||D.bbox.w===0&&$.bbox.w>0)&&S.set(O,$)}let w=b.map($=>({ax:$,dom:S.get(vk($.name??""))})),R=r?w:w.filter($=>$.dom?$.dom.bbox.w>0||$.dom.bbox.h>0:!0);R.sort(($,O)=>{let D=$.dom?.bbox.y??0,N=O.dom?.bbox.y??0;if(D!==N)return D-N;let B=$.dom?.bbox.x??0,U=O.dom?.bbox.x??0;return B-U}),R.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=R.slice(0,n).map(($,O)=>{let D=$.ax.role??"generic",N=$.ax.name??"",B=qU(D,N,O),U=$.dom?.bbox??{x:0,y:0,w:0,h:0},j=$.dom?.type??null,F=null;$.ax.value!==void 0&&$.ax.value!==null&&(F=String($.ax.value)),$.ax.checked!==void 0&&(F=String($.ax.checked)),bk({role:D,kind:j})&&(F="[redacted]");let L={disabled:$.ax.disabled??!1};$.ax.checked!==void 0&&(L.checked=$.ax.checked===!0||$.ax.checked==="mixed"),$.ax.selected!==void 0&&(L.selected=$.ax.selected),$.ax.expanded!==void 0&&(L.expanded=$.ax.expanded);let M;$.dom?.testId?M=`[data-testid="${$.dom.testId}"]`:$.dom?.id&&(M=`#${$.dom.id}`);let q={id:B,role:D,label:zU(N),kind:j,value:F,state:L,bbox:U};return M!==void 0&&(q.selector=M),q}),T="idle";try{let $=await e.evaluate(()=>document.readyState);$==="loading"?T="loading":$==="interactive"?T="navigating":T="idle"}catch{T="navigating"}T!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let v=JU(f),_=`obs_${t.observationCounter.toString(36)}`,I=new Date().toISOString();return{observationId:_,url:g,title:h,textSummary:v,interactive:A,status:{httpStatus:t.httpStatus??null,loadingState:T,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:I}}var kk,xk,Tk=C(()=>{"use strict";ma();kk=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);xk="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Rk(e,t){try{let n=await e.nth(t).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let 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 tg(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>Rk(e,s)))).filter(o=>o!==null)}async function ZU(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(i)||(t.add(i),n.push({key:i,locator:r,index:s}))}return n}async function ng(e,t,n){switch(t.kind){case"element_id":return QU(e,t,n);case"selector":return e1(e,t);case"semantic":return t1(e,t)}}async function QU(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:t};if(s===1)return{outcome:"resolved",locator:o};let i=await tg(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function e1(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await tg(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function t1(e,t){return t.role!==void 0?n1(e,t.text,t.role):r1(e,t.text,t)}async function n1(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await tg(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function r1(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),s=e.getByLabel(t,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let u=[];i>0&&u.push({loc:r,count:i}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:s,count:l});let d=await ZU(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=d.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let y=await Rk(b.locator,b.index);if(y!==null){let S=`${y.role}:${y.label}:${h}`,w=0;for(let R=0;R<S.length;R++)w=w*31+S.charCodeAt(R)>>>0;f.push({...y,id:`el_${w.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var Ak=C(()=>{"use strict"});import{randomBytes as o1}from"crypto";import{mkdir as s1,stat as i1,writeFile as a1}from"fs/promises";import{join as rg}from"path";import{gzip as l1}from"zlib";import{promisify as c1}from"util";function u1(e){return rg(is(e),"browser")}function d1(e){return rg(u1(e),"screenshots")}function p1(){return new Date().toISOString().replace(/[:.]/g,"-")}function m1(){return o1(3).toString("hex")}async function og(e,t,n){if(t.length>Ck)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Ck} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=d1(e);await s1(r,{recursive:!0});let o=`${p1()}-${m1()}-${n}.png`,s=rg(r,o);await a1(s,t);let{size:i}=await i1(s);return{path:s,bytes:i}}var Rae,Ck,_k=C(()=>{"use strict";W();ma();Rae=c1(l1);Ck=5*1024*1024});var Pk={};Ll(Pk,{PlaywrightProvider:()=>sg});function Ik(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var sg,Mk=C(()=>{"use strict";yk();Tk();Ak();Qf();ma();_k();sg=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Hc(t)}async open(t){let n=Zf(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(c){a=c}(t.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await Kc(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,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;t.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Kc(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=t.timeoutMs??3e4,a=await ng(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Ik(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:i});break;case"fill":{let h=eg(t.value??"");await l.fill(t.value??"");break}case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=r.url();if(d!==s){let h=Zf(d,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:d,reason:h.reason}}let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Kc(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(t.target!==void 0){let u=await ng(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Ik(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await u.locator.screenshot()}else s=await r.screenshot({fullPage:t.fullPage??!1});let{path:i,bytes:a}=await og(n,s,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,s){t.knownElements=new Map(n.map(i=>[i.id,i])),t.currentUrl=r,t.currentTitle=o,t.lastAction=s,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:s}=await og(n,o,r);return s}catch{return null}}}});var fo={};Ll(fo,{__resetBrowserRegistryForTests:()=>b1,browserProviderActive:()=>h1,closeBrowserProvider:()=>ig,getBrowserProvider:()=>g1,peekBrowserProvider:()=>y1});function Ok(){Promise.resolve(ig()).then(()=>{process.exit(130)})}function $k(){Promise.resolve(ig()).then(()=>{process.exit(143)})}function Dk(){dn=null}function f1(){Wc||(process.on("SIGINT",Ok),process.on("SIGTERM",$k),process.on("exit",Dk),Wc=!0)}function Lk(){Wc&&(process.removeListener("SIGINT",Ok),process.removeListener("SIGTERM",$k),process.removeListener("exit",Dk),Wc=!1)}async function g1(e){return dn!==null?dn:(mo!==null||(mo=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(Mk(),Pk)),n=hk(e),r=new t(n);return f1(),dn=r,mo=null,r})()),mo)}async function ig(){if(dn===null)return;let e=dn;dn=null,mo=null,Lk(),await e.shutdown()}function h1(){return dn!==null}function y1(){return dn}function b1(){dn=null,mo=null,Lk()}var dn,mo,Wc,go=C(()=>{"use strict";Qf();dn=null,mo=null,Wc=!1});function Fk(e,t){try{return pk(e,t)}catch(n){return V("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function E1(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(go(),fo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function Nk(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??E1,o=null,s=e,i=null,a=null;try{let c=await n(e,{headers:k1,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(v1.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let d=await c.text();if(S1.test(u)&&!w1.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=Fk(d,s)}}catch(c){if(t.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<dk)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),u=Fk(c.html,c.finalUrl);if(o===null||u.textLength>=o.textLength)return{title:u.title,markdown:u.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let u=c instanceof Error?c.message:String(c),d=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${e}: fetch failed (${d}) and render failed (${u}).`);throw p.cause=c,p}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${i??"error"}).`)}var w1,S1,v1,k1,Bk=C(()=>{"use strict";mk();Pe();w1=/(text\/html|application\/xhtml\+xml)/i,S1=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,v1=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,k1={"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 R1(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(x1,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),T1),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=Pc(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function jk(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?R1({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function Uk(e,t){if(t.length===0)return`# Search results for "${e}"
1076
+ `).trim()}function RU(e){return(e?.textContent??"").replace(/\s+/g," ").trim().length}function pk(e,t){let r=new EU(e,{url:t}).window.document,o=(r.title??"").trim(),s=null;try{let c=r.cloneNode(!0);s=new xU(c).parse()}catch{s=null}if(s&&typeof s.content=="string"&&s.content.trim().length>0){let c=uk(Xf.turndown(s.content)),u=(s.title??"").trim()||o,d=typeof s.length=="number"&&s.length>0?s.length:(s.textContent??"").replace(/\s+/g," ").trim().length;return{title:u,markdown:c,textLength:d,usedFallback:!1}}let i=r.body,a=i?.innerHTML??"",l=uk(Xf.turndown(a));return{title:o,markdown:l,textLength:RU(i),usedFallback:!0}}var dk,Xf,mk=C(()=>{"use strict";dk=200,Xf=new TU({headingStyle:"atx",codeBlockStyle:"fenced",bulletListMarker:"-"});Xf.remove(["script","style","noscript","iframe"])});import{readFileSync as AU}from"node:fs";import{join as CU}from"path";function _U(e){let n=e.replace(/[.+?()[\]{}/\\^$|]/g,"\\$&").replace(/\*/g,"[^.]*");return new RegExp(`^${n}$`,"i")}function fk(e,t){return _U(t).test(e)}function MU(e,t){if(e!==void 0){let n=e.trim().toLowerCase();if(n==="1"||n==="true"||n==="yes")return!0;if(n==="0"||n==="false"||n==="no")return!1}if(t!==void 0){if(IU.has(t))return!0;if(PU.has(t))return!1}return!1}function gk(e){return e===void 0||e.trim()===""?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>t.length>0)}function OU(e){if(e===void 0||e===""||e==="playwright")return"playwright";throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${e}`)}function $U(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"}function DU(e){try{return AU(e,"utf8")}catch(t){if(t.code==="ENOENT")return;throw t}}function LU(e,t){let n={...e};if(typeof t.headless=="boolean"&&(n.headless=t.headless),Array.isArray(t.allowedDomains)&&(n.allowedDomains=t.allowedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),Array.isArray(t.blockedDomains)&&(n.blockedDomains=t.blockedDomains.filter(r=>typeof r=="string").map(r=>r.trim().toLowerCase()).filter(r=>r.length>0)),typeof t.domSnapshots=="boolean"&&(n.domSnapshots=t.domSnapshots),t.backend==="playwright")n.backend="playwright";else if(t.backend!==void 0)throw new Error(`AFK_BROWSER_BACKEND: only "playwright" is supported in Phase 1, got: ${String(t.backend)}`);return n}function hk(e){let t=e?.env??k,n=e?.readFileSync??DU,r=e?.surface??t.AGENT_SURFACE,o=MU(t.AFK_BROWSER_HEADLESS,r),s=gk(t.AFK_BROWSER_ALLOWED_DOMAINS),i=gk(t.AFK_BROWSER_BLOCKED_DOMAINS),a=$U(t.AFK_BROWSER_DOM_SNAPSHOTS),l=OU(t.AFK_BROWSER_BACKEND),c={headless:o,allowedDomains:s,blockedDomains:i,domSnapshots:a,backend:l,configPath:null},u=t.AFK_BROWSER_CONFIG,d=u!==void 0&&u.trim()!==""?u.trim():CU(zt(),"browser.json"),p=n(d);if(p===void 0)return c;let f;try{f=JSON.parse(p)}catch(h){throw new Error(`Failed to parse browser config at ${d}: ${String(h)}`)}if(typeof f!="object"||f===null||Array.isArray(f))throw new Error(`Browser config at ${d} must be a JSON object`);let g=LU(c,f);return g.configPath=d,g}function Zf(e,t){let n;try{n=new URL(e).hostname.toLowerCase()}catch{return{allowed:!1,reason:`invalid URL: ${e}`}}for(let r of t.blockedDomains)if(fk(n,r))return{allowed:!1,reason:`blocked by AFK_BROWSER_BLOCKED_DOMAINS: ${r}`};return t.allowedDomains.length>0&&!t.allowedDomains.some(o=>fk(n,o))?{allowed:!1,reason:"not in AFK_BROWSER_ALLOWED_DOMAINS"}:{allowed:!0}}var IU,PU,Qf=C(()=>{"use strict";G();W();IU=new Set(["daemon","subagent","telegram","afk"]),PU=new Set(["repl","interactive","cli"])});import FU from"node:fs";import NU from"node:path";import{chromium as BU}from"playwright";function jU(){try{return"4.24.0"}catch{}try{let e=NU.resolve(import.meta.dirname,"../../../package.json"),t=FU.readFileSync(e,"utf8"),n=JSON.parse(t);return typeof n.version=="string"?n.version:"unknown"}catch{return"unknown"}}var UU,Hc,yk=C(()=>{"use strict";UU=jU(),Hc=class{config;browser;sessions=new Map;launchPromise;shutdownComplete=!1;constructor(t){this.config=t}async ensureBrowser(){return this.browser!==void 0&&this.browser.isConnected()?this.browser:(this.browser!==void 0&&!this.browser.isConnected()&&(this.browser=void 0,this.launchPromise=void 0),this.launchPromise!==void 0?this.launchPromise:(this.launchPromise=BU.launch({headless:this.config.headless}).then(t=>(this.browser=t,this.launchPromise=void 0,t)).catch(t=>{throw this.launchPromise=void 0,t}),this.launchPromise))}isBrowserActive(){return this.browser!==void 0&&this.browser.isConnected()}async ensureContext(t){let n=this.sessions.get(t);if(n!==void 0)return n.context;let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s={context:o,page:void 0,consoleErrors:0,lastHttpStatus:null,openDialog:void 0};return this.sessions.set(t,s),o}async ensurePage(t){let n=this.sessions.get(t);if(n!==void 0&&n.page!==void 0)return n.page;await this.ensureContext(t);let r=this.sessions.get(t);if(r===void 0)throw new Error(`[BrowserLauncher] session entry disappeared for sessionId=${t}`);if(r.page!==void 0)return r.page;let o=await r.context.newPage();return r.page=o,o.on("console",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(t){return this.sessions.get(t)?.page}async renderHtml(t,n){let o=await(await this.ensureBrowser()).newContext(this.contextOptions()),s=()=>{o.close().catch(()=>{})};if(n.signal?.aborted===!0)throw await o.close().catch(()=>{}),new Error("render aborted");n.signal!==void 0&&n.signal.addEventListener("abort",s,{once:!0});try{let i=await o.newPage(),a=await i.goto(t,{timeout:n.timeoutMs,waitUntil:n.waitUntil}),l=await i.content(),c=i.url(),u=a!==null?a.status():null;return{html:l,finalUrl:c,httpStatus:u}}finally{n.signal!==void 0&&n.signal.removeEventListener("abort",s),await o.close().catch(()=>{})}}getConsoleErrorCount(t){return this.sessions.get(t)?.consoleErrors??0}getLastHttpStatus(t){return this.sessions.get(t)?.lastHttpStatus??null}hasOpenDialog(t){return this.sessions.get(t)?.openDialog!==void 0}async dismissDialog(t,n=!0){let r=this.sessions.get(t);if(r===void 0||r.openDialog===void 0)return;let o=r.openDialog;r.openDialog=void 0,n?await o.accept():await o.dismiss()}async closeSession(t){let n=this.sessions.get(t);n!==void 0&&(this.sessions.delete(t),n.page!==void 0&&await n.page.close().catch(()=>{}),await n.context.close().catch(()=>{}))}async shutdown(){if(this.shutdownComplete)return;this.shutdownComplete=!0;let t=[...this.sessions.keys()];if(await Promise.all(t.map(n=>this.closeSession(n))),this.browser!==void 0){let n=this.browser;this.browser=void 0,await n.close().catch(()=>{})}}activeSessions(){return this.sessions.size}contextOptions(){return{viewport:{width:1280,height:800},userAgent:`Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 agent-afk/${UU}`}}}});import{createHash as HU}from"crypto";function eg(e){if(e.length===0)return e;let t=e;for(let{regex:n,name:r}of KU)r==="form-password"?t=t.replace(n,"password=[redacted]"):t=t.replace(n,"[redacted]");return t}function bk(e){return!!(e.role==="textbox"&&e.kind==="password"||e.label&&WU.test(e.label))}function wk(e){return HU("sha256").update(e,"utf8").digest("hex").slice(0,8)}function Sk(e){let t=e.replace(/\s+/g," ").trim();return t.length<=80?t:t.slice(0,77)+"..."}var KU,WU,ma=C(()=>{"use strict";KU=[{name:"aws-access-key",regex:/AKIA[0-9A-Z]{16}/g},{name:"github-pat",regex:/ghp_[a-zA-Z0-9]{36}/g},{name:"openai-bearer",regex:/sk-[a-zA-Z0-9_-]{20,}/g},{name:"slack-token",regex:/xox[abp]-[a-zA-Z0-9-]{10,}/g},{name:"jwt",regex:/eyJ[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}\.[a-zA-Z0-9_-]{20,}/g},{name:"form-password",regex:/password=[^&\s]+/gi}];WU=/password|secret|token|api[_-]?key|otp|2fa/i});import{createHash as GU}from"node:crypto";function zU(e){return e?e.replace(/\s+/g," ").trim().slice(0,200):""}function qU(e,t,n){return`el_${GU("sha256").update(`${e}:${t}:${n}`).digest("hex").slice(0,6)}`}function JU(e){let t=e.replace(/\s+/g," ").trim(),n=4e3;return t.length<=n?t:t.slice(0,n)+"\u2026[truncated]"}function vk(e){return e.replace(/\s+/g," ").trim().toLowerCase().slice(0,100)}function Ek(e,t){let n=e.role??"",r=e.name??"";kk.has(n)&&(n!=="searchbox"&&n!=="spinbutton"||r!=="")&&t.push(e);for(let s of e.children??[])Ek(s,t)}async function VU(e){return e.evaluate(t=>{let n=Array.from(document.querySelectorAll(t)),r=[];for(let o of n){let s=o.getBoundingClientRect(),i=o;if(s.width===0&&s.height===0){let u=window.getComputedStyle(i);if(u.display==="none"||u.visibility==="hidden")continue}let a=o.tagName.toLowerCase(),l=o.getAttribute("aria-label")??o.getAttribute("placeholder")??(o.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a==="input"?o.type||null:o.getAttribute("type");r.push({name:l,tagName:a,type:c,id:o.id||null,testId:o.getAttribute("data-testid"),bbox:{x:Math.round(s.left),y:Math.round(s.top),w:Math.round(s.width),h:Math.round(s.height)}})}return r},xk).catch(()=>[])}async function YU(e){return e.evaluate(t=>{let n={button:"button",a:"link",input:"textbox",textarea:"textbox",select:"combobox"},r=Array.from(document.querySelectorAll(t)),o=[];for(let s of r){let i=s.tagName.toLowerCase(),a=s.getAttribute("role")??"",l=s.getAttribute("aria-label")??s.getAttribute("placeholder")??(s.textContent??"").replace(/\s+/g," ").trim().slice(0,100),c=a||(n[i]??"");if(i==="input"){let h=s.type;h==="checkbox"?c="checkbox":h==="radio"?c="radio":h==="button"||h==="submit"||h==="reset"?c="button":h==="search"?c="searchbox":c="textbox"}if(!c)continue;let u="value"in s?s.value:void 0,d=u!==void 0?String(u):void 0,p=s.disabled??!1,f=i==="input"?s.checked:void 0,g={role:c,name:l,disabled:p};d!==void 0&&(g.value=d),f!==void 0&&(g.checked=f),o.push(g)}return o},xk).catch(()=>[])}function XU(e){let n=e.accessibility;return n!==null&&typeof n=="object"?n:null}async function Kc(e,t){let n=t.maxElements??80,r=t.includeHidden??!1,o=[],s=XU(e),i=s?s.snapshot({interestingOnly:!1}).catch(()=>null):Promise.resolve(null),a=VU(e),l=e.evaluate(()=>document.body?.innerText??"").catch(()=>""),c=Promise.resolve(e.url()),u=e.title().catch(()=>""),[d,p,f,g,h]=await Promise.all([i,a,l,c,u]),b,y=!1;d!==null?(b=[],Ek(d,b)):(o.push("observation skipped accessibility tree (returned null)"),y=!0,b=(await YU(e)).filter(O=>kk.has(O.role??"")));let S=new Map;for(let $ of p){let O=vk($.name),D=S.get(O);(!D||D.bbox.w===0&&$.bbox.w>0)&&S.set(O,$)}let w=b.map($=>({ax:$,dom:S.get(vk($.name??""))})),R=r?w:w.filter($=>$.dom?$.dom.bbox.w>0||$.dom.bbox.h>0:!0);R.sort(($,O)=>{let D=$.dom?.bbox.y??0,N=O.dom?.bbox.y??0;if(D!==N)return D-N;let B=$.dom?.bbox.x??0,U=O.dom?.bbox.x??0;return B-U}),R.length>200&&o.push("page has 200+ interactive elements; consider scoping");let A=R.slice(0,n).map(($,O)=>{let D=$.ax.role??"generic",N=$.ax.name??"",B=qU(D,N,O),U=$.dom?.bbox??{x:0,y:0,w:0,h:0},j=$.dom?.type??null,F=null;$.ax.value!==void 0&&$.ax.value!==null&&(F=String($.ax.value)),$.ax.checked!==void 0&&(F=String($.ax.checked)),bk({role:D,kind:j})&&(F="[redacted]");let L={disabled:$.ax.disabled??!1};$.ax.checked!==void 0&&(L.checked=$.ax.checked===!0||$.ax.checked==="mixed"),$.ax.selected!==void 0&&(L.selected=$.ax.selected),$.ax.expanded!==void 0&&(L.expanded=$.ax.expanded);let M;$.dom?.testId?M=`[data-testid="${$.dom.testId}"]`:$.dom?.id&&(M=`#${$.dom.id}`);let q={id:B,role:D,label:zU(N),kind:j,value:F,state:L,bbox:U};return M!==void 0&&(q.selector=M),q}),T="idle";try{let $=await e.evaluate(()=>document.readyState);$==="loading"?T="loading":$==="interactive"?T="navigating":T="idle"}catch{T="navigating"}T!=="idle"&&o.push("page is still loading \u2014 observation may be incomplete"),y&&!o.includes("observation skipped accessibility tree (returned null)")&&o.push("observation skipped accessibility tree (returned null)");let v=JU(f),_=`obs_${t.observationCounter.toString(36)}`,I=new Date().toISOString();return{observationId:_,url:g,title:h,textSummary:v,interactive:A,status:{httpStatus:t.httpStatus??null,loadingState:T,hasDialog:t.hasDialog??!1,consoleErrors:t.consoleErrors??0},warnings:o,screenshotPath:t.screenshotPath??null,capturedAt:I}}var kk,xk,Tk=C(()=>{"use strict";ma();kk=new Set(["button","link","textbox","combobox","checkbox","radio","tab","menuitem","menuitemcheckbox","menuitemradio","switch","option","searchbox","spinbutton"]);xk="a[href], button, input, select, textarea, [role], [tabindex], label"});async function Rk(e,t){try{let n=await e.nth(t).evaluate(i=>{let a=i,l=a.getAttribute("role")??a.tagName.toLowerCase(),c=a.getAttribute("aria-label")??a.getAttribute("placeholder")??(a.innerText!=null?a.innerText.trim().slice(0,200):"")??a.getAttribute("title")??"",u=a.getBoundingClientRect();return{role:l,label:c,x:Math.round(u.x),y:Math.round(u.y),w:Math.round(u.width),h:Math.round(u.height)}}),r=`${n.role}:${n.label}:${t}`,o=0;for(let 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 tg(e,t){let n=Math.min(t,5);return(await Promise.all(Array.from({length:n},(o,s)=>Rk(e,s)))).filter(o=>o!==null)}async function ZU(e){let t=new Set,n=[];for(let{loc:r,count:o}of e)for(let s=0;s<o;s++){let i;try{i=await r.nth(s).evaluate(a=>{let l=a,c=l.getBoundingClientRect();return`${l.tagName}@${Math.round(c.x)},${Math.round(c.y)}`})}catch{continue}t.has(i)||(t.add(i),n.push({key:i,locator:r,index:s}))}return n}async function ng(e,t,n){switch(t.kind){case"element_id":return QU(e,t,n);case"selector":return e1(e,t);case"semantic":return t1(e,t)}}async function QU(e,t,n){let r=n.get(t.elementId);if(r===void 0)return{outcome:"not_found",query:t};if(r.selector!==void 0){let l=e.locator(r.selector);if(await l.count()===1)return{outcome:"resolved",locator:l}}let o=e.getByRole(r.role,{name:r.label,exact:!0}),s=await o.count();if(s===0)return{outcome:"not_found",query:t};if(s===1)return{outcome:"resolved",locator:o};let i=await tg(o,s);return{outcome:"ambiguous_target",query:{text:r.label,role:r.role},candidates:i}}async function e1(e,t){let n=e.locator(t.selector),r=await n.count();if(r===0)return{outcome:"not_found",query:t};if(r===1)return{outcome:"resolved",locator:n};let o=await tg(n,r);return{outcome:"ambiguous_target",query:{text:`[selector: ${t.selector}]`},candidates:o}}async function t1(e,t){return t.role!==void 0?n1(e,t.text,t.role):r1(e,t.text,t)}async function n1(e,t,n){let r=e.getByRole(n,{name:t}),o=await r.count();if(o===0)return{outcome:"not_found",query:{kind:"semantic",text:t,role:n}};if(o===1)return{outcome:"resolved",locator:r};let s=await tg(r,o);return{outcome:"ambiguous_target",query:{text:t,role:n},candidates:s}}async function r1(e,t,n){let r=e.getByRole("button",{name:t}),o=e.getByRole("link",{name:t}),s=e.getByLabel(t,{exact:!1}),[i,a,l]=await Promise.all([r.count(),o.count(),s.count()]);if(i+a+l===0)return{outcome:"not_found",query:n};let u=[];i>0&&u.push({loc:r,count:i}),a>0&&u.push({loc:o,count:a}),l>0&&u.push({loc:s,count:l});let d=await ZU(u);if(d.length===0)return{outcome:"not_found",query:n};if(d.length===1){let h=d[0];return h===void 0?{outcome:"not_found",query:n}:{outcome:"resolved",locator:h.locator.nth(h.index)}}let p=d.slice(0,5),f=[];for(let h=0;h<p.length;h++){let b=p[h];if(b===void 0)continue;let y=await Rk(b.locator,b.index);if(y!==null){let S=`${y.role}:${y.label}:${h}`,w=0;for(let R=0;R<S.length;R++)w=w*31+S.charCodeAt(R)>>>0;f.push({...y,id:`el_${w.toString(16).padStart(6,"0").slice(0,6)}`})}}return{outcome:"ambiguous_target",query:{text:t},candidates:f}}var Ak=C(()=>{"use strict"});import{randomBytes as o1}from"crypto";import{mkdir as s1,stat as i1,writeFile as a1}from"fs/promises";import{join as rg}from"path";import{gzip as l1}from"zlib";import{promisify as c1}from"util";function u1(e){return rg(is(e),"browser")}function d1(e){return rg(u1(e),"screenshots")}function p1(){return new Date().toISOString().replace(/[:.]/g,"-")}function m1(){return o1(3).toString("hex")}async function og(e,t,n){if(t.length>Ck)throw new Error(`writeScreenshotSidecar: buffer exceeds ${Ck} byte cap (received ${t.length} bytes). Refusing to write oversized screenshot.`);let r=d1(e);await s1(r,{recursive:!0});let o=`${p1()}-${m1()}-${n}.png`,s=rg(r,o);await a1(s,t);let{size:i}=await i1(s);return{path:s,bytes:i}}var Rae,Ck,_k=C(()=>{"use strict";W();ma();Rae=c1(l1);Ck=5*1024*1024});var Pk={};Ll(Pk,{PlaywrightProvider:()=>sg});function Ik(e){switch(e.kind){case"semantic":return e.role!==void 0?`semantic('${e.text}', role='${e.role}')`:`semantic('${e.text}')`;case"element_id":return`element_id(${e.elementId})`;case"selector":return`selector(${e.selector})`}}var sg,Mk=C(()=>{"use strict";yk();Tk();Ak();Qf();ma();_k();sg=class{name="playwright";config;launcher;sessions=new Map;constructor(t){this.config=t,this.launcher=new Hc(t)}async open(t){let n=Zf(t.url,this.config);if(!n.allowed)return{outcome:"blocked_by_policy",url:t.url,reason:n.reason};let{sessionId:r}=t,o=await this.launcher.ensurePage(r),s=this.ensureSessionState(r),i=null,a=null;try{await o.goto(t.url,{timeout:t.timeoutMs??3e4,waitUntil:t.waitFor??"load"})}catch(c){a=c}(t.screenshot===!0||a!==null)&&(i=await this.captureScreenshot(o,r,"browser_open")),s.observationCounter+=1;let l=await Kc(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,l.interactive,l.url,l.title,"browser_open"),a!==null)throw a;return l}async observe(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_observe: no page open for session ${n}`);let o=this.ensureSessionState(n),s=null;t.screenshot===!0&&(s=await this.captureScreenshot(r,n,"browser_observe")),o.observationCounter+=1;let i=await Kc(r,{observationCounter:o.observationCounter,screenshotPath:s,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n),includeHidden:t.includeHidden,maxElements:t.maxElements});return this.updateSessionFromObservation(o,i.interactive,i.url,i.title,"browser_observe"),i}async act(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_act: no page open for session ${n}`);let o=this.ensureSessionState(n),s=r.url(),i=t.timeoutMs??3e4,a=await ng(r,t.target,o.knownElements);if(a.outcome==="not_found")throw new Error(`browser_act: target not found: ${Ik(t.target)}`);if(a.outcome==="ambiguous_target")return a;let{locator:l}=a,c=null,u=async()=>{switch(t.action){case"click":await l.click({timeout:i});break;case"fill":{let h=eg(t.value??"");await l.fill(t.value??"");break}case"press":await l.press(t.value??"");break;case"select":await l.selectOption(t.value??"");break;case"hover":await l.hover({timeout:i});break;case"scroll_to":await l.scrollIntoViewIfNeeded({timeout:i});break;case"wait_for":await l.waitFor({timeout:i,state:"visible"});break}};try{await u()}catch(h){if(h instanceof Error&&/navigation|net::ERR/i.test(h.message))try{await u()}catch(b){c=b}else c=h}let d=r.url();if(d!==s){let h=Zf(d,this.config);if(!h.allowed)return await r.goBack().catch(()=>{}),{outcome:"blocked_by_policy",url:d,reason:h.reason}}let p=null;(t.screenshot===!0||c!==null)&&(p=await this.captureScreenshot(r,n,"browser_act")),o.observationCounter+=1;let f=await Kc(r,{observationCounter:o.observationCounter,screenshotPath:p,consoleErrors:this.launcher.getConsoleErrorCount(n),httpStatus:this.launcher.getLastHttpStatus(n),hasDialog:this.launcher.hasOpenDialog(n)}),g=`browser_act:${t.action}`;if(this.updateSessionFromObservation(o,f.interactive,f.url,f.title,g),c!==null)throw c;return f}async render(t){return this.launcher.renderHtml(t.url,{timeoutMs:t.timeoutMs??3e4,waitUntil:t.waitFor??"load",signal:t.signal})}async screenshot(t){let{sessionId:n}=t,r=this.launcher.getPage(n);if(r===void 0)throw new Error(`browser_screenshot: no page open for session ${n}`);let o=this.ensureSessionState(n),s;if(t.target!==void 0){let u=await ng(r,t.target,o.knownElements);if(u.outcome==="not_found")throw new Error(`browser_screenshot: target not found: ${Ik(t.target)}`);if(u.outcome==="ambiguous_target")throw new Error("screenshot target ambiguous; specify element_id or selector");s=await u.locator.screenshot()}else s=await r.screenshot({fullPage:t.fullPage??!1});let{path:i,bytes:a}=await og(n,s,"browser_screenshot"),l=0,c=0;if(t.fullPage===!0)try{let u=await r.evaluate(()=>({w:document.documentElement.scrollWidth,h:document.documentElement.scrollHeight}));l=u.w,c=u.h}catch{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}else{let u=r.viewportSize();l=u?.width??0,c=u?.height??0}return{path:i,bytes:a,width:l,height:c,dataBase64:s.toString("base64"),mediaType:"image/png"}}async extract(t){throw new Error("browser_extract not implemented in Phase 1")}async close(t){await this.launcher.closeSession(t.sessionId),this.sessions.delete(t.sessionId)}describe(t){let n=this.sessions.get(t);if(n===void 0)return null;let r=this.launcher.getPage(t);return{active:r!==void 0,url:n.currentUrl,title:n.currentTitle,lastAction:n.lastAction,lastActionAt:n.lastActionAt,openTabs:r!==void 0?1:0}}async shutdown(){this.sessions.clear(),await this.launcher.shutdown()}ensureSessionState(t){let n=this.sessions.get(t);if(n!==void 0)return n;let r={observationCounter:0,knownElements:new Map,lastAction:null,lastActionAt:null,currentUrl:null,currentTitle:null};return this.sessions.set(t,r),r}updateSessionFromObservation(t,n,r,o,s){t.knownElements=new Map(n.map(i=>[i.id,i])),t.currentUrl=r,t.currentTitle=o,t.lastAction=s,t.lastActionAt=new Date().toISOString()}async captureScreenshot(t,n,r){try{let o=await t.screenshot({fullPage:!1}),{path:s}=await og(n,o,r);return s}catch{return null}}}});var fo={};Ll(fo,{__resetBrowserRegistryForTests:()=>b1,browserProviderActive:()=>h1,closeBrowserProvider:()=>ig,getBrowserProvider:()=>g1,peekBrowserProvider:()=>y1});function Ok(){Promise.resolve(ig()).then(()=>{process.exit(130)})}function $k(){Promise.resolve(ig()).then(()=>{process.exit(143)})}function Dk(){dn=null}function f1(){Wc||(process.on("SIGINT",Ok),process.on("SIGTERM",$k),process.on("exit",Dk),Wc=!0)}function Lk(){Wc&&(process.removeListener("SIGINT",Ok),process.removeListener("SIGTERM",$k),process.removeListener("exit",Dk),Wc=!1)}async function g1(e){return dn!==null?dn:(mo!==null||(mo=(async()=>{let{PlaywrightProvider:t}=await Promise.resolve().then(()=>(Mk(),Pk)),n=hk(e),r=new t(n);return f1(),dn=r,mo=null,r})()),mo)}async function ig(){if(dn===null)return;let e=dn;dn=null,mo=null,Lk(),await e.shutdown()}function h1(){return dn!==null}function y1(){return dn}function b1(){dn=null,mo=null,Lk()}var dn,mo,Wc,go=C(()=>{"use strict";Qf();dn=null,mo=null,Wc=!1});function Fk(e,t){try{return pk(e,t)}catch(n){return V("[web/scrape] extraction failed",{url:t,err:n}),{title:"",markdown:"",textLength:0,usedFallback:!0}}}async function E1(e,t){let{getBrowserProvider:n}=await Promise.resolve().then(()=>(go(),fo));return(await n()).render({url:e,timeoutMs:t.timeoutMs,signal:t.signal})}async function Nk(e,t){let n=t.fetchFn??globalThis.fetch,r=t.renderFn??E1,o=null,s=e,i=null,a=null;try{let c=await n(e,{headers:k1,redirect:"follow",signal:t.signal});i=c.status,s=c.url||e;let u=c.headers.get("content-type")??"";if(c.ok){if(v1.test(u))throw new Error(`web_scrape markdown mode received binary content (${u.split(";")[0]}). Use mode: "raw" to fetch the bytes, or a different tool.`);let d=await c.text();if(S1.test(u)&&!w1.test(u))return{title:"",markdown:d.trim(),finalUrl:s,usedRender:!1};o=Fk(d,s)}}catch(c){if(t.signal.aborted||c instanceof Error&&c.message.startsWith("web_scrape markdown mode received binary"))throw c;a=c}if(!(o===null||o.textLength<dk)&&o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};try{let c=await r(e,{timeoutMs:t.timeoutMs,signal:t.signal}),u=Fk(c.html,c.finalUrl);if(o===null||u.textLength>=o.textLength)return{title:u.title,markdown:u.markdown,finalUrl:c.finalUrl,usedRender:!0}}catch(c){if(t.signal.aborted)throw c;if(o===null){let u=c instanceof Error?c.message:String(c),d=a instanceof Error?a.message:`HTTP ${i??"error"}`,p=new Error(`web_scrape could not retrieve ${e}: fetch failed (${d}) and render failed (${u}).`);throw p.cause=c,p}}if(o!==null)return{title:o.title,markdown:o.markdown,finalUrl:s,usedRender:!1};throw new Error(`web_scrape could not retrieve any content from ${e} (HTTP ${i??"error"}).`)}var w1,S1,v1,k1,Bk=C(()=>{"use strict";mk();Pe();w1=/(text\/html|application\/xhtml\+xml)/i,S1=/(application\/json|\/xml|\+xml|text\/|application\/(java|ecma)script|csv)/i,v1=/(image\/|audio\/|video\/|application\/pdf|application\/zip|application\/octet-stream|font\/)/i,k1={"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 R1(e){let t=e.fetchFn??globalThis.fetch;return{name:"exa",async search(n,{limit:r,signal:o}){let s=await t(x1,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json","x-api-key":e.apiKey,"User-Agent":"agent-afk/web_scrape"},body:JSON.stringify({query:n,type:"auto",numResults:Math.min(Math.max(r,1),T1),contents:{highlights:{numSentences:3,highlightsPerUrl:1}}}),signal:o});if(!s.ok){let l="";try{let u=await s.text(),d=Pc(u);d&&(l=`: ${d.length>200?d.slice(0,200)+"\u2026":d}`)}catch{}let c=s.statusText?` ${s.statusText}`:"";throw new Error(`Exa Search HTTP ${s.status}${c}${l}`)}let i;try{i=await s.json()}catch(l){throw new Error(`Exa Search response was not JSON: ${l instanceof Error?l.message:String(l)}`)}return(i.results??[]).slice(0,r).map(l=>({title:(l.title??"").trim()||"(untitled)",url:l.url??"",description:(l.highlights?.[0]??"").trim()})).filter(l=>l.url.length>0)}}}function jk(e){return e.exaApiKey!==void 0&&e.exaApiKey.trim()!==""?R1({apiKey:e.exaApiKey,fetchFn:e.fetchFn}):{error:'web_scrape search mode requires a search backend. Set EXA_API_KEY (free tier at https://exa.ai) to enable it. Use mode: "markdown" to read a known URL, or mode: "raw" for a direct fetch.'}}function Uk(e,t){if(t.length===0)return`# Search results for "${e}"
1077
1077
 
1078
1078
  (no results)`;let n=[`# Search results for "${e}"`,""];return t.forEach((r,o)=>{n.push(`## ${o+1}. ${r.title}`),r.url&&n.push(r.url),r.description&&n.push(r.description),n.push("")}),n.join(`
1079
1079
  `).trimEnd()}var x1,T1,Hk=C(()=>{"use strict";xs();x1="https://api.exa.ai/search",T1=10});function $1(e){if(!e||typeof e!="object")return{error:"Invalid input: expected an object"};let t=e,n=t.mode??"markdown";if(n!=="markdown"&&n!=="raw"&&n!=="search")return{error:`Invalid input: mode must be one of "markdown", "raw", "search" (got ${JSON.stringify(n)})`};let r=n,o,s;if(r==="search"){if(typeof t.query!="string"||t.query.length===0)return{error:'Invalid input: search mode requires a non-empty "query" string'};s=t.query}else{if(typeof t.url!="string"||t.url.length===0)return{error:`Invalid input: ${r} mode requires a non-empty "url" string`};let l;try{l=new URL(t.url)}catch{return{error:`Invalid input: "${t.url}" is not a valid absolute URL`}}if(l.protocol!=="http:"&&l.protocol!=="https:")return{error:`Invalid input: protocol "${l.protocol}" not supported (http/https only)`};o=l.toString()}let i=A1;if(t.timeout_ms!==void 0){if(typeof t.timeout_ms!="number"||!Number.isFinite(t.timeout_ms)||t.timeout_ms<=0)return{error:"Invalid input: timeout_ms must be a positive finite number"};i=Math.min(t.timeout_ms,C1)}let a=_1;if(t.max_bytes!==void 0){if(typeof t.max_bytes!="number"||!Number.isFinite(t.max_bytes)||t.max_bytes<=0)return{error:"Invalid input: max_bytes must be a positive finite number"};a=Math.min(t.max_bytes,I1)}return{mode:r,url:o,query:s,timeoutMs:i,maxBytes:a}}function ag(e,t){let n=Buffer.from(e,"utf8");return n.byteLength<=t?e:n.subarray(0,t).toString("utf8")+P1}function D1(e){let t=[],n=e;for(let o=0;o<4&&n instanceof Error;o++)t.push(n.message),n=n.cause;let r=t.join(" | ");return O1.some(o=>r.includes(o))}function L1(e={}){let t=e.fetchFn??globalThis.fetch,n=e.env??process.env;return async(r,o)=>{if(typeof t!="function")return{content:"web_scrape unavailable: global fetch() is not present in this runtime (agent-afk requires Node 20+).",isError:!0};let s=$1(r);if("error"in s)return{content:s.error,isError:!0};if(o.aborted){let u=o.reason;return{content:`web_scrape aborted: ${u instanceof Error?u.message:String(u??"aborted")}`,isError:!0}}let i=new AbortController,a=()=>{i.abort(o.reason)},l,c=()=>{let u=i.signal.reason;return u instanceof Error?u.message:String(u??"aborted")};try{if(o.addEventListener("abort",a,{once:!0}),l=setTimeout(()=>{i.abort(new Error(`web_scrape timeout after ${s.timeoutMs}ms`))},s.timeoutMs),s.mode==="raw"){let d;try{d=await t(s.url,{method:"GET",headers:{"User-Agent":"agent-afk/web_scrape",Accept:"*/*"},signal:i.signal})}catch(f){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape network error: ${f instanceof Error?f.message:String(f)}`,isError:!0}}if(!d.ok)return{content:`web_scrape HTTP ${d.status} ${d.statusText||""}`.trimEnd()+` for ${s.url}`,isError:!0};let p;try{p=await d.text()}catch(f){return{content:`web_scrape read error: ${f instanceof Error?f.message:String(f)}`,isError:!0}}return{content:ag(p,s.maxBytes)}}if(s.mode==="markdown")try{let d=await Nk(s.url,{fetchFn:t,renderFn:e.renderFn,timeoutMs:s.timeoutMs,signal:i.signal});return d.markdown.trim().length===0?{content:`web_scrape extracted no readable content from ${s.url}.`,isError:!0}:{content:ag(d.markdown,s.maxBytes)}}catch(d){if(i.signal.aborted)return{content:`web_scrape aborted: ${c()}`,isError:!0};let p=d instanceof Error?d.message:String(d),f=D1(d)?" (the render fallback needs the optional Playwright browser \u2014 run `pnpm exec playwright install chromium`)":"";return{content:`web_scrape markdown error: ${p}${f}`,isError:!0}}let u=jk({exaApiKey:n.EXA_API_KEY,fetchFn:t});if("error"in u)return{content:u.error,isError:!0};try{let d=await u.search(s.query,{limit:M1,timeoutMs:s.timeoutMs,signal:i.signal});return{content:ag(Uk(s.query,d),s.maxBytes)}}catch(d){return i.signal.aborted?{content:`web_scrape aborted: ${c()}`,isError:!0}:{content:`web_scrape search error (${u.name}): ${d instanceof Error?d.message:String(d)}`,isError:!0}}}finally{l!==void 0&&clearTimeout(l),o.removeEventListener("abort",a)}}}var A1,C1,_1,I1,P1,M1,O1,Kk,Wk=C(()=>{"use strict";Bk();Hk();A1=3e4,C1=12e4,_1=1e6,I1=1e7,P1=`
@@ -1596,7 +1596,7 @@ ${n}`;mJ(this.serverName,n);let o=!1;try{let{pushIfConfigured:s}=await Promise.r
1596
1596
  Open this URL to authorize:
1597
1597
  ${n}
1598
1598
  Status written to: ${Xi()}
1599
- `)}_readSlot(){let t=this.backend.read();if(!t)return{};try{return JSON.parse(t).mcpOAuth?.[this.serverName]??{}}catch{return{}}}_updateSlot(t){let n=this.backend.read(),r={};if(n)try{r=JSON.parse(n)}catch{}let o=r.mcpOAuth??{},s=o[this.serverName]??{};o[this.serverName]=t(s),r.mcpOAuth=o,this.backend.write(JSON.stringify(r))}}});W();Jl();import{config as $w}from"dotenv";import{Command as pte}from"commander";G();import Dm from"chalk";function nS(){let e=k.FORCE_COLOR;if(e&&e.length>0)return;let t=k.NO_COLOR;if(t&&t.length>0){Dm.level=0;return}let n=k.CI;if(n&&n.length>0){Dm.level=0;return}process.stdout.isTTY||(Dm.level=0)}import PC from"chalk";import Dq from"ora";Mt();function rS(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("rate limit")||t.toLowerCase().includes("too many requests")}function oS(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("network")||t.toLowerCase().includes("connect")||t.toLowerCase().includes("timeout")}function as(e){if(e instanceof ur)return{kind:"budget_exceeded",userMessage:`Session stopped: cost ceiling reached ($${e.runningCostUsd.toFixed(4)} of $${e.maxBudgetUsd.toFixed(4)} limit).`,exitCode:1,raw:e};if(e instanceof Vl)return{kind:"unsupported_config",userMessage:`The "${e.provider}" provider does not support this configuration option.`,hint:`Option "${e.field}" is not available for provider "${e.provider}". Switch to a compatible provider or remove the option.`,exitCode:1,raw:e};if(e instanceof Ie)return{kind:"hook_blocked",userMessage:`A hook blocked the operation (event: ${e.event}).`,...e.reason!==void 0?{hint:e.reason}:{},exitCode:1,raw:e};if(e instanceof Pt){let s=Math.round(e.timeoutMs/1e3);return{kind:"timeout",userMessage:`The operation timed out after ${s} second${s!==1?"s":""}.`,hint:`Timeout: ${e.timeoutMs}ms (${s}s). Increase the timeout or retry.`,exitCode:124,raw:e}}let t=e,n=e instanceof Error?e.message:String(e),r=n.toLowerCase();return t.status===401||e instanceof Error&&e.name==="AuthenticationError"?{kind:"auth",userMessage:"Authentication failed. Check that your API key is valid and has not expired.",hint:"Verify the ANTHROPIC_API_KEY environment variable or run `afk login`.",exitCode:1,raw:e}:t.status===429||rS(e)?{kind:"rate_limit",userMessage:"Anthropic rate limit reached. The request was rejected (HTTP 429).",hint:"Wait a moment and retry, or reduce the request frequency.",exitCode:1,raw:e}:t.status===529||t.status===503?{kind:"overloaded",userMessage:`Anthropic API is temporarily overloaded (HTTP ${t.status}). All retry attempts were exhausted.`,hint:"Wait a minute and try again, or switch to a less loaded model (e.g. sonnet).",exitCode:1,raw:e}:n==="Not in a git repository."||r.includes("not in a git repository")?{kind:"not_git_repo",userMessage:"This command must be run from inside a git repository.",hint:"Run `git init` to initialise a repository, or change to a directory that is already a git repo.",exitCode:1,raw:e}:oS(e)||r.includes("econnrefused")||r.includes("etimedout")?{kind:"network",userMessage:"Network error: unable to reach the API endpoint.",hint:"Check your internet connection and try again.",exitCode:1,raw:e}:{kind:"unknown",userMessage:(e instanceof Error?e.message:String(e))||"An unexpected error occurred.",exitCode:1,raw:e}}import UL from"string-width";var Lm=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,sS=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function $e(e){return e.replace(Lm,"")}function J(e){return UL(e)}function Yl(e){return e.length===0?[]:sS?Array.from(sS.segment(e),t=>t.segment):Array.from(e)}function HL(e){let t=[],n=0,r;for(Lm.lastIndex=0;(r=Lm.exec(e))!==null;){if(r.index>n)for(let o of Yl(e.slice(n,r.index)))t.push({type:"text",value:o});t.push({type:"ansi",value:r[0]}),n=r.index+r[0].length}if(n<e.length)for(let o of Yl(e.slice(n)))t.push({type:"text",value:o});return t}function Je(e,t){let n=Math.max(0,t-J(e));return e+" ".repeat(n)}function KL(e,t){let n=Math.max(0,t-J(e));return" ".repeat(n)+e}function Fm(e,t,n="left"){let r=Math.max(0,t-J(e));if(r===0)return e;if(n==="right")return KL(e,t);if(n==="center"){let o=Math.floor(r/2);return" ".repeat(o)+e+" ".repeat(r-o)}return Je(e,t)}var WL=/^\x1b\]8;[^;\x07\x1b]*;(.*?)(?:\x07|\x1b\\)$/s,GL="\x1B]8;;\x1B\\";function ie(e,t,n="\u2026"){if(t<=0)return"";if(J(e)<=t)return e;let r=J(n),o=Math.max(0,t-r),s=0,i="",a=!1,l=!1;for(let c of HL(e)){if(c.type==="ansi"){i+=c.value,a=!0;let d=WL.exec(c.value);d&&(l=(d[1]??"").length>0);continue}let u=s+J(c.value);if(u>o)break;i+=c.value,s=u}return i+n+(l?GL:"")+(a?"\x1B[0m":"")}function iS(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function Nm(e,t){let n=iS(t,e.length);if(n===0||e.length===0)return 0;let r=0;for(let o of Yl(e)){let s=r+o.length;if(s>=n)return r;r=s}return r}function Qr(e,t){let n=iS(t,e.length);if(n>=e.length||e.length===0)return e.length;let r=0;for(let o of Yl(e)){let s=r+o.length;if(r>=n||n>r&&n<s)return s;r=s}return e.length}function Q(){let e=process.stdout.columns;return typeof e=="number"&&e>0?e:80}var Xl=new Set,Zl=new Set,ls=!1,eo=null;function zL(){for(let e of Xl)try{e()}catch{}}function qL(){for(let e of Zl)try{e()}catch{}}function JL(){eo!==null&&clearTimeout(eo),eo=setTimeout(()=>{eo=null,zL()},150)}function Bm(){qL(),JL()}function VL(e){return Xl.add(e),ls||(process.stdout.on("resize",Bm),ls=!0),()=>{Xl.delete(e),aS()}}function YL(e){return Zl.add(e),ls||(process.stdout.on("resize",Bm),ls=!0),()=>{Zl.delete(e),aS()}}function aS(){Xl.size===0&&Zl.size===0&&(ls&&(process.stdout.off("resize",Bm),ls=!1),eo!==null&&(clearTimeout(eo),eo=null))}var Le={subscribe:VL,subscribeImmediate:YL};import lS from"wrap-ansi";function de(e,t){if(!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY)return e;let n=Math.floor(t);return lS(e,n,{hard:!1,trim:!1,wordWrap:!0})}function cS(e,t){return!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY?e:lS(e,Math.floor(t),{hard:!0,trim:!1,wordWrap:!1})}import Re from"chalk";var m={brand:Re.hex("#E67E4C"),mint:Re.hex("#5FE3A1"),goblin:Re.hex("#9CB04A"),user:Re.cyan,tool:Re.hex("#DCDCAA"),chrome:Re.hex("#B0B8C2"),syntaxString:Re.italic.hex("#8AB07A"),toolArg:Re.dim.white,thinking:Re.italic.hex("#9B8FB5"),success:Re.green,error:Re.red,warning:Re.yellow,plan:Re.hex("#9F7CE0"),meta:Re.blackBright,info:Re.hex("#5BA8FF"),fileRef:Re.hex("#56B5A8"),heading:Re.bold.white,label:Re.dim,dim:Re.dim,bold:Re.bold,italic:Re.italic,diffAdd:Re.green,diffRemove:Re.red,diffHunk:Re.blackBright};function Ot(){return Math.max(22,Q()-6)}function Zi(e,t){return ie(e,t)}var XL={ok:m.success("\u25CF"),warn:m.warning("\u25CF"),error:m.error("\u25CF"),info:m.info("\u25C6")};function uS(e,t){let o=t.reduce((w,R)=>Math.max(w,J(R.label)),0),s=t.reduce((w,R)=>Math.max(w,J(R.value)),0),i=o+4+2+s,a=Math.min(Q()-4,100),l=Math.max(44,J(e),i,a);l=Math.min(l,Ot());let c=l+4,u=m.dim,d=u("\u256D"+"\u2500".repeat(c)+"\u256E"),p=u("\u251C"+"\u2500".repeat(c)+"\u2524"),f=u("\u2570"+"\u2500".repeat(c)+"\u256F"),g=u("\u2502"),b=de(e,l).split(`
1599
+ `)}_readSlot(){let t=this.backend.read();if(!t)return{};try{return JSON.parse(t).mcpOAuth?.[this.serverName]??{}}catch{return{}}}_updateSlot(t){let n=this.backend.read(),r={};if(n)try{r=JSON.parse(n)}catch{}let o=r.mcpOAuth??{},s=o[this.serverName]??{};o[this.serverName]=t(s),r.mcpOAuth=o,this.backend.write(JSON.stringify(r))}}});W();Jl();import{config as $w}from"dotenv";import{Command as pte}from"commander";G();import Dm from"chalk";function nS(){let e=k.FORCE_COLOR;if(e&&e.length>0)return;let t=k.NO_COLOR;if(t&&t.length>0){Dm.level=0;return}let n=k.CI;if(n&&n.length>0){Dm.level=0;return}process.stdout.isTTY||(Dm.level=0)}import PC from"chalk";import Dq from"ora";Mt();function rS(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("rate limit")||t.toLowerCase().includes("too many requests")}function oS(e){let t=e instanceof Error?e.message:String(e);return t.toLowerCase().includes("network")||t.toLowerCase().includes("connect")||t.toLowerCase().includes("timeout")}function as(e){if(e instanceof ur)return{kind:"budget_exceeded",userMessage:`Session stopped: cost ceiling reached ($${e.runningCostUsd.toFixed(4)} of $${e.maxBudgetUsd.toFixed(4)} limit).`,exitCode:1,raw:e};if(e instanceof Vl)return{kind:"unsupported_config",userMessage:`The "${e.provider}" provider does not support this configuration option.`,hint:`Option "${e.field}" is not available for provider "${e.provider}". Switch to a compatible provider or remove the option.`,exitCode:1,raw:e};if(e instanceof Ie)return{kind:"hook_blocked",userMessage:`A hook blocked the operation (event: ${e.event}).`,...e.reason!==void 0?{hint:e.reason}:{},exitCode:1,raw:e};if(e instanceof Pt){let s=Math.round(e.timeoutMs/1e3);return{kind:"timeout",userMessage:`The operation timed out after ${s} second${s!==1?"s":""}.`,hint:`Timeout: ${e.timeoutMs}ms (${s}s). Increase the timeout or retry.`,exitCode:124,raw:e}}let t=e,n=e instanceof Error?e.message:String(e),r=n.toLowerCase();return t.status===401||e instanceof Error&&e.name==="AuthenticationError"?{kind:"auth",userMessage:"Authentication failed. Check that your API key is valid and has not expired.",hint:"Verify the ANTHROPIC_API_KEY environment variable or run `afk login`.",exitCode:1,raw:e}:t.status===429||rS(e)?{kind:"rate_limit",userMessage:"Anthropic rate limit reached. The request was rejected (HTTP 429).",hint:"Wait a moment and retry, or reduce the request frequency.",exitCode:1,raw:e}:t.status===529||t.status===503?{kind:"overloaded",userMessage:`Anthropic API is temporarily overloaded (HTTP ${t.status}). All retry attempts were exhausted.`,hint:"Wait a minute and try again, or switch to a less loaded model (e.g. sonnet).",exitCode:1,raw:e}:n==="Not in a git repository."||r.includes("not in a git repository")?{kind:"not_git_repo",userMessage:"This command must be run from inside a git repository.",hint:"Run `git init` to initialise a repository, or change to a directory that is already a git repo.",exitCode:1,raw:e}:oS(e)||r.includes("econnrefused")||r.includes("etimedout")?{kind:"network",userMessage:"Network error: unable to reach the API endpoint.",hint:"Check your internet connection and try again.",exitCode:1,raw:e}:{kind:"unknown",userMessage:(e instanceof Error?e.message:String(e))||"An unexpected error occurred.",exitCode:1,raw:e}}import UL from"string-width";var Lm=/\x1B(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1B]*(?:\x07|\x1B\\)|[P^_X][^\x1B]*\x1B\\|[@-OQ-WYZ\\\-])/g,sS=typeof Intl<"u"&&"Segmenter"in Intl?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null;function $e(e){return e.replace(Lm,"")}function J(e){return UL(e)}function Yl(e){return e.length===0?[]:sS?Array.from(sS.segment(e),t=>t.segment):Array.from(e)}function HL(e){let t=[],n=0,r;for(Lm.lastIndex=0;(r=Lm.exec(e))!==null;){if(r.index>n)for(let o of Yl(e.slice(n,r.index)))t.push({type:"text",value:o});t.push({type:"ansi",value:r[0]}),n=r.index+r[0].length}if(n<e.length)for(let o of Yl(e.slice(n)))t.push({type:"text",value:o});return t}function Je(e,t){let n=Math.max(0,t-J(e));return e+" ".repeat(n)}function KL(e,t){let n=Math.max(0,t-J(e));return" ".repeat(n)+e}function Fm(e,t,n="left"){let r=Math.max(0,t-J(e));if(r===0)return e;if(n==="right")return KL(e,t);if(n==="center"){let o=Math.floor(r/2);return" ".repeat(o)+e+" ".repeat(r-o)}return Je(e,t)}var WL=/^\x1b\]8;[^;\x07\x1b]*;(.*?)(?:\x07|\x1b\\)$/s,GL="\x1B]8;;\x1B\\";function ie(e,t,n="\u2026"){if(t<=0)return"";if(J(e)<=t)return e;let r=J(n),o=Math.max(0,t-r),s=0,i="",a=!1,l=!1;for(let c of HL(e)){if(c.type==="ansi"){i+=c.value,a=!0;let d=WL.exec(c.value);d&&(l=(d[1]??"").length>0);continue}let u=s+J(c.value);if(u>o)break;i+=c.value,s=u}return i+n+(l?GL:"")+(a?"\x1B[0m":"")}function iS(e,t){return Number.isFinite(e)?Math.max(0,Math.min(t,Math.trunc(e))):0}function Nm(e,t){let n=iS(t,e.length);if(n===0||e.length===0)return 0;let r=0;for(let o of Yl(e)){let s=r+o.length;if(s>=n)return r;r=s}return r}function Qr(e,t){let n=iS(t,e.length);if(n>=e.length||e.length===0)return e.length;let r=0;for(let o of Yl(e)){let s=r+o.length;if(r>=n||n>r&&n<s)return s;r=s}return e.length}function Q(){let e=process.stdout.columns;return typeof e=="number"&&e>0?e:80}var Xl=new Set,Zl=new Set,ls=!1,eo=null;function zL(){for(let e of Xl)try{e()}catch{}}function qL(){for(let e of Zl)try{e()}catch{}}function JL(){eo!==null&&clearTimeout(eo),eo=setTimeout(()=>{eo=null,zL()},150)}function Bm(){qL(),JL()}function VL(e){return Xl.add(e),ls||(process.stdout.on("resize",Bm),ls=!0),()=>{Xl.delete(e),aS()}}function YL(e){return Zl.add(e),ls||(process.stdout.on("resize",Bm),ls=!0),()=>{Zl.delete(e),aS()}}function aS(){Xl.size===0&&Zl.size===0&&(ls&&(process.stdout.off("resize",Bm),ls=!1),eo!==null&&(clearTimeout(eo),eo=null))}var Le={subscribe:VL,subscribeImmediate:YL};import lS from"wrap-ansi";function de(e,t){if(!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY)return e;let n=Math.floor(t);return lS(e,n,{hard:!1,trim:!1,wordWrap:!0})}function cS(e,t){return!Number.isFinite(t)||t<=0||t===Number.POSITIVE_INFINITY?e:lS(e,Math.floor(t),{hard:!0,trim:!1,wordWrap:!1})}import Te from"chalk";var m={brand:Te.hex("#E67E4C"),mint:Te.hex("#5FE3A1"),goblin:Te.hex("#9CB04A"),user:Te.cyan,tool:Te.hex("#DCDCAA"),chrome:Te.hex("#B0B8C2"),syntaxString:Te.italic.hex("#8AB07A"),toolArg:Te.dim.white,thinking:Te.italic.hex("#9B8FB5"),success:Te.green,error:Te.red,warning:Te.yellow,plan:Te.hex("#9F7CE0"),bypass:Te.bold.hex("#FF6AC1"),meta:Te.blackBright,info:Te.hex("#5BA8FF"),fileRef:Te.hex("#56B5A8"),heading:Te.bold.white,label:Te.dim,dim:Te.dim,bold:Te.bold,italic:Te.italic,diffAdd:Te.green,diffRemove:Te.red,diffHunk:Te.blackBright};function Ot(){return Math.max(22,Q()-6)}function Zi(e,t){return ie(e,t)}var XL={ok:m.success("\u25CF"),warn:m.warning("\u25CF"),error:m.error("\u25CF"),info:m.info("\u25C6")};function uS(e,t){let o=t.reduce((w,R)=>Math.max(w,J(R.label)),0),s=t.reduce((w,R)=>Math.max(w,J(R.value)),0),i=o+4+2+s,a=Math.min(Q()-4,100),l=Math.max(44,J(e),i,a);l=Math.min(l,Ot());let c=l+4,u=m.dim,d=u("\u256D"+"\u2500".repeat(c)+"\u256E"),p=u("\u251C"+"\u2500".repeat(c)+"\u2524"),f=u("\u2570"+"\u2500".repeat(c)+"\u256F"),g=u("\u2502"),b=de(e,l).split(`
1600
1600
  `).map(w=>g+" "+Je(w,l)+" "+g),y=Math.max(1,l-o-4-2),S=t.map(w=>{let R=w.kind?XL[w.kind]+" ":" ",x=m.dim(Je(Zi(w.label,o),o)),A=" ".repeat(4),T=Zi(w.value,y),v=Je(T,y),_=x+A+R+v;return g+" "+_+" "+g});return[d,...b,p,...S,f].join(`
1601
1601
  `)}import{sep as Hm}from"node:path";G();G();import jm from"chalk";var dS={".":null,D:[74,92,36],M:[139,166,63],L:[178,197,88],Y:[245,213,71],K:[13,18,9],W:[238,238,222],X:[42,42,26]},Ql=[".......KKKKK.......","......WKKLKKW......",".....KKWMLMWKK.....","..DDKKWLMMMLWKKDD..","DDD..KMMMMMMMK..DDD","..DDKMMMMMMMMMKDD..","...KKMMKKKKKMMKK...","...KMMKKKKKKKMMK...","...KMMMYMDMYMMMK...","...KMMMMMMMMMMMK...","...KKMMXXXXXMMKK...","....KKMMWXXMMKK....",".....KKMWMMMKK.....",".....KKMMMMMKK.....","......KKMMMKK......",".......KKKKK......."],Um=19,Qi=8;function ZL(e,t){if(e.length!==t.length)throw new Error(`pixel row width mismatch: top=${e.length}, bot=${t.length}`);let n="";for(let r=0;r<e.length;r++){let o=dS[e[r]??"."]??null,s=dS[t[r]??"."]??null;!o&&!s?n+=" ":o&&!s?n+=jm.rgb(o[0],o[1],o[2])("\u2580"):!o&&s?n+=jm.rgb(s[0],s[1],s[2])("\u2584"):o&&s&&(n+=jm.bgRgb(s[0],s[1],s[2]).rgb(o[0],o[1],o[2])("\u2580"))}return n}function QL(){if(Ql.length!==Qi*2)throw new Error(`GOBLIN_GRID has ${Ql.length} pixel rows but MASCOT_HEIGHT*2 = ${Qi*2}`);let e=[];for(let t=0;t<Qi;t++){let n=Ql[t*2]??"",r=Ql[t*2+1]??"";e.push(ZL(n,r))}return e}function pS(e="idle"){return k.AFK_BANNER_PLAIN==="1"?[]:QL()}function mS(){return k.AFK_BANNER_PLAIN==="1"}function gS(e){let t=e.model!==void 0||e.worktree!==void 0||e.cwd!==void 0||e.version!==void 0;return t&&!mS()?tF(e):fS(t?eF(e):e)}function eF(e){let t=e.mode;e.model!==void 0&&e.model.length>0&&(t=`${e.model} \xB7 ${t}`),e.version!==void 0&&e.version.length>0&&(t=`${t} \xB7 ${hS(e.version)}`);let n=[];e.worktree!==void 0&&e.worktree.length>0&&n.push(`branch ${e.worktree}`),e.cwd!==void 0&&e.cwd.length>0&&n.push(yS(e.cwd));let r=n.join(" \xB7 "),o=e.metaLine!==void 0?e.metaLine:r.length>0?r:void 0,s={mode:t};return o!==void 0&&(s.metaLine=o),e.hintLine!==void 0&&(s.hintLine=e.hintLine),s}function fS(e){let t="Agent AFK",n=" \xB7 ",r=m.bold(t)+m.dim(n)+e.mode,o=t+n+e.mode,s=Math.min(Q()-4,120),i=Math.max(54,J(o)+4,s);i=Math.min(i,Ot());let a=i+4,l=m.dim,c=l("\u256D"+"\u2500".repeat(a)+"\u256E"),d=de(r,i).split(`
1602
1602
  `).map(g=>l("\u2502")+" "+Je(g,i)+" "+l("\u2502")),p=l("\u2570"+"\u2500".repeat(a)+"\u256F"),f=[c,...d,p];return e.metaLine!==void 0&&f.push(...de(m.dim(" "+e.metaLine),Q()).split(`
@@ -1754,12 +1754,12 @@ Run \`afk i\` then \`/resume\` to list saved sessions.
1754
1754
  `)+`
1755
1755
  `);let c=l.length;function u(){let d=a();process.stdout.write(`\x1B[${c}A\x1B[0J`+d.join(`
1756
1756
  `)+`
1757
- `),c=d.length}return new Promise(d=>{process.stdin.setRawMode(!0),xo(process.stdin);let p=(g,h)=>{if(h)if(h.name==="up"||h.sequence==="\x1B[A")r>0&&(r--,r<o&&(o=r),u());else if(h.name==="down"||h.sequence==="\x1B[B"){if(r<e.length-1){r++;let{end:b}=i();r>=b&&o++,u()}}else h.name==="space"?(s.has(r)?s.delete(r):s.add(r),u()):h.name==="return"||h.name==="enter"?(f(),d([...s].sort((b,y)=>b-y))):(h.name==="escape"||h.ctrl&&h.name==="c")&&(f(),d(":cancel"))};function f(){process.stdin.removeListener("keypress",p);try{process.stdin.setRawMode(!1)}catch{}}process.stdin.on("keypress",p)})}function jC(e=process.env){return e.AFK_DEMO_CLEAN==="1"||typeof e.SCRIPT=="string"&&e.SCRIPT.length>0||e.ASCIINEMA_REC==="1"}function Kq(e=process.env){return e.AFK_BELL==="1"}function UC(e=process.env){return e.AFK_REDUCED_MOTION==="1"}function hd(e,t=process.env){Kq(t)&&e.isTTY&&e.write("\x07")}var Vh=64,bd=256,yd=20,Yh=new Set(["__proto__","constructor","prototype"]),mi={action:"decline"},ne={action:"cancel"},Wq={action:"accept"};function Gq(e){let t=e.properties,n={},r=0,o=!1;if(typeof t=="object"&&t!==null){let a=0;for(let[l,c]of Object.entries(t))if(!Yh.has(l)){if(r+=1,a>=Vh){o=!0;continue}n[l]=c,a+=1}}let s=e.required,i=new Set(Array.isArray(s)?s.slice(0,Vh*2).filter(a=>typeof a=="string").filter(a=>!Yh.has(a)):[]);return{properties:n,required:i,fieldsTruncated:o,originalFieldCount:r}}function zq(e,t){e.line(),e.line(m.warning("\u26A0 MCP form elicitation")),e.line(m.dim(" server: ")+m.bold(pe(t.serverName,64))),e.line(m.dim(" message: ")+pe(t.message,256)),t.elicitationId&&e.line(m.dim(" id: ")+pe(t.elicitationId,64)),e.line(m.dim(" Type :decline or :cancel at any prompt to exit.")),e.line()}var HC="\u2014 skip (optional) \u2014";async function qq(e,t,n,r,o,s,i){let a,l;if(e.enum!==void 0){let f=e.enum.slice(0,bd);a=f.map(g=>pe(String(g),64)),l=g=>{let h=a.indexOf(g);return h>=0?f[h]:g}}else a=["Yes","No"],l=f=>f==="Yes";let c=t?a:[...a,HC],u=[m.bold(" ? "+n),""],d;try{d=await o({header:u,options:c,multi:!1,signal:i})}catch{return{tag:"cancel"}}if(i.aborted)return{tag:"cancel"};if(d===null)return{tag:"cancel"};let p=d[0];return p===void 0?{tag:"cancel"}:!t&&p===HC?{tag:"value",value:e.default}:(s.line(m.dim(" \u2713 ")+m.brand(`${r}: ${pe(p,128)}`)),{tag:"value",value:l(p)})}async function Jq(e,t,n,r,o,s,i){if(s.aborted)return{tag:"cancel"};let a=pe(t.description??t.title??e),l=pe(t.type??"string",32),c=pe(e,64);if(i&&(t.enum!==void 0||l==="boolean"))return qq(t,n,a,c,i,o,s);let u;if(t.enum!==void 0){let p=t.enum.slice(0,yd).map(g=>pe(String(g),32)).join("|"),f=t.enum.length>yd?"|\u2026":"";u=` (enum: ${p}${f})`}else l==="boolean"?u=" (boolean: y/n)":l==="number"||l==="integer"?u=` (${l})`:l==="string"?u=" (string)":(u=` (${l} \u2014 treated as string)`,o.line(m.warning(` \u26A0 Unknown field type '${l}' for '${c}' \u2014 collecting as string.`)));let d=n?"":m.dim(" [optional, enter to skip]");for(o.line(m.dim(` [${c}]`)+m.dim(` ${a}`)+m.dim(u)+d),t.enum!==void 0&&t.enum.length>bd&&o.line(m.warning(` \u26A0 Field '${c}' has ${t.enum.length} enum values; only the first ${bd} are valid for input.`));;){let p;try{p=await r(m.dim(" > "))}catch{return{tag:"cancel"}}if(s.aborted)return{tag:"cancel"};let f=p.trim();if(f===":cancel")return{tag:"cancel"};if(f===":decline")return{tag:"decline"};if(f===""){if(n){o.line(m.warning(" (required \u2014 cannot be skipped)"));continue}return{tag:"value",value:t.default}}let g;if(l==="boolean"){let h=f.toLowerCase();if(h==="y"||h==="yes"||h==="true"||h==="1")g=!0;else if(h==="n"||h==="no"||h==="false"||h==="0")g=!1;else{o.line(m.warning(" Invalid boolean \u2014 enter y/yes/true/1 or n/no/false/0."));continue}}else if(l==="number"){let h=Number(f);if(!isFinite(h)){o.line(m.warning(" Invalid number \u2014 enter a numeric value."));continue}g=h}else if(l==="integer"){let h=parseInt(f,10);if(!isFinite(h)||String(h)!==f.replace(/\.0+$/,"")){o.line(m.warning(" Invalid integer \u2014 enter a whole number."));continue}g=h}else g=f;if(t.enum!==void 0){let h=t.enum.slice(0,bd),b=!1;for(let y of h)if(String(y)===String(g)){b=!0;break}if(!b){let y=pe(String(g),64),S=h.slice(0,yd).map(R=>pe(String(R),32)).join(", "),w=h.length>yd?", \u2026":"";o.line(m.warning(` '${y}' is not a valid choice. Valid: ${S}${w}`));continue}}return{tag:"value",value:g}}}function Vq(e,t){e.line(),e.line(m.warning("\u26A0 MCP elicitation")),e.line(m.dim(" server: ")+m.bold(pe(t.serverName,64))),e.line(m.dim(" message: ")+pe(t.message,256)),t.url&&e.line(m.dim(" url: ")+m.brand(pe(t.url,512))),t.elicitationId&&e.line(m.dim(" id: ")+pe(t.elicitationId,64)),e.line()}var Ro={action:"skip"};function wd(e){let t=[];return t.push(m.warning(" \u{1F4AC} Agent question")),t.push(m.bold(" ? "+pe(e.message,512))),e.context&&t.push(m.dim(" "+pe(e.context,512))),t.push(""),t}async function Yq(e,t,n,r){let o=wd(t),s=t.allowSkip===!0;if(e==="number"){let u=t.min,d=t.max,f=`enter to submit \xB7 esc to cancel${u!==void 0&&d!==void 0?` [${u}\u2013${d}]`:u!==void 0?` [\u2265${u}]`:d!==void 0?` [\u2264${d}]`:""}`,h=await n({header:o,help:f,validate:y=>{let S=y.trim();if(S==="")return s?null:"Please enter a number (or esc to cancel).";let w=Number(S);return Number.isFinite(w)?u!==void 0&&w<u?`Value must be \u2265 ${u}.`:d!==void 0&&w>d?`Value must be \u2264 ${d}.`:null:"Please enter a valid number."},signal:r});if(h===null)return null;let b=h.trim();return b===""&&s?{tag:"skip"}:{tag:"number",value:Number(b)}}let i=t.minLength,a=t.maxLength,c=await n({header:o,validate:u=>u===""?s?null:"Please enter a response (or esc to cancel).":i!==void 0&&u.length<i?`Response must be at least ${i} characters.`:a!==void 0&&u.length>a?`Response must be at most ${a} characters.`:null,signal:r});return c===null?null:c===""&&s?{tag:"skip"}:{tag:"text",value:c}}async function Xq(e,t,n){if(n.aborted)return mi;let{readLine:r,writer:o,pendingCount:s,pickFromList:i,readTextOverlay:a}=t,l=e.type??"text",c=s();if(c>1&&o.line(m.dim(` [${c} questions queued]`)),(l==="choice"||l==="multi_choice")&&i&&(e.choices?.length??0)>0){let p=(e.choices??[]).map(h=>pe(h,128));e.allowCustom&&p.push(To);let f;try{f=await i({header:wd(e),options:p,multi:l==="multi_choice",signal:n})}catch{return ne}if(n.aborted||f===null)return ne;if(e.allowCustom&&f.includes(To)){if(!a)return ne;let h=await a({header:wd(e),help:"Type your custom answer (Esc to cancel)",validate:b=>b.trim()===""?"Please enter a non-empty answer":null,signal:n});return h===null?ne:(o.line(m.dim(" \u270E ")+m.brand(pe(h,256))),{action:"accept",content:{value:null,custom_value:h}})}if(f.length===0)return e.allowSkip?Ro:ne;let g=f.length===1?pe(f[0]??"",128):f.map(h=>pe(h,128)).join(", ");return o.line(m.dim(" \u2713 ")+m.brand(g)),l==="choice"?{action:"accept",content:{value:f[0]}}:{action:"accept",content:{value:[...f]}}}if(l==="confirm"&&i){let f=e.questionDefault!==!1?["Yes","No"]:["No","Yes"],g;try{g=await i({header:wd(e),options:f,multi:!1,signal:n})}catch{return ne}if(n.aborted||g===null)return ne;let h=g[0];if(h===void 0)return ne;let b=h==="Yes";return o.line(m.dim(" \u2713 ")+(b?m.success("Yes"):m.error("No"))),{action:"accept",content:{value:b}}}if((l==="text"||l==="number")&&a){let p=await Yq(l,e,a,n);if(p===null)return ne;if(p.tag==="skip")return Ro;let f=p.tag==="text"?pe(p.value,256):String(p.value);return o.line(m.dim(" \u2713 ")+m.brand(f)),{action:"accept",content:{value:(p.tag==="text",p.value)}}}if(o.line(),o.line(m.warning("\u{1F4AC} Agent question")),e.context&&o.line(m.dim(" context: ")+pe(e.context,512)),o.line(m.bold(" "+pe(e.message,512))),o.line(m.dim(" Type :cancel to skip this question.")),o.line(),l==="confirm"){o.line("\x07");let p=e.questionDefault===!0?"Y/n":"y/N";for(;;){if(n.aborted)return ne;let f;try{f=(await r(m.dim(` Continue? [${p}] `))).trim().toLowerCase()}catch{return ne}if(n.aborted||f===":cancel")return ne;if(f==="")return{action:"accept",content:{value:e.questionDefault===!0}};if(f==="y"||f==="yes")return{action:"accept",content:{value:!0}};if(f==="n"||f==="no")return{action:"accept",content:{value:!1}};o.line(m.warning(" Please enter y or n."))}}if(l==="choice"){o.line("\x07");let p=e.choices??[],f=e.allowCustom?[...p,To]:p,g=await NC(f,n);if(g!==null){if(g===":cancel")return ne;if(e.allowCustom&&g===p.length){let b;try{b=(await r(m.dim(" Type your answer: "))).trim()}catch{return ne}return b===":cancel"||n.aborted?ne:{action:"accept",content:{value:null,custom_value:b}}}let h=p[g];return h!==void 0?(o.line(m.dim(` Selected: ${pe(h,128)}`)),{action:"accept",content:{value:h}}):ne}for(p.forEach((h,b)=>{o.line(` ${b+1}. ${pe(h,128)}`)}),e.allowCustom&&o.line(` ${p.length+1}. ${To}`);;){if(n.aborted)return ne;let h;try{h=(await r(m.dim(" Enter number: "))).trim()}catch{return ne}if(n.aborted||h===":cancel")return ne;if(e.allowCustom&&h===String(p.length+1)){let y;try{y=(await r(m.dim(" Type your answer: "))).trim()}catch{return ne}return y===":cancel"?ne:{action:"accept",content:{value:null,custom_value:y}}}if(h===""&&e.allowSkip)return Ro;let b=parseInt(h,10);if(!isFinite(b)||String(b)!==h||b<1||b>p.length){o.line(m.warning(` Please enter a number between 1 and ${p.length+(e.allowCustom?1:0)}.`));continue}return{action:"accept",content:{value:p[b-1]}}}}if(l==="multi_choice"){let p=e.choices??[],f=e.allowCustom?[...p,To]:p,g=await BC(f,n);if(g!==null){if(g===":cancel")return ne;if(e.allowCustom&&g.includes(p.length)){let h;try{h=(await r(m.dim(" Type your answer: "))).trim()}catch{return ne}return h===":cancel"||n.aborted?ne:{action:"accept",content:{value:null,custom_value:h}}}if(g.length===0&&e.allowSkip)return Ro;if(g.length>0){let h=g.map(b=>p[b]);return o.line(m.dim(` Selected: ${h.map(b=>pe(b,64)).join(", ")}`)),{action:"accept",content:{value:h}}}}for(p.forEach((h,b)=>{o.line(` ${b+1}. ${pe(h,128)}`)}),e.allowCustom&&o.line(` ${p.length+1}. ${To}`);;){if(n.aborted)return ne;let h;try{h=(await r(m.dim(" Enter numbers (comma-separated): "))).trim()}catch{return ne}if(n.aborted||h===":cancel")return ne;if(e.allowCustom&&h===String(p.length+1)){let w;try{w=(await r(m.dim(" Type your answer: "))).trim()}catch{return ne}return w===":cancel"?ne:{action:"accept",content:{value:null,custom_value:w}}}if(h===""&&e.allowSkip)return Ro;if(h===""){o.line(m.warning(" Please enter at least one selection."));continue}let b=h.split(",").map(w=>w.trim()),y=[],S=!0;for(let w of b){let R=parseInt(w,10);if(!isFinite(R)||String(R)!==w||R<1||R>p.length){o.line(m.warning(` Invalid selection "${pe(w,32)}". Enter numbers between 1 and ${p.length}.`)),S=!1;break}y.push(p[R-1])}if(S)return{action:"accept",content:{value:y}}}}if(l==="number"){let p=e.min,f=e.max,g=p!==void 0&&f!==void 0?` [${p}\u2013${f}]`:p!==void 0?` [\u2265${p}]`:f!==void 0?` [\u2264${f}]`:"";for(;;){if(n.aborted)return ne;let h;try{h=(await r(m.dim(` Enter a number${g}: `))).trim()}catch{return ne}if(n.aborted||h===":cancel")return ne;if(h===""&&e.allowSkip)return Ro;if(h===""&&!e.allowSkip){o.line(m.warning(" Please enter a number (or :cancel to skip)."));continue}let b=Number(h);if(!isFinite(b)){o.line(m.warning(" Please enter a valid number."));continue}if(p!==void 0&&b<p){o.line(m.warning(` Value must be \u2265 ${p}.`));continue}if(f!==void 0&&b>f){o.line(m.warning(` Value must be \u2264 ${f}.`));continue}return{action:"accept",content:{value:b}}}}let u=e.minLength,d=e.maxLength;for(;;){if(n.aborted)return ne;let p;try{p=(await r(m.dim(" > "))).trim()}catch{return ne}if(n.aborted||p===":cancel")return ne;if(p===""&&e.allowSkip)return Ro;if(p===""){o.line(m.warning(" Please enter a response (or type :cancel to skip)."));continue}if(u!==void 0&&p.length<u){o.line(m.warning(` Response must be at least ${u} characters.`));continue}if(d!==void 0&&p.length>d){o.line(m.warning(` Response must be at most ${d} characters.`));continue}return{action:"accept",content:{value:p}}}}function Sd(e){return async(t,{signal:n})=>{if(n.aborted)return mi;hd(process.stdout),e.suspendInput?.();try{if(t.origin==="agent")return await Xq(t,e,n);if(t.mode==="form"){let o=t.requestedSchema,{properties:s,required:i,fieldsTruncated:a,originalFieldCount:l}=typeof o=="object"&&o!==null?Gq(o):{properties:{},required:new Set,fieldsTruncated:!1,originalFieldCount:0};zq(e.writer,t),a&&e.writer.line(m.warning(` \u26A0 Schema has ${l} fields; only the first ${Vh} will be prompted (server may be malformed or compromised).`));let c=Object.create(null);if(Object.keys(s).length===0)return e.writer.line(m.warning(" \u26A0 Form schema has no usable fields \u2014 declining.")),mi;for(let u of i)if(!(u in s))return e.writer.line(m.warning(` \u26A0 Required field '${pe(u,64)}' has no schema entry \u2014 declining.`)),mi;for(let[u,d]of Object.entries(s)){if(n.aborted)return ne;let p=await Jq(u,d,i.has(u),e.readLine,e.writer,n,e.pickFromList);if(p.tag==="cancel")return ne;if(p.tag==="decline")return mi;p.value!==void 0&&!Yh.has(u)&&(c[u]=p.value)}return{action:"accept",content:{...c}}}Vq(e.writer,t);let r=(await e.readLine(m.dim("Continue? [y/N] "))).trim().toLowerCase();return r===""?ne:r==="y"||r==="yes"?Wq:mi}finally{e.resumeInput?.()}}}Gs();qt();Qt();He();Nt();function KC(e){let t=Math.max(0,Math.min(1,e.ratio)),n=t>.8?m.error:t>.5?m.warning:m.meta,r=20,o=Math.round(t*r),s=r-o,i="["+"\u2588".repeat(o)+"\u2591".repeat(s)+"]",a=Math.round(t*100)+"%",l="";e.used!==void 0&&e.limit!==void 0&&(l=ae(e.used)+"/"+ae(e.limit));let c=l?`${i} ${a} ${l}`:`${i} ${a}`,u=`${i} ${a}`,d=`ctx ${a}`,p=e.sparkline?m.meta(e.sparkline)+" ":"",f=e.sparkline?J(e.sparkline)+1:0,g=Math.max(0,e.width-f);if(J(c)<=g&&g>90)return p+n(c);if(J(u)<=g&&g>32)return p+n(u);if(J(d)<=g)return p+n(d);if(e.width>0){let h=p+n(d);return ie(h,e.width)}return n(a)}var vd=class{stream;force;throttleMs;started=!1;lastRepaint=0;lastFields=null;resizeUnsub=null;resizeImmediateUnsub=null;lastPaintedRow=null;preResizePaintedRow=null;extraRows=0;afterScrollRestore=null;constructor(t={}){this.stream=t.stream??process.stdout,this.force=t.force??!1,this.throttleMs=t.throttleMs??100}get enabled(){return this.force||!!this.stream.isTTY}start(){if(this.started||!this.enabled)return;this.started=!0,this.lastRepaint=0;let t=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.resizeUnsub===null&&(this.resizeUnsub=Le.subscribe(()=>{this.onResize()}),this.resizeImmediateUnsub=Le.subscribeImmediate(()=>this.resetGeometry()))}resetGeometry(){this.preResizePaintedRow=this.lastPaintedRow,this.lastPaintedRow=null,this.lastRepaint=0}onResize(){if(!this.started||!this.enabled)return;let t=this.currentRows(),n=this.preResizePaintedRow??this.lastPaintedRow;this.preResizePaintedRow=null,this.stream.write("\x1B[s"),n!==null&&n!==this.paintRow(t)&&(this.stream.write(`\x1B[${n};1H`),this.stream.write("\x1B[2K")),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.flush()}repaint(t){if(!this.enabled||!this.started){this.lastFields=t;return}let n=Date.now();if(n-this.lastRepaint<this.throttleMs){this.lastFields=t;return}this.lastRepaint=n,this.lastFields=t;let r=this.currentRows();this.stream.write("\x1B[s"),this.stream.write(`\x1B[${this.paintRow(r)};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatLine(t)),this.stream.write("\x1B[u"),this.lastPaintedRow=this.paintRow(r)}flush(){this.lastRepaint=0,this.lastFields&&this.repaint(this.lastFields)}setExtraRows(t){if(this.extraRows=t,this.started&&this.enabled){let n=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(n),this.stream.write("\x1B[u"),this.flush()}}getExtraRows(){return this.extraRows}setAfterScrollRestore(t){this.afterScrollRestore=t}rearm(){if(!this.started||!this.enabled)return;let t=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.flush()}withFullScrollRegion(t){if(!this.started||!this.enabled)return t();this.stream.write("\x1B[s"),this.stream.write("\x1B[r"),this.stream.write("\x1B[u");try{return t()}finally{let n=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(n),this.stream.write("\x1B[u"),this.flush(),this.afterScrollRestore?.()}}stop(){if(this.resizeUnsub!==null&&(this.resizeUnsub(),this.resizeUnsub=null),this.resizeImmediateUnsub!==null&&(this.resizeImmediateUnsub(),this.resizeImmediateUnsub=null),!this.started||!this.enabled){this.started=!1;return}let t=this.currentRows();this.stream.write("\x1B[s");let n=this.preResizePaintedRow??this.lastPaintedRow??this.paintRow(t);this.stream.write(`\x1B[${n};1H`),this.stream.write("\x1B[2K"),this.stream.write("\x1B[r"),this.stream.write("\x1B[u"),this.started=!1,this.lastRepaint=0,this.lastPaintedRow=null,this.preResizePaintedRow=null}formatLine(t){let n=[],r=Math.max(4,(this.stream.columns??80)-2);if(t.cwd){let a=Math.max(8,Math.floor(r*.4)),l=Wa(t.cwd,{maxWidth:a});l&&n.push({text:m.dim(l)})}if(n.push({text:m.brand(t.model)}),t.permissionMode==="plan"?n.push({text:m.warning("\u25CF plan")}):t.permissionMode==="autonomous"?n.push({text:m.info("\u25D0 AFK")}):t.permissionMode==="bypassPermissions"&&n.push({text:m.warning("\u26A0 BYPASS")}),t.contextPct!==void 0){let a=KC({ratio:t.contextPct,used:t.contextUsedTokens,limit:t.contextLimit,sparkline:t.contextSparkline,width:r});n.push({text:a,droppablePriority:1})}t.cost!==void 0&&n.push({text:m.meta(`$${t.cost.toFixed(2)}`),droppablePriority:2}),t.tokens!==void 0&&n.push({text:m.meta(`${Zq(t.tokens)} tok`),droppablePriority:3});let o=m.dim(" \xB7 "),s=n.map(a=>a.text).join(o);if(J(s)<=r)return s;let i=n.filter(a=>a.droppablePriority!==void 0);for(;i.length>0&&J(s)>r;){let a=Math.max(...i.map(l=>l.droppablePriority));n=n.filter(l=>l.droppablePriority===void 0||l.droppablePriority!==a),s=n.map(l=>l.text).join(o),i=n.filter(l=>l.droppablePriority!==void 0)}return ie(s,r)}currentRows(){let t=this.stream.rows;return typeof t=="number"&&t>0?t:24}paintRow(t){return t>1?t:1}writeScrollRegion(t){let n=1+this.extraRows;if(t>n){this.stream.write(`\x1B[1;${t-n}r`);return}this.stream.write("\x1B[r")}};function Zq(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}var Rt=new Map,Ao=new Map;function fe(e){if(Rt.has(e.name))throw new Error(`Slash command already registered: ${e.name}`);Rt.set(e.name,e);for(let t of e.aliases??[]){if(Ao.has(t)||Rt.has(t))throw new Error(`Slash alias collides: ${t}`);Ao.set(t,e.name)}}function Dr(e){if(Rt.has(e.name)){for(let[t,n]of Ao.entries())n===e.name&&Ao.delete(t);Rt.delete(e.name)}fe(e)}function WC(e){Rt.has(e.name)||fe(e)}function GC(){Rt.clear(),Ao.clear()}function Ze(){return[...Rt.values()].sort((e,t)=>e.name.localeCompare(t.name))}function fi(){let e=[];for(let[t,n]of Ao.entries()){let r=Rt.get(n);r&&e.push({alias:t,canonical:n,summary:r.summary})}return e.sort((t,n)=>t.alias.localeCompare(n.alias))}function Qq(e){if(Rt.has(e))return Rt.get(e);let t=Ao.get(e);return t?Rt.get(t):void 0}function eJ(e,t){let n=Array.from({length:e.length+1},()=>new Array(t.length+1).fill(0));for(let r=0;r<=e.length;r++)n[r][0]=r;for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let o=1;o<=t.length;o++){let s=e[r-1]===t[o-1]?0:1;n[r][o]=Math.min(n[r-1][o]+1,n[r][o-1]+1,n[r-1][o-1]+s)}return n[e.length][t.length]}function tJ(e,t=3){let n;for(let r of Rt.keys()){let o=eJ(e,r);o<=t&&(n===void 0||o<n.dist)&&(n={name:r,dist:o})}return n?.name}function Xh(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.indexOf(" ");return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}async function zC(e,t,n){let r=Xh(e);if(r===null)return{handled:!1};let o=Qq(r.name);if(!o){let a=tJ(r.name);return a?t.out.warn(`Unknown command: ${r.name} (did you mean ${a}?)`):t.out.warn(`Unknown command: ${r.name} (type /help for commands)`),{handled:!0,result:"continue"}}let s=n??[];s.length>0&&o.acceptsAttachments!==!0&&t.out.warn(`\u26A0 Image attachments are ignored by ${r.name} (images only reach the model on skill commands like /forge, /mint).`);let i=await o.handler(t,r.args,o.acceptsAttachments===!0?s:void 0);return i==="forward"?{handled:!1}:{handled:!0,result:i}}import sJ from"ora";wa();function qC(e,t=5){if(e.length===0)return"";let n=e.slice(-t),r=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];return n.map(o=>{let s=Math.max(0,Math.min(1,o)),i=Math.min(7,Math.floor(s*8));return r[i]}).join("")}function kd(e,t,n){e.totalTurns=t.totalTurns,e.totalCostUsd=t.totalCostUsd,e.totalTokens=t.totalTokens,e.totalDurationMs=t.totalDurationMs,e.turns=[...t.turns],e.sessionId=t.sessionId??n,e.name=t.name,e.model=t.model,e.sessionStartTime=t.startedAt??Date.now()}function Ed(e,t){let n=e.turns;if(n.length===0)return;let r=n[n.length-1];if(!r)return;let o=VC(JC(r.user),80),s=VC(oJ(JC(r.assistant)),120);o.length>0&&t.fn(m.dim(` Last: ${o}`)),s.length>0&&t.fn(m.dim(` \u21B3 ${s}`)),t.fn(m.dim(" \u21AA /history for full review"))}function JC(e){return e.replace(rJ,"").replace(/\s+/g," ").trim()}var rJ=/\u001B\][\s\S]*?(?:\u0007|\u001B\\|\u009C)|\u001B[PX^_][\s\S]*?(?:\u0007|\u001B\\|\u009C)|\u001B[@-OQ-WY-Z\\`6-9=]|[\u001B\u009B][[\]()#;?]*(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]/g;function oJ(e){let t=e.match(/^.*?(?<![A-Za-z]\.[A-Za-z])[.!?](?=\s|$)/);return t?t[0]:e}function VC(e,t){let n=[...e];return n.length<=t?e:n.slice(0,t-1).join("")+"\u2026"}var Ga={stream:process.stdout,hideCursor:!1,discardStdin:!1};function Zh(e,t){if(t?.getRatio()!==void 0)return t.getRatio();let n=e.turnTokens[e.turnTokens.length-1];return n?(n.footprint??n.input+n.output+n.cache)/kt(e.model):0}function tr(e,t){let n=Zh(e,t),r=kt(e.model),o,s=t?.getDetail();if(s!==void 0)o=s.used;else{let a=e.turnTokens[e.turnTokens.length-1];a&&(o=a.footprint??a.input+a.output+a.cache)}let i;if(e.turnTokens.length>=2){let a=e.turnTokens.map(c=>(c.footprint??c.input+c.output+c.cache)/r),l=qC(a,5);l.length>0&&(i=l)}return{model:e.model,cost:e.totalCostUsd,tokens:e.totalTokens,contextPct:n,contextLimit:r,contextUsedTokens:o,contextSparkline:i,permissionMode:e.permissionMode,...e.cwd!==void 0?{cwd:e.cwd}:{}}}var iJ={name:"/exit",aliases:["/quit"],summary:"Exit the session",hint:"When you want to tear down the REPL \u2014 Ctrl+D on an empty prompt does the same.",async handler(){return"exit"}},aJ={name:"/clear",summary:"Clear conversation history",hint:"When the current thread has drifted off-topic or you want a clean slate without restarting the session.",async handler(e){try{await e.session.current.reset(),e.ui.clearScreen(),vC(e.stats),e.ledger?.clear(),e.out.success("Conversation history cleared.")}catch(t){e.out.error(t instanceof Error?t.message:"Unknown error")}return"continue"}},lJ={name:"/compact",summary:"Compact history (summarize older messages)",hint:"When context is filling up but you want to keep the thread \u2014 summarizes old turns and keeps the recent ones intact.",async handler(e){let t=sJ({text:m.meta("Summarizing earlier turns..."),...Ga}).start();try{let n=await e.session.current.compact();if(t.stop(),n.compacted){let r=n.tokensSavedEstimate?` (~${n.tokensSavedEstimate} input tokens saved)`:"";e.out.success(`Compacted ${n.messagesBefore} \u2192 ${n.messagesAfter} messages${r}.`)}else{let r=n.reason??"unknown";r==="aborted"?e.out.info("Compaction cancelled."):r.startsWith("summarization-failed")?e.out.error(`Compaction failed: ${r}. History unchanged.`):r==="nothing-to-summarize"?e.out.info("Nothing to compact \u2014 all history is within the keep window."):r==="not-supported"?e.out.warn("Compaction is not supported for this model or provider \u2014 use a Claude model to enable /compact."):e.out.info(`Nothing to compact (${r}).`)}}catch(n){t.stop(),e.out.error(n instanceof Error?n.message:"Unknown error")}return"continue"}},cJ={name:"/help",summary:"Show this help",hint:"When you want the full command list with usage strings \u2014 broader than this inline dropdown.",async handler(e){let t=Ze(),n=t.reduce((r,o)=>Math.max(r,o.name.length),0)+2;e.out.line(),e.out.line(m.bold(m.brand("Commands"))),e.out.line(me());for(let r of t){let o=r.usage??r.name,s=" ".repeat(Math.max(0,n-o.length));e.out.line(` ${m.warning(o)}${s} ${m.dim(r.summary)}`)}return e.out.line(),e.out.line(m.dim(" Tip: Ctrl+C interrupts a running turn; a second press exits.")),e.out.line(),"continue"}},YC=[iJ,aJ,lJ,cJ];function Qh(e,t=30){return!e||e.length===0?m.dim("(none)"):e.length<=t?e.join(", "):`${e.slice(0,t).join(", ")}, ${m.dim(`+${e.length-t} more`)}`}function Kt(e,t){return` ${m.label(e.padEnd(16))} ${t}`}function xd(e){let t=[];t.push(" "+me("Session Debug")),e.sessionId&&t.push(Kt("session",e.sessionId)),e.model&&t.push(Kt("model",e.model)),e.permissionMode&&t.push(Kt("permission",e.permissionMode)),e.cwd&&t.push(Kt("cwd",e.cwd)),e.claudeCodeVersion&&t.push(Kt("sdk",`v${e.claudeCodeVersion}`)),e.apiKeySource&&t.push(Kt("api key",e.apiKeySource)),e.outputStyle&&t.push(Kt("output style",e.outputStyle));let n=e.tools?.length??0;t.push(Kt(`tools (${n})`,Qh(e.tools)));let r=e.mcpServers??[],o=r.length?r.map(c=>`${c.name}[${c.status}]`).join(", "):m.dim("(none)");t.push(Kt(`mcp (${r.length})`,o));let s=e.skills?.length??0;t.push(Kt(`skills (${s})`,Qh(e.skills)));let i=e.plugins?.length??0,a=i?(e.plugins??[]).map(c=>c.name).join(", "):m.dim("(none)");t.push(Kt(`plugins (${i})`,a));let l=e.slashCommands?.length??0;return t.push(Kt(`slash (${l})`,Qh(e.slashCommands))),t.push(" "+me()),t.join(`
1757
+ `),c=d.length}return new Promise(d=>{process.stdin.setRawMode(!0),xo(process.stdin);let p=(g,h)=>{if(h)if(h.name==="up"||h.sequence==="\x1B[A")r>0&&(r--,r<o&&(o=r),u());else if(h.name==="down"||h.sequence==="\x1B[B"){if(r<e.length-1){r++;let{end:b}=i();r>=b&&o++,u()}}else h.name==="space"?(s.has(r)?s.delete(r):s.add(r),u()):h.name==="return"||h.name==="enter"?(f(),d([...s].sort((b,y)=>b-y))):(h.name==="escape"||h.ctrl&&h.name==="c")&&(f(),d(":cancel"))};function f(){process.stdin.removeListener("keypress",p);try{process.stdin.setRawMode(!1)}catch{}}process.stdin.on("keypress",p)})}function jC(e=process.env){return e.AFK_DEMO_CLEAN==="1"||typeof e.SCRIPT=="string"&&e.SCRIPT.length>0||e.ASCIINEMA_REC==="1"}function Kq(e=process.env){return e.AFK_BELL==="1"}function UC(e=process.env){return e.AFK_REDUCED_MOTION==="1"}function hd(e,t=process.env){Kq(t)&&e.isTTY&&e.write("\x07")}var Vh=64,bd=256,yd=20,Yh=new Set(["__proto__","constructor","prototype"]),mi={action:"decline"},ne={action:"cancel"},Wq={action:"accept"};function Gq(e){let t=e.properties,n={},r=0,o=!1;if(typeof t=="object"&&t!==null){let a=0;for(let[l,c]of Object.entries(t))if(!Yh.has(l)){if(r+=1,a>=Vh){o=!0;continue}n[l]=c,a+=1}}let s=e.required,i=new Set(Array.isArray(s)?s.slice(0,Vh*2).filter(a=>typeof a=="string").filter(a=>!Yh.has(a)):[]);return{properties:n,required:i,fieldsTruncated:o,originalFieldCount:r}}function zq(e,t){e.line(),e.line(m.warning("\u26A0 MCP form elicitation")),e.line(m.dim(" server: ")+m.bold(pe(t.serverName,64))),e.line(m.dim(" message: ")+pe(t.message,256)),t.elicitationId&&e.line(m.dim(" id: ")+pe(t.elicitationId,64)),e.line(m.dim(" Type :decline or :cancel at any prompt to exit.")),e.line()}var HC="\u2014 skip (optional) \u2014";async function qq(e,t,n,r,o,s,i){let a,l;if(e.enum!==void 0){let f=e.enum.slice(0,bd);a=f.map(g=>pe(String(g),64)),l=g=>{let h=a.indexOf(g);return h>=0?f[h]:g}}else a=["Yes","No"],l=f=>f==="Yes";let c=t?a:[...a,HC],u=[m.bold(" ? "+n),""],d;try{d=await o({header:u,options:c,multi:!1,signal:i})}catch{return{tag:"cancel"}}if(i.aborted)return{tag:"cancel"};if(d===null)return{tag:"cancel"};let p=d[0];return p===void 0?{tag:"cancel"}:!t&&p===HC?{tag:"value",value:e.default}:(s.line(m.dim(" \u2713 ")+m.brand(`${r}: ${pe(p,128)}`)),{tag:"value",value:l(p)})}async function Jq(e,t,n,r,o,s,i){if(s.aborted)return{tag:"cancel"};let a=pe(t.description??t.title??e),l=pe(t.type??"string",32),c=pe(e,64);if(i&&(t.enum!==void 0||l==="boolean"))return qq(t,n,a,c,i,o,s);let u;if(t.enum!==void 0){let p=t.enum.slice(0,yd).map(g=>pe(String(g),32)).join("|"),f=t.enum.length>yd?"|\u2026":"";u=` (enum: ${p}${f})`}else l==="boolean"?u=" (boolean: y/n)":l==="number"||l==="integer"?u=` (${l})`:l==="string"?u=" (string)":(u=` (${l} \u2014 treated as string)`,o.line(m.warning(` \u26A0 Unknown field type '${l}' for '${c}' \u2014 collecting as string.`)));let d=n?"":m.dim(" [optional, enter to skip]");for(o.line(m.dim(` [${c}]`)+m.dim(` ${a}`)+m.dim(u)+d),t.enum!==void 0&&t.enum.length>bd&&o.line(m.warning(` \u26A0 Field '${c}' has ${t.enum.length} enum values; only the first ${bd} are valid for input.`));;){let p;try{p=await r(m.dim(" > "))}catch{return{tag:"cancel"}}if(s.aborted)return{tag:"cancel"};let f=p.trim();if(f===":cancel")return{tag:"cancel"};if(f===":decline")return{tag:"decline"};if(f===""){if(n){o.line(m.warning(" (required \u2014 cannot be skipped)"));continue}return{tag:"value",value:t.default}}let g;if(l==="boolean"){let h=f.toLowerCase();if(h==="y"||h==="yes"||h==="true"||h==="1")g=!0;else if(h==="n"||h==="no"||h==="false"||h==="0")g=!1;else{o.line(m.warning(" Invalid boolean \u2014 enter y/yes/true/1 or n/no/false/0."));continue}}else if(l==="number"){let h=Number(f);if(!isFinite(h)){o.line(m.warning(" Invalid number \u2014 enter a numeric value."));continue}g=h}else if(l==="integer"){let h=parseInt(f,10);if(!isFinite(h)||String(h)!==f.replace(/\.0+$/,"")){o.line(m.warning(" Invalid integer \u2014 enter a whole number."));continue}g=h}else g=f;if(t.enum!==void 0){let h=t.enum.slice(0,bd),b=!1;for(let y of h)if(String(y)===String(g)){b=!0;break}if(!b){let y=pe(String(g),64),S=h.slice(0,yd).map(R=>pe(String(R),32)).join(", "),w=h.length>yd?", \u2026":"";o.line(m.warning(` '${y}' is not a valid choice. Valid: ${S}${w}`));continue}}return{tag:"value",value:g}}}function Vq(e,t){e.line(),e.line(m.warning("\u26A0 MCP elicitation")),e.line(m.dim(" server: ")+m.bold(pe(t.serverName,64))),e.line(m.dim(" message: ")+pe(t.message,256)),t.url&&e.line(m.dim(" url: ")+m.brand(pe(t.url,512))),t.elicitationId&&e.line(m.dim(" id: ")+pe(t.elicitationId,64)),e.line()}var Ro={action:"skip"};function wd(e){let t=[];return t.push(m.warning(" \u{1F4AC} Agent question")),t.push(m.bold(" ? "+pe(e.message,512))),e.context&&t.push(m.dim(" "+pe(e.context,512))),t.push(""),t}async function Yq(e,t,n,r){let o=wd(t),s=t.allowSkip===!0;if(e==="number"){let u=t.min,d=t.max,f=`enter to submit \xB7 esc to cancel${u!==void 0&&d!==void 0?` [${u}\u2013${d}]`:u!==void 0?` [\u2265${u}]`:d!==void 0?` [\u2264${d}]`:""}`,h=await n({header:o,help:f,validate:y=>{let S=y.trim();if(S==="")return s?null:"Please enter a number (or esc to cancel).";let w=Number(S);return Number.isFinite(w)?u!==void 0&&w<u?`Value must be \u2265 ${u}.`:d!==void 0&&w>d?`Value must be \u2264 ${d}.`:null:"Please enter a valid number."},signal:r});if(h===null)return null;let b=h.trim();return b===""&&s?{tag:"skip"}:{tag:"number",value:Number(b)}}let i=t.minLength,a=t.maxLength,c=await n({header:o,validate:u=>u===""?s?null:"Please enter a response (or esc to cancel).":i!==void 0&&u.length<i?`Response must be at least ${i} characters.`:a!==void 0&&u.length>a?`Response must be at most ${a} characters.`:null,signal:r});return c===null?null:c===""&&s?{tag:"skip"}:{tag:"text",value:c}}async function Xq(e,t,n){if(n.aborted)return mi;let{readLine:r,writer:o,pendingCount:s,pickFromList:i,readTextOverlay:a}=t,l=e.type??"text",c=s();if(c>1&&o.line(m.dim(` [${c} questions queued]`)),(l==="choice"||l==="multi_choice")&&i&&(e.choices?.length??0)>0){let p=(e.choices??[]).map(h=>pe(h,128));e.allowCustom&&p.push(To);let f;try{f=await i({header:wd(e),options:p,multi:l==="multi_choice",signal:n})}catch{return ne}if(n.aborted||f===null)return ne;if(e.allowCustom&&f.includes(To)){if(!a)return ne;let h=await a({header:wd(e),help:"Type your custom answer (Esc to cancel)",validate:b=>b.trim()===""?"Please enter a non-empty answer":null,signal:n});return h===null?ne:(o.line(m.dim(" \u270E ")+m.brand(pe(h,256))),{action:"accept",content:{value:null,custom_value:h}})}if(f.length===0)return e.allowSkip?Ro:ne;let g=f.length===1?pe(f[0]??"",128):f.map(h=>pe(h,128)).join(", ");return o.line(m.dim(" \u2713 ")+m.brand(g)),l==="choice"?{action:"accept",content:{value:f[0]}}:{action:"accept",content:{value:[...f]}}}if(l==="confirm"&&i){let f=e.questionDefault!==!1?["Yes","No"]:["No","Yes"],g;try{g=await i({header:wd(e),options:f,multi:!1,signal:n})}catch{return ne}if(n.aborted||g===null)return ne;let h=g[0];if(h===void 0)return ne;let b=h==="Yes";return o.line(m.dim(" \u2713 ")+(b?m.success("Yes"):m.error("No"))),{action:"accept",content:{value:b}}}if((l==="text"||l==="number")&&a){let p=await Yq(l,e,a,n);if(p===null)return ne;if(p.tag==="skip")return Ro;let f=p.tag==="text"?pe(p.value,256):String(p.value);return o.line(m.dim(" \u2713 ")+m.brand(f)),{action:"accept",content:{value:(p.tag==="text",p.value)}}}if(o.line(),o.line(m.warning("\u{1F4AC} Agent question")),e.context&&o.line(m.dim(" context: ")+pe(e.context,512)),o.line(m.bold(" "+pe(e.message,512))),o.line(m.dim(" Type :cancel to skip this question.")),o.line(),l==="confirm"){o.line("\x07");let p=e.questionDefault===!0?"Y/n":"y/N";for(;;){if(n.aborted)return ne;let f;try{f=(await r(m.dim(` Continue? [${p}] `))).trim().toLowerCase()}catch{return ne}if(n.aborted||f===":cancel")return ne;if(f==="")return{action:"accept",content:{value:e.questionDefault===!0}};if(f==="y"||f==="yes")return{action:"accept",content:{value:!0}};if(f==="n"||f==="no")return{action:"accept",content:{value:!1}};o.line(m.warning(" Please enter y or n."))}}if(l==="choice"){o.line("\x07");let p=e.choices??[],f=e.allowCustom?[...p,To]:p,g=await NC(f,n);if(g!==null){if(g===":cancel")return ne;if(e.allowCustom&&g===p.length){let b;try{b=(await r(m.dim(" Type your answer: "))).trim()}catch{return ne}return b===":cancel"||n.aborted?ne:{action:"accept",content:{value:null,custom_value:b}}}let h=p[g];return h!==void 0?(o.line(m.dim(` Selected: ${pe(h,128)}`)),{action:"accept",content:{value:h}}):ne}for(p.forEach((h,b)=>{o.line(` ${b+1}. ${pe(h,128)}`)}),e.allowCustom&&o.line(` ${p.length+1}. ${To}`);;){if(n.aborted)return ne;let h;try{h=(await r(m.dim(" Enter number: "))).trim()}catch{return ne}if(n.aborted||h===":cancel")return ne;if(e.allowCustom&&h===String(p.length+1)){let y;try{y=(await r(m.dim(" Type your answer: "))).trim()}catch{return ne}return y===":cancel"?ne:{action:"accept",content:{value:null,custom_value:y}}}if(h===""&&e.allowSkip)return Ro;let b=parseInt(h,10);if(!isFinite(b)||String(b)!==h||b<1||b>p.length){o.line(m.warning(` Please enter a number between 1 and ${p.length+(e.allowCustom?1:0)}.`));continue}return{action:"accept",content:{value:p[b-1]}}}}if(l==="multi_choice"){let p=e.choices??[],f=e.allowCustom?[...p,To]:p,g=await BC(f,n);if(g!==null){if(g===":cancel")return ne;if(e.allowCustom&&g.includes(p.length)){let h;try{h=(await r(m.dim(" Type your answer: "))).trim()}catch{return ne}return h===":cancel"||n.aborted?ne:{action:"accept",content:{value:null,custom_value:h}}}if(g.length===0&&e.allowSkip)return Ro;if(g.length>0){let h=g.map(b=>p[b]);return o.line(m.dim(` Selected: ${h.map(b=>pe(b,64)).join(", ")}`)),{action:"accept",content:{value:h}}}}for(p.forEach((h,b)=>{o.line(` ${b+1}. ${pe(h,128)}`)}),e.allowCustom&&o.line(` ${p.length+1}. ${To}`);;){if(n.aborted)return ne;let h;try{h=(await r(m.dim(" Enter numbers (comma-separated): "))).trim()}catch{return ne}if(n.aborted||h===":cancel")return ne;if(e.allowCustom&&h===String(p.length+1)){let w;try{w=(await r(m.dim(" Type your answer: "))).trim()}catch{return ne}return w===":cancel"?ne:{action:"accept",content:{value:null,custom_value:w}}}if(h===""&&e.allowSkip)return Ro;if(h===""){o.line(m.warning(" Please enter at least one selection."));continue}let b=h.split(",").map(w=>w.trim()),y=[],S=!0;for(let w of b){let R=parseInt(w,10);if(!isFinite(R)||String(R)!==w||R<1||R>p.length){o.line(m.warning(` Invalid selection "${pe(w,32)}". Enter numbers between 1 and ${p.length}.`)),S=!1;break}y.push(p[R-1])}if(S)return{action:"accept",content:{value:y}}}}if(l==="number"){let p=e.min,f=e.max,g=p!==void 0&&f!==void 0?` [${p}\u2013${f}]`:p!==void 0?` [\u2265${p}]`:f!==void 0?` [\u2264${f}]`:"";for(;;){if(n.aborted)return ne;let h;try{h=(await r(m.dim(` Enter a number${g}: `))).trim()}catch{return ne}if(n.aborted||h===":cancel")return ne;if(h===""&&e.allowSkip)return Ro;if(h===""&&!e.allowSkip){o.line(m.warning(" Please enter a number (or :cancel to skip)."));continue}let b=Number(h);if(!isFinite(b)){o.line(m.warning(" Please enter a valid number."));continue}if(p!==void 0&&b<p){o.line(m.warning(` Value must be \u2265 ${p}.`));continue}if(f!==void 0&&b>f){o.line(m.warning(` Value must be \u2264 ${f}.`));continue}return{action:"accept",content:{value:b}}}}let u=e.minLength,d=e.maxLength;for(;;){if(n.aborted)return ne;let p;try{p=(await r(m.dim(" > "))).trim()}catch{return ne}if(n.aborted||p===":cancel")return ne;if(p===""&&e.allowSkip)return Ro;if(p===""){o.line(m.warning(" Please enter a response (or type :cancel to skip)."));continue}if(u!==void 0&&p.length<u){o.line(m.warning(` Response must be at least ${u} characters.`));continue}if(d!==void 0&&p.length>d){o.line(m.warning(` Response must be at most ${d} characters.`));continue}return{action:"accept",content:{value:p}}}}function Sd(e){return async(t,{signal:n})=>{if(n.aborted)return mi;hd(process.stdout),e.suspendInput?.();try{if(t.origin==="agent")return await Xq(t,e,n);if(t.mode==="form"){let o=t.requestedSchema,{properties:s,required:i,fieldsTruncated:a,originalFieldCount:l}=typeof o=="object"&&o!==null?Gq(o):{properties:{},required:new Set,fieldsTruncated:!1,originalFieldCount:0};zq(e.writer,t),a&&e.writer.line(m.warning(` \u26A0 Schema has ${l} fields; only the first ${Vh} will be prompted (server may be malformed or compromised).`));let c=Object.create(null);if(Object.keys(s).length===0)return e.writer.line(m.warning(" \u26A0 Form schema has no usable fields \u2014 declining.")),mi;for(let u of i)if(!(u in s))return e.writer.line(m.warning(` \u26A0 Required field '${pe(u,64)}' has no schema entry \u2014 declining.`)),mi;for(let[u,d]of Object.entries(s)){if(n.aborted)return ne;let p=await Jq(u,d,i.has(u),e.readLine,e.writer,n,e.pickFromList);if(p.tag==="cancel")return ne;if(p.tag==="decline")return mi;p.value!==void 0&&!Yh.has(u)&&(c[u]=p.value)}return{action:"accept",content:{...c}}}Vq(e.writer,t);let r=(await e.readLine(m.dim("Continue? [y/N] "))).trim().toLowerCase();return r===""?ne:r==="y"||r==="yes"?Wq:mi}finally{e.resumeInput?.()}}}Gs();qt();Qt();He();Nt();function KC(e){let t=Math.max(0,Math.min(1,e.ratio)),n=t>.8?m.error:t>.5?m.warning:m.meta,r=20,o=Math.round(t*r),s=r-o,i="["+"\u2588".repeat(o)+"\u2591".repeat(s)+"]",a=Math.round(t*100)+"%",l="";e.used!==void 0&&e.limit!==void 0&&(l=ae(e.used)+"/"+ae(e.limit));let c=l?`${i} ${a} ${l}`:`${i} ${a}`,u=`${i} ${a}`,d=`ctx ${a}`,p=e.sparkline?m.meta(e.sparkline)+" ":"",f=e.sparkline?J(e.sparkline)+1:0,g=Math.max(0,e.width-f);if(J(c)<=g&&g>90)return p+n(c);if(J(u)<=g&&g>32)return p+n(u);if(J(d)<=g)return p+n(d);if(e.width>0){let h=p+n(d);return ie(h,e.width)}return n(a)}var vd=class{stream;force;throttleMs;started=!1;lastRepaint=0;lastFields=null;resizeUnsub=null;resizeImmediateUnsub=null;lastPaintedRow=null;preResizePaintedRow=null;extraRows=0;afterScrollRestore=null;constructor(t={}){this.stream=t.stream??process.stdout,this.force=t.force??!1,this.throttleMs=t.throttleMs??100}get enabled(){return this.force||!!this.stream.isTTY}start(){if(this.started||!this.enabled)return;this.started=!0,this.lastRepaint=0;let t=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.resizeUnsub===null&&(this.resizeUnsub=Le.subscribe(()=>{this.onResize()}),this.resizeImmediateUnsub=Le.subscribeImmediate(()=>this.resetGeometry()))}resetGeometry(){this.preResizePaintedRow=this.lastPaintedRow,this.lastPaintedRow=null,this.lastRepaint=0}onResize(){if(!this.started||!this.enabled)return;let t=this.currentRows(),n=this.preResizePaintedRow??this.lastPaintedRow;this.preResizePaintedRow=null,this.stream.write("\x1B[s"),n!==null&&n!==this.paintRow(t)&&(this.stream.write(`\x1B[${n};1H`),this.stream.write("\x1B[2K")),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.flush()}repaint(t){if(!this.enabled||!this.started){this.lastFields=t;return}let n=Date.now();if(n-this.lastRepaint<this.throttleMs){this.lastFields=t;return}this.lastRepaint=n,this.lastFields=t;let r=this.currentRows();this.stream.write("\x1B[s"),this.stream.write(`\x1B[${this.paintRow(r)};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatLine(t)),this.stream.write("\x1B[u"),this.lastPaintedRow=this.paintRow(r)}flush(){this.lastRepaint=0,this.lastFields&&this.repaint(this.lastFields)}setExtraRows(t){if(this.extraRows=t,this.started&&this.enabled){let n=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(n),this.stream.write("\x1B[u"),this.flush()}}getExtraRows(){return this.extraRows}setAfterScrollRestore(t){this.afterScrollRestore=t}rearm(){if(!this.started||!this.enabled)return;let t=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.flush()}withFullScrollRegion(t){if(!this.started||!this.enabled)return t();this.stream.write("\x1B[s"),this.stream.write("\x1B[r"),this.stream.write("\x1B[u");try{return t()}finally{let n=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(n),this.stream.write("\x1B[u"),this.flush(),this.afterScrollRestore?.()}}stop(){if(this.resizeUnsub!==null&&(this.resizeUnsub(),this.resizeUnsub=null),this.resizeImmediateUnsub!==null&&(this.resizeImmediateUnsub(),this.resizeImmediateUnsub=null),!this.started||!this.enabled){this.started=!1;return}let t=this.currentRows();this.stream.write("\x1B[s");let n=this.preResizePaintedRow??this.lastPaintedRow??this.paintRow(t);this.stream.write(`\x1B[${n};1H`),this.stream.write("\x1B[2K"),this.stream.write("\x1B[r"),this.stream.write("\x1B[u"),this.started=!1,this.lastRepaint=0,this.lastPaintedRow=null,this.preResizePaintedRow=null}formatLine(t){let n=[],r=Math.max(4,(this.stream.columns??80)-2);if(t.cwd){let a=Math.max(8,Math.floor(r*.4)),l=Wa(t.cwd,{maxWidth:a});l&&n.push({text:m.dim(l)})}if(n.push({text:m.brand(t.model)}),t.permissionMode==="plan"?n.push({text:m.warning("\u25CF plan")}):t.permissionMode==="autonomous"?n.push({text:m.info("\u25D0 AFK")}):t.permissionMode==="bypassPermissions"&&n.push({text:m.bypass("\u26A1 BYPASS")}),t.contextPct!==void 0){let a=KC({ratio:t.contextPct,used:t.contextUsedTokens,limit:t.contextLimit,sparkline:t.contextSparkline,width:r});n.push({text:a,droppablePriority:1})}t.cost!==void 0&&n.push({text:m.meta(`$${t.cost.toFixed(2)}`),droppablePriority:2}),t.tokens!==void 0&&n.push({text:m.meta(`${Zq(t.tokens)} tok`),droppablePriority:3});let o=m.dim(" \xB7 "),s=n.map(a=>a.text).join(o);if(J(s)<=r)return s;let i=n.filter(a=>a.droppablePriority!==void 0);for(;i.length>0&&J(s)>r;){let a=Math.max(...i.map(l=>l.droppablePriority));n=n.filter(l=>l.droppablePriority===void 0||l.droppablePriority!==a),s=n.map(l=>l.text).join(o),i=n.filter(l=>l.droppablePriority!==void 0)}return ie(s,r)}currentRows(){let t=this.stream.rows;return typeof t=="number"&&t>0?t:24}paintRow(t){return t>1?t:1}writeScrollRegion(t){let n=1+this.extraRows;if(t>n){this.stream.write(`\x1B[1;${t-n}r`);return}this.stream.write("\x1B[r")}};function Zq(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}var Rt=new Map,Ao=new Map;function fe(e){if(Rt.has(e.name))throw new Error(`Slash command already registered: ${e.name}`);Rt.set(e.name,e);for(let t of e.aliases??[]){if(Ao.has(t)||Rt.has(t))throw new Error(`Slash alias collides: ${t}`);Ao.set(t,e.name)}}function Dr(e){if(Rt.has(e.name)){for(let[t,n]of Ao.entries())n===e.name&&Ao.delete(t);Rt.delete(e.name)}fe(e)}function WC(e){Rt.has(e.name)||fe(e)}function GC(){Rt.clear(),Ao.clear()}function Ze(){return[...Rt.values()].sort((e,t)=>e.name.localeCompare(t.name))}function fi(){let e=[];for(let[t,n]of Ao.entries()){let r=Rt.get(n);r&&e.push({alias:t,canonical:n,summary:r.summary})}return e.sort((t,n)=>t.alias.localeCompare(n.alias))}function Qq(e){if(Rt.has(e))return Rt.get(e);let t=Ao.get(e);return t?Rt.get(t):void 0}function eJ(e,t){let n=Array.from({length:e.length+1},()=>new Array(t.length+1).fill(0));for(let r=0;r<=e.length;r++)n[r][0]=r;for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let o=1;o<=t.length;o++){let s=e[r-1]===t[o-1]?0:1;n[r][o]=Math.min(n[r-1][o]+1,n[r][o-1]+1,n[r-1][o-1]+s)}return n[e.length][t.length]}function tJ(e,t=3){let n;for(let r of Rt.keys()){let o=eJ(e,r);o<=t&&(n===void 0||o<n.dist)&&(n={name:r,dist:o})}return n?.name}function Xh(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.indexOf(" ");return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}async function zC(e,t,n){let r=Xh(e);if(r===null)return{handled:!1};let o=Qq(r.name);if(!o){let a=tJ(r.name);return a?t.out.warn(`Unknown command: ${r.name} (did you mean ${a}?)`):t.out.warn(`Unknown command: ${r.name} (type /help for commands)`),{handled:!0,result:"continue"}}let s=n??[];s.length>0&&o.acceptsAttachments!==!0&&t.out.warn(`\u26A0 Image attachments are ignored by ${r.name} (images only reach the model on skill commands like /forge, /mint).`);let i=await o.handler(t,r.args,o.acceptsAttachments===!0?s:void 0);return i==="forward"?{handled:!1}:{handled:!0,result:i}}import sJ from"ora";wa();function qC(e,t=5){if(e.length===0)return"";let n=e.slice(-t),r=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];return n.map(o=>{let s=Math.max(0,Math.min(1,o)),i=Math.min(7,Math.floor(s*8));return r[i]}).join("")}function kd(e,t,n){e.totalTurns=t.totalTurns,e.totalCostUsd=t.totalCostUsd,e.totalTokens=t.totalTokens,e.totalDurationMs=t.totalDurationMs,e.turns=[...t.turns],e.sessionId=t.sessionId??n,e.name=t.name,e.model=t.model,e.sessionStartTime=t.startedAt??Date.now()}function Ed(e,t){let n=e.turns;if(n.length===0)return;let r=n[n.length-1];if(!r)return;let o=VC(JC(r.user),80),s=VC(oJ(JC(r.assistant)),120);o.length>0&&t.fn(m.dim(` Last: ${o}`)),s.length>0&&t.fn(m.dim(` \u21B3 ${s}`)),t.fn(m.dim(" \u21AA /history for full review"))}function JC(e){return e.replace(rJ,"").replace(/\s+/g," ").trim()}var rJ=/\u001B\][\s\S]*?(?:\u0007|\u001B\\|\u009C)|\u001B[PX^_][\s\S]*?(?:\u0007|\u001B\\|\u009C)|\u001B[@-OQ-WY-Z\\`6-9=]|[\u001B\u009B][[\]()#;?]*(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]/g;function oJ(e){let t=e.match(/^.*?(?<![A-Za-z]\.[A-Za-z])[.!?](?=\s|$)/);return t?t[0]:e}function VC(e,t){let n=[...e];return n.length<=t?e:n.slice(0,t-1).join("")+"\u2026"}var Ga={stream:process.stdout,hideCursor:!1,discardStdin:!1};function Zh(e,t){if(t?.getRatio()!==void 0)return t.getRatio();let n=e.turnTokens[e.turnTokens.length-1];return n?(n.footprint??n.input+n.output+n.cache)/kt(e.model):0}function tr(e,t){let n=Zh(e,t),r=kt(e.model),o,s=t?.getDetail();if(s!==void 0)o=s.used;else{let a=e.turnTokens[e.turnTokens.length-1];a&&(o=a.footprint??a.input+a.output+a.cache)}let i;if(e.turnTokens.length>=2){let a=e.turnTokens.map(c=>(c.footprint??c.input+c.output+c.cache)/r),l=qC(a,5);l.length>0&&(i=l)}return{model:e.model,cost:e.totalCostUsd,tokens:e.totalTokens,contextPct:n,contextLimit:r,contextUsedTokens:o,contextSparkline:i,permissionMode:e.permissionMode,...e.cwd!==void 0?{cwd:e.cwd}:{}}}var iJ={name:"/exit",aliases:["/quit"],summary:"Exit the session",hint:"When you want to tear down the REPL \u2014 Ctrl+D on an empty prompt does the same.",async handler(){return"exit"}},aJ={name:"/clear",summary:"Clear conversation history",hint:"When the current thread has drifted off-topic or you want a clean slate without restarting the session.",async handler(e){try{await e.session.current.reset(),e.ui.clearScreen(),vC(e.stats),e.ledger?.clear(),e.out.success("Conversation history cleared.")}catch(t){e.out.error(t instanceof Error?t.message:"Unknown error")}return"continue"}},lJ={name:"/compact",summary:"Compact history (summarize older messages)",hint:"When context is filling up but you want to keep the thread \u2014 summarizes old turns and keeps the recent ones intact.",async handler(e){let t=sJ({text:m.meta("Summarizing earlier turns..."),...Ga}).start();try{let n=await e.session.current.compact();if(t.stop(),n.compacted){let r=n.tokensSavedEstimate?` (~${n.tokensSavedEstimate} input tokens saved)`:"";e.out.success(`Compacted ${n.messagesBefore} \u2192 ${n.messagesAfter} messages${r}.`)}else{let r=n.reason??"unknown";r==="aborted"?e.out.info("Compaction cancelled."):r.startsWith("summarization-failed")?e.out.error(`Compaction failed: ${r}. History unchanged.`):r==="nothing-to-summarize"?e.out.info("Nothing to compact \u2014 all history is within the keep window."):r==="not-supported"?e.out.warn("Compaction is not supported for this model or provider \u2014 use a Claude model to enable /compact."):e.out.info(`Nothing to compact (${r}).`)}}catch(n){t.stop(),e.out.error(n instanceof Error?n.message:"Unknown error")}return"continue"}},cJ={name:"/help",summary:"Show this help",hint:"When you want the full command list with usage strings \u2014 broader than this inline dropdown.",async handler(e){let t=Ze(),n=t.reduce((r,o)=>Math.max(r,o.name.length),0)+2;e.out.line(),e.out.line(m.bold(m.brand("Commands"))),e.out.line(me());for(let r of t){let o=r.usage??r.name,s=" ".repeat(Math.max(0,n-o.length));e.out.line(` ${m.warning(o)}${s} ${m.dim(r.summary)}`)}return e.out.line(),e.out.line(m.dim(" Tip: Ctrl+C interrupts a running turn; a second press exits.")),e.out.line(),"continue"}},YC=[iJ,aJ,lJ,cJ];function Qh(e,t=30){return!e||e.length===0?m.dim("(none)"):e.length<=t?e.join(", "):`${e.slice(0,t).join(", ")}, ${m.dim(`+${e.length-t} more`)}`}function Kt(e,t){return` ${m.label(e.padEnd(16))} ${t}`}function xd(e){let t=[];t.push(" "+me("Session Debug")),e.sessionId&&t.push(Kt("session",e.sessionId)),e.model&&t.push(Kt("model",e.model)),e.permissionMode&&t.push(Kt("permission",e.permissionMode)),e.cwd&&t.push(Kt("cwd",e.cwd)),e.claudeCodeVersion&&t.push(Kt("sdk",`v${e.claudeCodeVersion}`)),e.apiKeySource&&t.push(Kt("api key",e.apiKeySource)),e.outputStyle&&t.push(Kt("output style",e.outputStyle));let n=e.tools?.length??0;t.push(Kt(`tools (${n})`,Qh(e.tools)));let r=e.mcpServers??[],o=r.length?r.map(c=>`${c.name}[${c.status}]`).join(", "):m.dim("(none)");t.push(Kt(`mcp (${r.length})`,o));let s=e.skills?.length??0;t.push(Kt(`skills (${s})`,Qh(e.skills)));let i=e.plugins?.length??0,a=i?(e.plugins??[]).map(c=>c.name).join(", "):m.dim("(none)");t.push(Kt(`plugins (${i})`,a));let l=e.slashCommands?.length??0;return t.push(Kt(`slash (${l})`,Qh(e.slashCommands))),t.push(" "+me()),t.join(`
1758
1758
  `)}Ve();qt();var ny=["local","small","medium","large","opus","opus_1m","sonnet","sonnet_1m","haiku","fable"],fJ={name:"/cost",summary:"Show total and per-turn cost",hint:"When you want a dollar breakdown of this session \u2014 total, average per turn, and the recent turn-by-turn series.",async handler(e){let{stats:t,out:n}=e;if(n.line(),n.line(m.bold("Session cost")),n.line(me()),n.line(` total ${m.success(Xe(t.totalCostUsd))}`),n.line(` turns ${m.meta(String(t.totalTurns))}`),t.totalTurns>0){let r=t.totalCostUsd/t.totalTurns;n.line(` avg/turn ${m.meta(Xe(r))}`)}if(t.turnCosts.length>0){let r=t.turnCosts.slice(-5).map(Xe).join(m.dim(" \xB7 "));n.line(` last 5 ${r}`)}return n.line(),"continue"}};function gJ(e,t){let n=t.apiUsage,r=n?.input_tokens??0,o=n?.output_tokens??0,s=n?.cache_read_input_tokens??0,i=n?.cache_creation_input_tokens??0,a=r+o+s+i;e.line(),e.line(m.bold("Token usage")+m.dim(" (SDK breakdown)")),e.line(me()),e.line(` total ${m.success(ae(t.totalTokens))} of ${m.meta(ae(t.maxTokens))} (${m.meta(`${Math.round(t.percentage*100)/100}%`)})`),t.autoCompactThreshold&&t.isAutoCompactEnabled&&e.line(` compact at ${m.meta(ae(t.autoCompactThreshold))}`),e.line(),e.line(m.dim(" Last turn (API):")),e.line(` input ${m.meta(ae(r))}`),e.line(` output ${m.meta(ae(o))}`),e.line(` cache read ${m.meta(ae(s))}`),e.line(` cache creat ${m.meta(ae(i))}`),e.line(` total ${m.meta(ae(a))}`);let l=t.categories??[];if(l.length>0){let p=[...l].sort((f,g)=>g.tokens-f.tokens).slice(0,5);e.line(),e.line(m.dim(" Top categories:"));for(let f of p)e.line(` ${m.warning(f.name.padEnd(18))} ${m.meta(ae(f.tokens))}`)}let c=t.systemTools??[],u=t.mcpTools??[];if(c.length>0||u.length>0){e.line();let p=c.reduce((g,h)=>g+h.tokens,0),f=u.reduce((g,h)=>g+h.tokens,0);c.length>0&&e.line(m.dim(` system tools ${c.length} tools, ${ae(p)} tokens`)),u.length>0&&e.line(m.dim(` MCP tools ${u.length} tools, ${ae(f)} tokens`))}let d=t.agents??[];if(d.length>0){let p=d.reduce((f,g)=>f+g.tokens,0);e.line(m.dim(` agents ${d.length} loaded, ${ae(p)} tokens`))}if(t.skills){let p=t.skills;e.line(m.dim(` skills ${p.includedSkills}/${p.totalSkills} included, ${ae(p.tokens)} tokens`))}if(t.slashCommands){let p=t.slashCommands;e.line(m.dim(` slash cmds ${p.includedCommands}/${p.totalCommands} included, ${ae(p.tokens)} tokens`))}e.line()}function hJ(e,t){let n=t.turnTokens.reduce((u,d)=>u+d.input,0),r=t.turnTokens.reduce((u,d)=>u+d.output,0),o=t.turnTokens.reduce((u,d)=>u+d.cache,0),s=n+r,i=kt(t.model),a=t.turnTokens[t.turnTokens.length-1],l=a?a.footprint??a.input+a.output+a.cache:0,c=i>0?Math.round(l/i*100):0;e.line(),e.line(m.bold("Token usage")+m.dim(" (local stats \u2014 SDK breakdown unavailable)")),e.line(me()),e.line(` input ${m.meta(ae(n))}`),e.line(` output ${m.meta(ae(r))}`),e.line(` cache read ${m.meta(ae(o))}`),e.line(` total ${m.success(ae(s))}`),e.line(` context ${m.meta(`${c}% of ${ae(i)} (${t.model})`)}`),e.line()}var yJ={name:"/tokens",aliases:["/ctx"],summary:"Show token usage (SDK breakdown with local-stats fallback)",hint:"When you want to know how full the context window is \u2014 input/output/cache breakdown plus % of the model's limit used.",async handler(e){try{let t=await e.session.current.getContextUsage();gJ(e.out,t)}catch{hJ(e.out,e.stats)}return"continue"}},bJ={name:"/history",summary:"Show conversation history",async handler(e){let{stats:t,out:n}=e;return t.turns.length===0?(n.info("No turns yet in this session."),"continue"):(n.line(),n.line(m.bold(`Session history (${t.turns.length} turn${t.turns.length===1?"":"s"})`)),n.line(me()),t.turns.forEach((r,o)=>{let s=m.meta(`#${o+1}`),i=r.user.length>100?r.user.slice(0,97)+"...":r.user,a=r.assistant.length>100?r.assistant.slice(0,97)+"...":r.assistant;n.line(` ${s} ${m.user("\u25B6")} ${i}`),n.line(` ${m.brand("\u25C6")} ${m.dim(a)}`)}),n.line(),"continue")}},wJ={name:"/reset",summary:"Clear screen, history, and session stats",async handler(e){let{stats:t,ui:n,out:r}=e;try{await e.session.current.sendMessage("/clear")}catch{}return t.totalTurns=0,t.totalCostUsd=0,t.totalTokens=0,t.totalDurationMs=0,t.turnCosts.length=0,t.turnTokens.length=0,t.turns.length=0,t.sessionStartTime=Date.now(),n.clearScreen(),r.success("Session reset."),"continue"}},SJ={name:"/model",usage:"/model <local|small|medium|large|opus|sonnet|haiku|fable|org/model>",summary:"Switch the active model mid-session",hint:"Switch the capability tier (local/small/medium/large \u2014 or your configured names) or pass a full model id. Upgrade to large for a hard problem, downshift to small for cheap iteration \u2014 context carries over. Also accepts HuggingFace-style ids (e.g. mlx-community/Qwen3-30B-A3B-4bit).",async handler(e,t){let n=t.trim().toLowerCase();if(!n)return e.out.info(`Current model: ${m.brand(e.stats.model)}`),e.out.line(m.dim(` Aliases: ${ny.join(", ")} (or any org/model HF id)`)),"continue";let r=ny.includes(n),o=hs(n)!==void 0,s=oe(n)==="openai-compatible";if(!r&&!o&&!s)return e.out.warn(`Unknown model: ${n}. Aliases: ${ny.join(", ")} (or org/model for local/OpenAI-compatible)`),"continue";let i=ys(n);if(i)return e.out.warn(i),"continue";try{await e.session.current.setModel(n),e.stats.model=n,e.ui.repaintStatusLine(),e.out.success(`Model switched to ${m.brand(n)}`)}catch(a){e.out.error(`Failed to switch model: ${a instanceof Error?a.message:String(a)}`)}return"continue"}},vJ={name:"/tools",summary:"List tools available to the session",async handler(e){try{let n=(await e.session.current.waitForInitialization()).tools??[];if(n.length===0)return e.out.info("No tools reported by the session."),"continue";e.out.line(),e.out.line(m.bold(`Tools (${n.length})`)),e.out.line(me());let r=3,o=Math.ceil(n.length/r),s=Math.max(...n.map(i=>i.length))+2;for(let i=0;i<o;i++){let a=[];for(let l=0;l<r;l++){let c=l*o+i;c<n.length&&a.push(n[c].padEnd(s))}e.out.line(" "+a.join(""))}e.out.line()}catch(t){e.out.error(`Could not read session tools: ${t instanceof Error?t.message:String(t)}`)}return"continue"}},kJ={name:"/mcp",summary:'List MCP servers connected to the session ("/mcp auth" to surface pending OAuth URLs)',async handler(e,t){let n=(t??"").trim().toLowerCase();if(n==="auth"){try{let{readOauthPending:r}=await Promise.resolve().then(()=>(Ad(),o_)),o=r();if(Object.keys(o).length===0)return e.out.info("No MCP servers are waiting for OAuth."),"continue";e.out.line(),e.out.line(m.bold(`MCP OAuth pending (${Object.keys(o).length})`)),e.out.line(me());for(let[s,i]of Object.entries(o)){let a=Date.now()-i.timestamp,l=Math.round(a/6e4);e.out.line(` ${m.warning("\u25CF")} ${s} ${m.dim(`(${l}m ago)`)}`),e.out.line(` ${m.info(i.authorizationUrl)}`)}e.out.line(),e.out.line(m.dim(" Open each URL in a browser. After authorizing, paste the code with:")),e.out.line(m.dim(" /mcp auth complete <serverName> <code>")),e.out.line()}catch(r){e.out.error(`Could not read OAuth state: ${r instanceof Error?r.message:String(r)}`)}return"continue"}if(n.startsWith("auth complete ")){let r=(t??"").trim(),o=r.slice(r.toLowerCase().indexOf("auth complete ")+14).trim(),s=o.indexOf(" ");if(s===-1||o.slice(0,s).length===0||o.slice(s+1).trim().length===0)return e.out.error("Usage: /mcp auth complete <serverName> <code>"),"continue";let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(!e.mcpManager)return e.out.error("No MCP manager available in this session. Make sure an mcp.json config is present and at least one server is enabled."),"continue";try{e.out.info(`Completing OAuth for "${i}"\u2026`),await e.mcpManager.completeAuth(i,a),e.out.success(`OAuth complete for "${i}" \u2014 server is now connected.`)}catch(l){e.out.error(`OAuth completion failed for "${i}": ${l instanceof Error?l.message:String(l)}`)}return"continue"}if(n!==""&&n!=="auth")return e.out.error(`Unknown /mcp subcommand: "${n}". Try: /mcp, /mcp auth, /mcp auth complete <server> <code>.`),"continue";try{let o=(await e.session.current.waitForInitialization()).mcpServers??[];if(o.length===0)return e.out.info("No MCP servers connected."),"continue";e.out.line(),e.out.line(m.bold(`MCP servers (${o.length})`)),e.out.line(me());let s=0;for(let i of o){let a=typeof i=="string"?i:i.name??JSON.stringify(i),l=typeof i=="object"&&i!==null&&"status"in i?String(i.status):"",c=l==="connected"?m.success("\u25CF"):m.warning("\u25CF");e.out.line(` ${c} ${a}${l?m.dim(` (${l})`):""}`),l==="oauth_pending"&&s++}e.out.line(),s>0&&(e.out.line(m.dim(` ${s} server(s) need OAuth \u2014 run "/mcp auth" to see authorization URLs.`)),e.out.line())}catch(r){e.out.error(`Could not read MCP servers: ${r instanceof Error?r.message:String(r)}`)}return"continue"}},EJ={name:"/limits",summary:"Show known per-model context-window limits",async handler(e){e.out.line(),e.out.line(m.bold("Context-window limits")),e.out.line(me());for(let[t,n]of Object.entries(Fs)){let r=t===e.stats.model?m.brand(" \u2190 active"):"";e.out.line(` ${m.warning(t.padEnd(12))} ${m.meta(ae(n))}${r}`)}return e.out.line(),"continue"}},xJ={name:"/debug",summary:"Show SDK session metadata (tools, MCP, skills, plugins, etc.)",hint:"When something feels broken and you want to inspect what the session actually loaded \u2014 tools, MCP servers, plugins, system prompt source.",async handler(e){try{let t=await e.session.current.waitForInitialization();e.out.line(),e.out.line(xd(t)),e.out.line()}catch(t){e.out.error(`Could not read session metadata: ${t instanceof Error?t.message:String(t)}`)}return"continue"}},s_=[fJ,yJ,bJ,wJ,SJ,vJ,kJ,EJ,xJ];W();var ry=!1;async function nr(e,t){let n=e.stats.permissionMode==="plan",r=t!==void 0?t:!n;try{if(await e.session.current.setPermissionMode(r?"plan":"default"),e.stats.permissionMode=r?"plan":"default",e.ui.repaintStatusLine(),r){let o=ry?"":m.dim(" /plan off saves the plan + implements; Shift+Tab just exits.");ry||(ry=!0),e.out.success(m.warning("\u25CF plan mode ON")+m.dim(" \u2014 writes are refused; read-only bash runs, mutating bash is blocked.")+o)}else e.out.success(m.success("\u25CB plan mode OFF")+m.dim(" \u2014 default permissions restored"))}catch(o){e.out.error(`Could not toggle plan mode: ${o instanceof Error?o.message:String(o)}`)}}function TJ(e){return["The user has switched off plan mode. Writes are now permitted. Do two things, in order:","",`1. Save the plan. Write the plan you developed in this conversation to a new markdown file under \`${e}/\` \u2014 pick a short, descriptive kebab-case filename (e.g. \`${e}/refactor-auth-flow.md\`). Capture the full plan: the chosen approach, the concrete step-by-step changes, the risks named, and the alternatives considered. This is the durable record.`,"","2. Implement the plan. Work through the steps you just recorded, verifying as you go \u2014 run the project's lint/test gates where they apply. End in a terminal state: Done with evidence, Blocked with the exact unblock condition, or Asking one precise question."].join(`
1759
1759
  `)}async function RJ(e){if(await nr(e,!1),e.stats.permissionMode==="plan")return"continue";let t=Kw(e.stats.cwd??process.cwd());return e.out.info(m.dim(` \u2192 saving the plan to ${t}/, then implementing it.`)),{kind:"submit",message:TJ(t)}}var i_={name:"/plan",usage:"/plan [on|off|<prompt>]",summary:"Toggle plan mode; /plan off saves the plan to a file then implements it",hint:"Think through an approach without changing anything \u2014 write tools and state-mutating bash are refused until you exit; read-only investigation runs. /plan off saves the plan + implements it; Shift+Tab exits without implementing.",async handler(e,t){let n=t.trim(),r=n.toLowerCase();return n!==""&&r!=="on"&&r!=="off"?(e.stats.permissionMode!=="plan"&&await nr(e,!0),{kind:"submit",message:n}):(r==="on"?!0:r==="off"?!1:e.stats.permissionMode!=="plan")===!0?(e.stats.permissionMode==="plan"||await nr(e,!0),"continue"):e.stats.permissionMode!=="plan"?(await nr(e,!1),"continue"):RJ(e)}};G();jc();Ju();po();var a_=20,AJ={done:"\u2705 Done",blocked:"\u26D4 Blocked",asking:"\u2753 Asking",interrupted:"\u23F8\uFE0F Interrupted"},CJ={done:[["","whatWasDone"],["Evidence","evidence"],["Pending","deferred"]],blocked:[["Blocked by","whatBlocks"],["Unblock","unblockCondition"],["Done so far","alreadyDone"]],asking:[["","question"],["Resolves","assumption"],["Then","followup"]],interrupted:[["","whatWasInProgress"],["State saved","stateLocation"],["Resume needs","resumeRequires"]]};function _J(e){let t=`\u{1F916} AFK \xB7 ${AJ[e.kind]}`,n=[];for(let[o,s]of CJ[e.kind]){let i=e[s];typeof i=="string"&&i.trim().length>0&&n.push(o?`\u2022 ${o}: ${i.trim()}`:`\u2022 ${i.trim()}`)}n.length===0&&e.rawBody.trim().length>0&&n.push(e.rawBody.trim());let r=n.length>0?n.join(`
1760
1760
  `):"(no detail)";return Mr(`${t}
1761
1761
  ${r}`)}var oy=0,sy=!1;function l_(){oy=0,sy=!1}async function c_(e,t=wr){try{if(oy>=a_){sy||(sy=!0,await t(`\u{1F916} AFK \xB7 reached ${a_} updates this session \u2014 further terminal-state pushes muted. Run /afk off then /afk on to resume.`));return}oy+=1,await t(_J(e))}catch{}}W();import*as hi from"node:fs";import*as d_ from"node:path";import{createHmac as IJ,randomBytes as p_,timingSafeEqual as PJ}from"node:crypto";var MJ=32,m_="\0";function OJ(e){return JSON.stringify(iy(e))}function iy(e){if(Array.isArray(e))return e.map(iy);if(e!==null&&typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort())n[r]=iy(t[r]);return n}return e}function f_(e){let t=u_(e);if(t)return t;let n;try{n=$m(e)}catch{return null}try{hi.mkdirSync(d_.dirname(n),{recursive:!0});let r=p_(MJ).toString("hex");return hi.writeFileSync(n,r+`
1762
- `,{mode:384}),r}catch{return u_(e)}}function u_(e){let t;try{t=$m(e)}catch{return null}try{let n=hi.readFileSync(t,"utf8").trim();return n.length>0?n:null}catch{return null}}function g_(e,t){return IJ("sha256",e).update(t).digest("hex")}function h_(e,t){if(typeof e!="string"||typeof t!="string"||e.length!==t.length||e.length===0||!/^[0-9a-f]+$/i.test(e)||!/^[0-9a-f]+$/i.test(t))return!1;let n,r;try{n=Buffer.from(e,"hex"),r=Buffer.from(t,"hex")}catch{return!1}return n.length!==r.length||n.length===0?!1:PJ(n,r)}function $J(e,t,n){return["elicitation_response",e,t,OJ(n)].join(m_)}function DJ(e,t,n,r){return g_(e,$J(t,n,r))}function y_(e,t,n,r,o){return h_(o,DJ(e,t,n,r))}function LJ(e,t){return["abort_request",e,t].join(m_)}function FJ(e,t,n){return g_(e,LJ(t,n))}function b_(e,t,n,r){return h_(r,FJ(e,t,n))}function w_(){return p_(8).toString("hex")}jh();var S_={action:"decline"};function v_(e){let{sessionId:t,key:n,onAbort:r}=e;if(n===null)return{stop:()=>{}};let o=new AbortController;return(async()=>{try{for await(let s of Bh(t,{fromStart:!1,signal:o.signal}))if(s.kind==="abort_request"&&b_(n,t,s.nonce,s.hmac)){r("remote abort via Telegram"),o.abort();return}}catch{}})(),{stop:()=>{o.abort()}}}function k_(e){let{sessionId:t,key:n,emitElicitation:r,fallback:o}=e,s=e.newReqId??w_;return function(a,l){let c=l.signal;if(c.aborted)return Promise.resolve(S_);let u=s(),d,p=new Promise(h=>{d=h}),f=new AbortController,g=()=>{f.abort(),d(S_)};c.addEventListener("abort",g,{once:!0}),n&&(async()=>{try{for await(let h of Bh(t,{fromStart:!1,signal:f.signal}))if(h.kind==="elicitation_response"&&h.reqId===u&&y_(n,t,u,h.result,h.hmac)){d(h.result);return}}catch{}})();try{r({kind:"elicitation",reqId:u,request:a})}catch{}return Promise.resolve(o(a,{signal:f.signal})).then(h=>d(h)).catch(()=>{}),p.finally(()=>{f.abort(),c.removeEventListener("abort",g)})}}aa();var Cd=null;function NJ(){return k.TELEGRAM_BOT_TOKEN?Ps().length>0:!1}async function ay(e,t){let n=e.stats.permissionMode==="autonomous",r=t!==void 0?t:!n;try{if(await e.session.current.setPermissionMode(r?"autonomous":"default"),e.stats.permissionMode=r?"autonomous":"default",e.ui.repaintStatusLine(),r){l_();let o=e.session.current,s=o.sessionId,i=e.swapElicitationHandler,a=e.stdinElicitationHandler;if(s&&i&&a){let l=f_(s),c=k_({sessionId:s,key:l,emitElicitation:u=>o.recordLedgerElicitation(u.reqId,u.request),fallback:a});i(c),Cd?.stop(),Cd=v_({sessionId:s,key:l,onAbort:u=>o.abort(u)}),Rf(s,!0)}e.out.success(m.info("\u25D0 AFK mode ON")+m.dim(" \u2014 autonomous on reversible work; high-risk/irreversible ops are refused; terminal states report to Telegram.")),NJ()||e.out.error("Telegram is not configured, so AFK updates will not be delivered. Run /telegram-setup to connect a chat. (AFK posture + safety gate still apply.)")}else{e.swapElicitationHandler?.(null),Cd?.stop(),Cd=null;let o=e.session.current.sessionId;o&&Rf(o,!1),e.out.success(m.success("\u25CB AFK mode OFF")+m.dim(" \u2014 default permissions restored"))}}catch(o){e.out.error(`Could not toggle AFK mode: ${o instanceof Error?o.message:String(o)}`)}}var E_={name:"/afk",usage:"/afk [on|off]",summary:"Toggle AFK mode \u2014 autonomous work + Telegram reporting while you are away",hint:"Tell the agent you are away from keyboard: it works autonomously on reversible operations, a safety gate refuses high-risk/irreversible ops, and each turn reports its terminal state to Telegram. /afk off restores default permissions.",async handler(e,t){let n=t.trim().toLowerCase(),r=n==="on"?!0:n==="off"?!1:e.stats.permissionMode!=="autonomous";return r&&e.stats.permissionMode==="autonomous"?"continue":!r&&e.stats.permissionMode!=="autonomous"?(await ay(e,!1),"continue"):(await ay(e,r),"continue")}};var BJ=m.warning("\u26A0 bypass mode ON")+m.dim(" \u2014 path-approval prompts OFF; the agent can read/write ANY path on this machine with no confirmation. Run /bypass off to restore containment. (Does not affect ask_question.)"),x_=m.success("\u25CB bypass mode OFF")+m.dim(" \u2014 default permissions restored (path containment + prompts back on)"),T_={name:"/bypass",usage:"/bypass [on|off]",summary:"Toggle bypass mode \u2014 skip path-approval prompts (DANGEROUS: read/write anywhere)",hint:"Disable path-approval prompts AND path containment for filesystem tools \u2014 the agent can touch any path with no confirmation. The agent-afk equivalent of --dangerously-skip-permissions. Does not affect ask_question. /bypass off restores containment.",async handler(e,t){let n=t.trim().toLowerCase(),r=e.stats.permissionMode==="bypassPermissions",o=n==="on"?!0:n==="off"?!1:!r;if(o&&r)return"continue";if(!o&&!r)return e.out.success(x_),"continue";try{await e.session.current.setPermissionMode(o?"bypassPermissions":"default"),e.stats.permissionMode=o?"bypassPermissions":"default",e.ui.repaintStatusLine(),o?e.out.error(BJ):e.out.success(x_)}catch(s){e.out.error(`Could not toggle bypass mode: ${s instanceof Error?s.message:String(s)}`)}return"continue"}};W();import{readFileSync as jJ,writeFileSync as UJ,existsSync as R_,mkdirSync as HJ}from"fs";import{join as KJ}from"path";function A_(){return Yw(),Am()}function C_(e){return KJ(A_(),`${e}.json`)}function _d(e){let t=C_(e);if(!R_(t))return{sessionId:e,items:[]};try{let n=jJ(t,"utf-8"),r=JSON.parse(n);return Array.isArray(r.items)?r:{sessionId:e,items:[]}}catch{return{sessionId:e,items:[]}}}function za(e){let t=A_();R_(t)||HJ(t,{recursive:!0}),UJ(C_(e.sessionId),JSON.stringify(e,null,2))}function __(e,t){let r={id:e.items.reduce((o,s)=>Math.max(o,s.id),0)+1,text:t,done:!1,createdAt:Date.now()};return e.items.push(r),r}function I_(e,t){let n=e.items.find(r=>r.id===t);return n&&(n.done=!0),n}function P_(e,t){let n=e.items.findIndex(r=>r.id===t);return n===-1?!1:(e.items.splice(n,1),!0)}function M_(e){e.items.length=0}function Id(e){if(e.items.length===0)return[];let t=[],n=Math.max(20,Q());{let r=m.dim("\u250C\u2500 todos "),o=Math.max(0,Math.min(n-10,120));t.push(r+m.dim("\u2500".repeat(o)))}for(let r of e.items){let o=r.done?m.success("[x]"):m.dim("[ ]"),s=r.done?m.dim(r.text):pr(r.text),a=` ${m.meta(`#${r.id}`)} ${o} `,l=Math.max(8,n-J(a)),c=de(s,l).split(`
1762
+ `,{mode:384}),r}catch{return u_(e)}}function u_(e){let t;try{t=$m(e)}catch{return null}try{let n=hi.readFileSync(t,"utf8").trim();return n.length>0?n:null}catch{return null}}function g_(e,t){return IJ("sha256",e).update(t).digest("hex")}function h_(e,t){if(typeof e!="string"||typeof t!="string"||e.length!==t.length||e.length===0||!/^[0-9a-f]+$/i.test(e)||!/^[0-9a-f]+$/i.test(t))return!1;let n,r;try{n=Buffer.from(e,"hex"),r=Buffer.from(t,"hex")}catch{return!1}return n.length!==r.length||n.length===0?!1:PJ(n,r)}function $J(e,t,n){return["elicitation_response",e,t,OJ(n)].join(m_)}function DJ(e,t,n,r){return g_(e,$J(t,n,r))}function y_(e,t,n,r,o){return h_(o,DJ(e,t,n,r))}function LJ(e,t){return["abort_request",e,t].join(m_)}function FJ(e,t,n){return g_(e,LJ(t,n))}function b_(e,t,n,r){return h_(r,FJ(e,t,n))}function w_(){return p_(8).toString("hex")}jh();var S_={action:"decline"};function v_(e){let{sessionId:t,key:n,onAbort:r}=e;if(n===null)return{stop:()=>{}};let o=new AbortController;return(async()=>{try{for await(let s of Bh(t,{fromStart:!1,signal:o.signal}))if(s.kind==="abort_request"&&b_(n,t,s.nonce,s.hmac)){r("remote abort via Telegram"),o.abort();return}}catch{}})(),{stop:()=>{o.abort()}}}function k_(e){let{sessionId:t,key:n,emitElicitation:r,fallback:o}=e,s=e.newReqId??w_;return function(a,l){let c=l.signal;if(c.aborted)return Promise.resolve(S_);let u=s(),d,p=new Promise(h=>{d=h}),f=new AbortController,g=()=>{f.abort(),d(S_)};c.addEventListener("abort",g,{once:!0}),n&&(async()=>{try{for await(let h of Bh(t,{fromStart:!1,signal:f.signal}))if(h.kind==="elicitation_response"&&h.reqId===u&&y_(n,t,u,h.result,h.hmac)){d(h.result);return}}catch{}})();try{r({kind:"elicitation",reqId:u,request:a})}catch{}return Promise.resolve(o(a,{signal:f.signal})).then(h=>d(h)).catch(()=>{}),p.finally(()=>{f.abort(),c.removeEventListener("abort",g)})}}aa();var Cd=null;function NJ(){return k.TELEGRAM_BOT_TOKEN?Ps().length>0:!1}async function ay(e,t){let n=e.stats.permissionMode==="autonomous",r=t!==void 0?t:!n;try{if(await e.session.current.setPermissionMode(r?"autonomous":"default"),e.stats.permissionMode=r?"autonomous":"default",e.ui.repaintStatusLine(),r){l_();let o=e.session.current,s=o.sessionId,i=e.swapElicitationHandler,a=e.stdinElicitationHandler;if(s&&i&&a){let l=f_(s),c=k_({sessionId:s,key:l,emitElicitation:u=>o.recordLedgerElicitation(u.reqId,u.request),fallback:a});i(c),Cd?.stop(),Cd=v_({sessionId:s,key:l,onAbort:u=>o.abort(u)}),Rf(s,!0)}e.out.success(m.info("\u25D0 AFK mode ON")+m.dim(" \u2014 autonomous on reversible work; high-risk/irreversible ops are refused; terminal states report to Telegram.")),NJ()||e.out.error("Telegram is not configured, so AFK updates will not be delivered. Run /telegram-setup to connect a chat. (AFK posture + safety gate still apply.)")}else{e.swapElicitationHandler?.(null),Cd?.stop(),Cd=null;let o=e.session.current.sessionId;o&&Rf(o,!1),e.out.success(m.success("\u25CB AFK mode OFF")+m.dim(" \u2014 default permissions restored"))}}catch(o){e.out.error(`Could not toggle AFK mode: ${o instanceof Error?o.message:String(o)}`)}}var E_={name:"/afk",usage:"/afk [on|off]",summary:"Toggle AFK mode \u2014 autonomous work + Telegram reporting while you are away",hint:"Tell the agent you are away from keyboard: it works autonomously on reversible operations, a safety gate refuses high-risk/irreversible ops, and each turn reports its terminal state to Telegram. /afk off restores default permissions.",async handler(e,t){let n=t.trim().toLowerCase(),r=n==="on"?!0:n==="off"?!1:e.stats.permissionMode!=="autonomous";return r&&e.stats.permissionMode==="autonomous"?"continue":!r&&e.stats.permissionMode!=="autonomous"?(await ay(e,!1),"continue"):(await ay(e,r),"continue")}};var BJ=m.bypass("\u26A1 BYPASS ON")+m.dim(" \u2014 full-power mode: path-approval prompts OFF; the agent can read/write ANY path on this machine with no confirmation. Run /bypass off to restore containment. (Does not affect ask_question.)"),x_=m.success("\u25CB BYPASS OFF")+m.dim(" \u2014 default permissions restored (path containment + prompts back on)"),T_={name:"/bypass",usage:"/bypass [on|off]",summary:"Toggle bypass mode \u2014 skip path-approval prompts (DANGEROUS: read/write anywhere)",hint:"Disable path-approval prompts AND path containment for filesystem tools \u2014 the agent can touch any path with no confirmation. The agent-afk equivalent of --dangerously-skip-permissions. Does not affect ask_question. /bypass off restores containment.",async handler(e,t){let n=t.trim().toLowerCase(),r=e.stats.permissionMode==="bypassPermissions",o=n==="on"?!0:n==="off"?!1:!r;if(o&&r)return"continue";if(!o&&!r)return e.out.success(x_),"continue";try{await e.session.current.setPermissionMode(o?"bypassPermissions":"default"),e.stats.permissionMode=o?"bypassPermissions":"default",e.ui.repaintStatusLine(),o?e.out.line(BJ):e.out.success(x_)}catch(s){e.out.error(`Could not toggle bypass mode: ${s instanceof Error?s.message:String(s)}`)}return"continue"}};W();import{readFileSync as jJ,writeFileSync as UJ,existsSync as R_,mkdirSync as HJ}from"fs";import{join as KJ}from"path";function A_(){return Yw(),Am()}function C_(e){return KJ(A_(),`${e}.json`)}function _d(e){let t=C_(e);if(!R_(t))return{sessionId:e,items:[]};try{let n=jJ(t,"utf-8"),r=JSON.parse(n);return Array.isArray(r.items)?r:{sessionId:e,items:[]}}catch{return{sessionId:e,items:[]}}}function za(e){let t=A_();R_(t)||HJ(t,{recursive:!0}),UJ(C_(e.sessionId),JSON.stringify(e,null,2))}function __(e,t){let r={id:e.items.reduce((o,s)=>Math.max(o,s.id),0)+1,text:t,done:!1,createdAt:Date.now()};return e.items.push(r),r}function I_(e,t){let n=e.items.find(r=>r.id===t);return n&&(n.done=!0),n}function P_(e,t){let n=e.items.findIndex(r=>r.id===t);return n===-1?!1:(e.items.splice(n,1),!0)}function M_(e){e.items.length=0}function Id(e){if(e.items.length===0)return[];let t=[],n=Math.max(20,Q());{let r=m.dim("\u250C\u2500 todos "),o=Math.max(0,Math.min(n-10,120));t.push(r+m.dim("\u2500".repeat(o)))}for(let r of e.items){let o=r.done?m.success("[x]"):m.dim("[ ]"),s=r.done?m.dim(r.text):pr(r.text),a=` ${m.meta(`#${r.id}`)} ${o} `,l=Math.max(8,n-J(a)),c=de(s,l).split(`
1763
1763
  `);t.push(a+(c[0]??""));let u=" ".repeat(J(a));for(let d of c.slice(1))t.push(u+d)}{let r=Math.max(0,Math.min(n-1,120));t.push(m.dim("\u2514"+"\u2500".repeat(r)))}return t}function O_(e){return e.items.length===0?"":e.items.map(t=>`${t.id}:${t.done?1:0}:${t.text}`).join(`
1764
1764
  `)}function $_(e){let t=e.stats.sessionId??"unbound";return _d(t)}function WJ(e){let t=$_(e),n=Id(t);if(n.length===0){e.out.info("No todos yet. Try /todo add buy milk");return}for(let r of n)e.out.line(r)}var D_={name:"/todo",usage:"/todo [add|done|rm|clear|list] ...",summary:"Manage this session's todo list",hint:"When you want a durable checklist the model and you both see \u2014 survives across turns and shows above each prompt.",async handler(e,t){let n=t.trim();if(!n||n==="list")return WJ(e),"continue";let[r,...o]=n.split(/\s+/),s=o.join(" "),i=$_(e);switch(r){case"add":{if(!s)return e.out.warn("Usage: /todo add <text>"),"continue";let a=__(i,s);return za(i),e.out.success(`Added ${m.meta(`#${a.id}`)} ${a.text}`),"continue"}case"done":{let a=parseInt(s,10);if(!Number.isFinite(a))return e.out.warn("Usage: /todo done <id>"),"continue";let l=I_(i,a);return l?(za(i),e.out.success(`Marked done ${m.meta(`#${a}`)} ${l.text}`)):e.out.warn(`No todo with id ${a}`),"continue"}case"rm":case"remove":{let a=parseInt(s,10);return Number.isFinite(a)?(P_(i,a)?(za(i),e.out.success(`Removed ${m.meta(`#${a}`)}`)):e.out.warn(`No todo with id ${a}`),"continue"):(e.out.warn("Usage: /todo rm <id>"),"continue")}case"clear":return M_(i),za(i),e.out.success("All todos cleared."),"continue";default:return e.out.warn(`Unknown subcommand: ${r}. Try /todo add, done, rm, clear, list.`),"continue"}}};var L_={name:"/save",usage:"/save [name]",hint:"Checkpoint now (sessions already autosave each turn). Pass a name to label it \u2014 /name is the primary rename command.",summary:"Save this session to disk (for /resume)",async handler(e,t){if(e.stats.totalTurns===0)return e.out.warn("Nothing to save \u2014 no turns in this session yet."),"continue";let n=t.trim();if(n){let r=pi(n);r?e.stats.name=r:e.out.warn("Ignoring invalid name \u2014 use letters, numbers, spaces, or hyphens.")}try{let r=wn(e.stats);e.out.success(m.success("Saved")+m.dim(` ${r}`));let o=e.stats.name??e.stats.sessionId;o&&e.out.line(m.dim(` Resume: ${Sn(o,e.stats.model)}`))}catch(r){e.out.error(`Could not save: ${r instanceof Error?r.message:String(r)}`)}return"continue"}};var F_={name:"/name",usage:"/name [name]",hint:"When you want a memorable handle for this session so /resume and --resume can find it by name instead of a UUID.",summary:"Show or set this session\u2019s name",async handler(e,t){let n=t.trim();if(!n)return e.stats.name?e.out.line(m.dim(" name ")+m.warning(e.stats.name)):e.out.info("No name set. Use /name <name> to set one."),"continue";let r=pi(n);if(!r)return e.out.warn("Invalid name \u2014 use letters, numbers, spaces, or hyphens."),"continue";if(e.stats.name=r,e.stats.totalTurns>0)try{wn(e.stats),e.out.success(m.success("Named")+m.dim(` ${r}`)),e.out.line(m.dim(` Resume: ${Sn(r,e.stats.model)}`))}catch(o){e.out.error(`Named "${r}" but save failed: ${o instanceof Error?o.message:String(o)}`)}else e.out.success(m.success("Named")+m.dim(` ${r} (saves on first turn)`));return"continue"}};function GJ(e){if(typeof e!="number"||!Number.isFinite(e))return" \u2014 ";let t=new Date(e);return Number.isNaN(t.getTime())?" \u2014 ":t.toISOString().replace("T"," ").slice(0,16)}function zJ(e){return{id:e.id,resumeId:e.data.sessionId??e.id,stored:e.data}}var N_={name:"/resume",usage:"/resume [id]",hint:"When you want to continue a previously /saved session \u2014 runs interactively to pick one if no id is given.",summary:"List saved sessions, or swap the active session for a stored one",async handler(e,t){let n=t.trim();if(n){let c=ci(n);if(!c)return e.out.warn(`No saved session: ${n}`),"continue";let u=c.data.name??c.id;if(typeof e.requestResume=="function"){let f=e.session.current.sessionId,g=c.data.sessionId;if(f!==void 0&&g!==void 0&&f===g||f!==void 0&&f===c.id)return e.out.warn(`Already on session ${u}.`),"continue";e.out.info(`Resuming session ${u} \u2026`);let b=await e.requestResume(zJ(c));return b.ok?e.out.success(`Resumed ${u} (sdk id: ${b.sessionId})`):e.out.warn(b.reason),"continue"}let d=c.data,p=d.name??d.sessionId??c.id;return e.out.line(),e.out.line(m.bold(`Session ${d.name??c.id}`)),e.out.line(me()),e.out.line(` name ${m.brand(d.name??"\u2014")}`),e.out.line(` source ${m.brand(d.source??"cli")}`),e.out.line(` model ${m.brand(d.model)}`),e.out.line(` turns ${m.meta(String(d.totalTurns))}`),e.out.line(` cost ${m.meta(Xe(d.totalCostUsd))}`),e.out.line(` sdk id ${m.meta(d.sessionId??"\u2014")}`),e.out.line(),e.out.line(m.dim(" Resume with:")),e.out.line(m.brand(` ${Sn(p,d.model)}`)),e.out.line(),"continue"}let r=Ua();if(r.length===0)return e.out.info("No saved sessions found. Use /save first."),"continue";let o=e.stats.cwd??process.cwd(),s=r.filter(c=>c.cwd===o),i=s.length>0,a=i?s:r,l=i?m.bold(`Saved sessions (${a.length})`):m.bold("Saved sessions \u2014 all (none in this directory)");e.out.line(),e.out.line(l),e.out.line(me());for(let c of a.slice(0,20)){let u=GJ(c.savedAt),d=m.brand(c.model.padEnd(7)),p=m.meta(`${c.totalTurns} turn${c.totalTurns===1?"":"s"}`.padEnd(9)),f=m.meta(Xe(c.totalCostUsd).padStart(8)),g=c.source==="telegram"?m.brand("tg"):" ",h=m.warning(c.name??c.id);e.out.line(` ${u} ${d} ${p} ${f} ${g} ${h}`)}return e.out.line(),e.out.line(m.dim(" Resume with: /resume <name>")),e.out.line(),"continue"}};import{spawnSync as qJ}from"node:child_process";function JJ(e){switch(e){case"darwin":return[{cmd:"pbcopy",args:[]}];case"win32":return[{cmd:"clip",args:[]}];default:return[{cmd:"wl-copy",args:[]},{cmd:"xclip",args:["-selection","clipboard"]},{cmd:"xsel",args:["--clipboard","--input"]}]}}function B_(e,t=process.platform){for(let n of JJ(t))try{let r=qJ(n.cmd,n.args,{input:e});if(!r.error&&r.status===0)return!0}catch{}return!1}import{spawnSync as QJ}from"node:child_process";function qa(e=process.env){if(e.TMUX)return"tmux";if(e.KITTY_WINDOW_ID)return"kitty";if(e.WEZTERM_PANE)return"wezterm";if(e.WT_SESSION)return"windows-terminal";if(e.KONSOLE_DBUS_SERVICE)return"konsole";if(e.GNOME_TERMINAL_SCREEN)return"gnome-terminal";let t=e.TERM_PROGRAM;if(t==="iTerm.app")return"iterm2";if(t==="Apple_Terminal")return"apple-terminal";if(t==="vscode")return"vscode";if(t==="Hyper")return"hyper";let n=e.TERM;return n==="xterm-ghostty"||e.GHOSTTY_RESOURCES_DIR?"ghostty":n==="alacritty"?"alacritty":e.VTE_VERSION?"gnome-terminal":"unknown"}import{resolve as VJ}from"node:path";function ly(e,t,n){let r=VJ(process.argv[1]??""),o=[process.execPath,r,"interactive"];typeof t=="string"&&t.length>0&&o.push("--model",t),o.push("--resume",e);let s=o.map(Ka).join(" "),i=r.length>0&&!r.endsWith(".ts");return{argv:o,shellCommand:s,cwd:n,spawnable:i}}function Pd(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function j_(e){return`cd ${Ka(e.cwd)} && ${e.shellCommand}`}function YJ(e){return`tell application "iTerm" to tell current window to create tab with default profile command "${Pd(j_(e))}"`}function XJ(e){return`tell application "Terminal" to do script "${Pd(j_(e))}"`}function ZJ(e){return['tell application "Ghostty"',"set cfg to new surface configuration",`set command of cfg to "${Pd(e.shellCommand)}"`,`set initial working directory of cfg to "${Pd(e.cwd)}"`,"new tab in (front window) with configuration cfg","end tell"].join(`
1765
1765
  `)}function cy(e,t,n=process.platform){switch(e){case"tmux":return{kind:e,capability:"tab",exec:{cmd:"tmux",args:["new-window","-c",t.cwd,t.shellCommand]}};case"wezterm":return{kind:e,capability:"tab",exec:{cmd:"wezterm",args:["cli","spawn","--cwd",t.cwd,"--",...t.argv]}};case"kitty":return{kind:e,capability:"tab",exec:{cmd:"kitten",args:["@","launch","--type=tab",`--cwd=${t.cwd}`,...t.argv]}};case"windows-terminal":return{kind:e,capability:"tab",exec:{cmd:"wt",args:["-w","0","new-tab","-d",t.cwd,...t.argv]}};case"iterm2":return{kind:e,capability:"tab",exec:{cmd:"osascript",args:["-e",YJ(t)]}};case"apple-terminal":return{kind:e,capability:"window",exec:{cmd:"osascript",args:["-e",XJ(t)]}};case"ghostty":return n==="darwin"?{kind:e,capability:"tab",exec:{cmd:"osascript",args:["-e",ZJ(t)]}}:{kind:e,capability:"none"};case"gnome-terminal":return{kind:e,capability:"tab",exec:{cmd:"gnome-terminal",args:["--tab",`--working-directory=${t.cwd}`,"--",...t.argv]}};case"konsole":return{kind:e,capability:"tab",exec:{cmd:"konsole",args:["--new-tab","--workdir",t.cwd,"-e",...t.argv]}};case"vscode":case"alacritty":case"hyper":case"unknown":return{kind:e,capability:"none"}}}var eV=5e3,tV=(e,t,n)=>{let r=QJ(e,t,n);return{status:r.status,...r.error?{error:r.error}:{}}};function U_(e){let t=e.env??process.env,n=e.platform??process.platform,r=e.run??tV,o=qa(t);if(!e.interactive)return{spawned:!1,kind:o,capability:"none",reason:"non-interactive-surface"};let s=ly(e.forkId,e.model,e.cwd);if(!s.spawnable)return{spawned:!1,kind:o,capability:"none",reason:"dev-entrypoint"};let i=cy(o,s,n);if(i.capability==="none"||!i.exec)return{spawned:!1,kind:o,capability:i.capability,reason:"no-tab-mechanism"};try{let a=r(i.exec.cmd,i.exec.args,{stdio:"ignore",timeout:eV});if(a.error||a.status!==0){let l=a.error?a.error.message:`exited ${a.status}`;return{spawned:!1,kind:o,capability:i.capability,reason:l}}return{spawned:!0,kind:o,capability:i.capability}}catch(a){return{spawned:!1,kind:o,capability:i.capability,reason:a instanceof Error?a.message:String(a)}}}var nV={tmux:"tmux",wezterm:"WezTerm",kitty:"kitty",iterm2:"iTerm","apple-terminal":"Terminal",ghostty:"Ghostty","windows-terminal":"Windows Terminal","gnome-terminal":"GNOME Terminal",konsole:"Konsole",vscode:"VS Code",alacritty:"Alacritty",hyper:"Hyper",unknown:"this terminal"};function rV(e,t,n){let r=[];if(e.spawned){let o=e.capability==="window"?"window":"tab";r.push(m.info(` \u2197 Continuing in a new ${nV[e.kind]} ${o}.`)),r.push(m.dim(" Or run it yourself:"))}else e.kind==="vscode"&&e.reason==="no-tab-mechanism"?r.push(m.dim(" VS Code's integrated terminal can't be opened from outside \u2014 run this in a new terminal:")):r.push(m.dim(" Continue the fork with:"));return r.push(m.brand(` ${t}`)),n&&r.push(m.dim(" (copied to clipboard)")),r.push(""),r.push(m.meta(" This session continues here, untouched. The fork carries the")),r.push(m.meta(" conversation only \u2014 live subagents and background jobs are not forked.")),r}var H_={name:"/fork",aliases:["/branch"],usage:"/fork",hint:"When you want to explore a divergent path without losing this thread \u2014 duplicates the conversation into a new resumable session you can continue in parallel.",summary:"Duplicate this conversation into a new, independent session",async handler(e){if(e.stats.totalTurns===0)return e.out.warn("Nothing to fork yet \u2014 no turns in this session."),"continue";let t,n;try{({id:t,path:n}=SC(e.stats))}catch(l){return e.out.error(`Could not fork: ${l instanceof Error?l.message:String(l)}`),"continue"}let r=Sn(t,e.stats.model),o=e.stats.cwd??process.cwd(),s=typeof e.requestResume=="function"&&process.stdout.isTTY===!0,i=U_({forkId:t,model:e.stats.model,cwd:o,interactive:s}),a=!i.spawned&&B_(r);e.out.success(m.success("Forked")+m.dim(` ${n}`)),e.out.line();for(let l of rV(i,r,a))e.out.line(l);return e.out.line(),"continue"}};import{existsSync as uV,readFileSync as dV}from"node:fs";import{resolve as q_}from"node:path";import{execFileSync as K_}from"node:child_process";import{readFileSync as oV,writeFileSync as sV}from"node:fs";import{resolve as iV}from"node:path";var aV={feat:"Added",fix:"Fixed",refactor:"Changed",perf:"Changed",docs:"Changed",chore:"Changed",ci:"Changed",test:"Changed","test+fix":"Fixed",build:"Changed",style:"Changed"},lV=["Added","Fixed","Changed","Deprecated","Removed","Security"];function W_(e){let t;try{t=K_("git",["describe","--tags","--abbrev=0"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{t=""}let n=t?["log",`${t}..HEAD`,"--format=%h %s"]:["log","-50","--format=%h %s"],r=K_("git",n,{cwd:e,encoding:"utf8"}).trim();return r?r.split(`
@@ -1829,8 +1829,8 @@ ${u}`}function fy(e,t){let n=X_[t.status];e.out.line(` ${n} ${m.bold(t.jobId)}
1829
1829
  `,s=mY(r,n,{trim:!1,hard:!0,wordWrap:!1}).split(`
1830
1830
  `);for(;s.length>0&&s[s.length-1]==="";)s.pop();return s}measure(t,n){let r=this.stream.columns??80,o=Math.max(1,e.wrapToPhysicalLines(t,r).length),s=Math.max(1,n);return{topRow:Math.max(1,s-o+1),lineCount:o}}render(t,n,r){let o=Math.max(1,n),s=Math.max(1,r??1),i=this.stream.columns??80,a=this.stream.isTTY===!0,l=e.wrapToPhysicalLines(t,i),c=Math.max(1,l.length),u=this.previousRawLineCount>c?this.previousRawLineCount-c:0,d=Math.max(0,o-c+1-s),p=Math.min(u,d),f=p>0?[...Array(p).fill(""),...l]:l,g=f.length,h=Math.max(1,o-g+1),b="";if(a&&(b+=QI),this.previousLineCount>0)for(let y=0;y<this.previousLineCount;y++){let S=this.previousTopRow+y;b+=Qa(S,1)+Ty}for(let y=0;y<g;y++){let S=h+y;b+=Qa(S,1)+Ty+(f[y]??"")}if(b+=Qa(h+g-1,1),a&&(b+=eP),this.stream.isTTY)try{this.stream.write(fY)}catch{}try{this.stream.write(b)}catch{try{this.stream.isTTY&&this.stream.write(tP)}catch{}}if(k.NODE_ENV!=="production"&&g<c)throw new Error(`CupFrameRenderer invariant violation: lineCount (${g}) < rawLineCount (${c}). previousLineCount must cover at least previousRawLineCount \u2014 padded footprint must be \u2265 raw content size; see PR #557.`);this.previousTopRow=h,this.previousLineCount=g,this.previousRawLineCount=c}resetGeometry(){this.previousTopRow=0,this.previousLineCount=0,this.previousRawLineCount=0}clear(t=0){if(this.previousLineCount===0)return;let n="",r=this.stream.isTTY===!0;r&&(n+=QI);for(let o=0;o<this.previousLineCount;o++){let s=this.previousTopRow+o;n+=Qa(s,1)+Ty}n+=Qa(Math.max(1,(this.stream.rows??24)-1-t),1),r&&(n+=eP);try{this.stream.write(n)}catch{}this.previousTopRow=0,this.previousLineCount=0,this.previousRawLineCount=0}done(){if(this.previousTopRow=0,this.previousLineCount=0,this.previousRawLineCount=0,this.stream.isTTY)try{this.stream.write(tP)}catch{}}};var el=null;function tl(e){if(el!==null)throw new Error(`stdin claim conflict: '${el.name}' already holds the claim, '${e}' cannot acquire it concurrently.`);let t=!1,n={release(){t||(t=!0,el?.handle===n&&(el=null))}};return el={name:e,handle:n},n}async function nP(e,t){let n=tl(e);try{return await t()}finally{n.release()}}function rP(e){if(!(!e.armed||e.suspended)){if(e.logUpdate)try{e.logUpdate.clear(e.scrollRegion?.getExtraRows()??0),e.logUpdate.done()}catch{}e.handleKeypress&&e.stdin.removeListener("keypress",e.handleKeypress);try{e.stdin.setRawMode(!1)}catch{}e.suspended=!0}}function oP(e){if(!(!e.armed||!e.suspended)){try{e.stdin.setRawMode(!0)}catch{}e.handleKeypress&&e.stdin.on("keypress",e.handleKeypress),e.suspended=!1,e.repaint()}}async function sP(e){if(e.armed)throw new Error("TerminalCompositor: arm() called while already armed");if(!(!e.stdout.isTTY||!e.stdin.isTTY)){e.anchorRow=e.declaredAnchorRow,e.logUpdate||(e.logUpdate=new Gd(e.stdout)),e.stdinClaim=tl("TerminalCompositor.arm"),e.wasRaw=e.stdin.isRaw??!1;try{e.stdin.setRawMode(!0)}catch{e.stdinClaim?.release(),e.stdinClaim=null,e.logUpdate=null,e.wasRaw=!1;return}try{e.stdout.write("\x1B[?2004h")}catch{}e.stdin.resume(),xo(e.stdin),e.handleKeypress=(t,n)=>XI(e,t,n),e.stdin.on("keypress",e.handleKeypress),e.armed=!0,e.canceled=!1,e.resizeUnsub=Le.subscribe(()=>{e.armed&&e.repaint()}),e.resizeImmediateUnsub=Le.subscribeImmediate(()=>{if(!e.armed)return;let t=e.stdout.rows??24;if(e.lastKnownRows>0&&t>e.lastKnownRows){let n=e.scrollRegion?.getExtraRows()??0,r=e.logUpdate?.topRow??0,o=e.committedBand.length>0?e.committedBandTopRow:0,s=[r,o].filter(l=>l>0),i=s.length>0?Math.min(...s):0,a=Math.max(1,e.lastKnownRows-1-n);i>0&&i<=a&&(e.pendingResizeErase={top:i,bottom:a})}else e.pendingResizeErase=null;e.logUpdate?.resetGeometry?.()}),e.repaint()}}function iP(e){if(e.spinnerController.dispose(),!e.armed){e.resetState();return}if(e.handleKeypress&&(e.stdin.removeListener("keypress",e.handleKeypress),e.handleKeypress=null),e.resizeUnsub&&(e.resizeUnsub(),e.resizeUnsub=null),e.resizeImmediateUnsub&&(e.resizeImmediateUnsub(),e.resizeImmediateUnsub=null),gY(e),e.logUpdate)try{e.logUpdate.clear(e.scrollRegion?.getExtraRows()??0),e.logUpdate.done()}catch{}if(e.stdout.isTTY&&e.stdin.isTTY){try{e.stdout.write("\x1B[?2004l")}catch{}try{e.stdin.setRawMode(e.wasRaw)}catch{}}e.stdinClaim&&(e.stdinClaim.release(),e.stdinClaim=null),e.armed=!1,e.resetState(),e.ghostEngine?.dispose()}function gY(e){let t=e.committedBand.length-e.committedBandPaintedRows;if(t<=0)return;let n=e.committedBand.slice(0,t),r=Math.max(1,e.stdout.rows??24),o=Math.max(e.anchorRow??1,1),s=()=>{let i=Math.max(1,r-o+1);for(let a=0;a<n.length;a+=i){let l=n.slice(a,Math.min(a+i,n.length)),c=l.map((u,d)=>mt(o+d,u)).join("");e.stdout.write(`${c}\x1B[${r};1H${`
1831
1831
  `.repeat(l.length)}`)}};try{e.scrollRegion?e.scrollRegion.withFullScrollRegion(s):s()}catch{}}function aP(e){e.overlay="",e.input=K.seed(""),e.queued=!1,e.pendingSubmissions=[],e.canceled=!1,e.backgrounded=!1,e.softStopped=!1,e.paused=!1,e.activeGhost=null,e.anchorRow=void 0,e.hasCommitted=!1,e.clearCommittedBand(),e.commitInFlight=!1,e.pendingResizeErase=null,e.lastKnownRows=0,e.pickerController=null,e.inputMode="streaming",e.attachments=[],e.pasting=!1,e.pasteStartBufferLen=0,e.pasteStartCursor=0,e.pasteRegistry.clear(),e.clipboardFailureMsg=null,e.autocompleteState?.reset(),e.resizeUnsub&&(e.resizeUnsub(),e.resizeUnsub=null),e.resizeImmediateUnsub&&(e.resizeImmediateUnsub(),e.resizeImmediateUnsub=null)}var Si=class{stdout;stdin;onCancel;onSoftStop;softStopped=!1;onBackground;onPauseInterrupt;onShiftTab;promptTextFn;history;autocompleteState;formatInputBuffer;scrollRegion;anchorRow;declaredAnchorRow;onSubmit;attachments=[];pasting=!1;pasteStartBufferLen=0;pasteStartCursor=0;pasteRegistry=new Map;clipboardInFlight=!1;clipboardFailureMsg=null;inputMode="streaming";pickerController=null;pickerSavedMode="streaming";armed=!1;suspended=!1;canceled=!1;backgrounded=!1;paused=!1;wasRaw=!1;stdinClaim=null;logUpdate=null;overlay="";input=K.seed("");queued=!1;pendingSubmissions=[];handleKeypress=null;resizeUnsub=null;resizeImmediateUnsub=null;spinnerController;committing=!1;hasCommitted=!1;committedBand=[];committedBandTopRow=0;committedBandBottomRow=0;committedBandPaintedRows=0;lastKnownRows=0;pendingResizeErase=null;commitInFlight=!1;debugCompositor=!!k.AFK_DEBUG_COMPOSITOR;ghostEngine;ghostGetContext;activeGhost=null;debugLog(t,n={}){if(!this.debugCompositor)return;let r=process.hrtime.bigint(),o=Object.entries(n).map(([s,i])=>{let a=typeof i=="string"?JSON.stringify(i.length>60?i.slice(0,57)+"...":i):String(i);return`${s}=${a}`}).join(" ");process.stderr.write(`[compositor] t=${r} ${t}${o?" "+o:""}
1832
- `)}constructor(t){this.stdout=t.stdout,this.stdin=t.stdin,this.onCancel=t.onCancel,this.onSoftStop=t.onSoftStop,this.onBackground=t.onBackground,this.onPauseInterrupt=t.onPauseInterrupt,this.onShiftTab=t.onShiftTab;let n=t.promptText;if(typeof n=="function")this.promptTextFn=n;else if(typeof n=="string")this.promptTextFn=()=>n;else{let r=" "+m.dim("\u23AF")+" ";this.promptTextFn=()=>r}this.history=t.history,this.autocompleteState=t.autocompleteState,this.formatInputBuffer=t.formatInputBuffer,this.scrollRegion=t.scrollRegion,this.spinnerController=new Fd({captureMode:t.captureMode??!1,onTick:()=>this.repaint()}),this.onSubmit=t.onSubmit,this.anchorRow=t.anchorRow,this.declaredAnchorRow=t.anchorRow,this.ghostEngine=t.suggest?.engine,this.ghostGetContext=t.suggest?.getContext}isArmed(){return this.armed}setAnchorRow(t){this.anchorRow=t,this.declaredAnchorRow=t}suspendInput(){rP(this)}resumeInput(){oP(this)}setOnSubmit(t){this.onSubmit=t??void 0}setOnCancel(t){this.onCancel=t??void 0}getOnCancel(){return this.onCancel}setOnSoftStop(t){this.onSoftStop=t??void 0}setOnBackground(t){this.onBackground=t??void 0}setOnShiftTab(t){this.onShiftTab=t??void 0}enterPickerMode(t){jI(this,t)}exitPickerMode(){UI(this)}repaintPicker(){HI(this)}setInputMode(t){KI(this,t)}getInputMode(){return WI(this)}async arm(){return sP(this)}disarm(){iP(this)}setOverlay(t){t!==this.overlay&&(this.debugLog("setOverlay",{framesLen:t.length,anchorRow:this.anchorRow??null}),this.overlay=t,this.repaint())}setSpinner(t){this.stdout.isTTY&&this.spinnerController.set(t)}commitAbove(t){OI(this,t)}clearCommittedBand(){Xa(this)}flushResizeGhostErase(){DI(this)}resetCommittedBand(){$I(this)}repositionCommittedBand(t,n,r){LI(this,t,n,r)}getBuffer(){return fI(this)}getPendingCount(){return this.pendingSubmissions.length}getAttachments(){return[...this.attachments]}renderInputLine(){return _I(this)}updateAutocomplete(){Hd(this)}updateGhost(){TI(this)}renderDropdownRows(){return II(this)}renderHintRow(){return PI(this)}repaint(){BI(this)}resetState(){aP(this)}applyEdit(t){return YI(this,t)}applyDropdownSelection(){return RI(this)}applyGhostAccept(){return AI(this)}};import bY from"chalk";var wY=/(?<=\s|^)(\/[A-Za-z][\w:-]*)(?=\s|$)/g,SY=/(?<=\s|^)(@[~\w./-]*)(?=\s|$)/g,vY=/\[Pasted text #[0-9a-f]+ \+\d+ (?:lines|chars)\]/g,lP={mint:m.mint};function kY(e){let t=lP[e];if(t)return t;let n=e.lastIndexOf(":");if(n>=0){let r=e.slice(n+1),o=lP[r];if(o)return o}return null}function Nr(e,t){return bY.level===0?e:e.replace(wY,o=>{let s=o.slice(1);return t.has(s)?(kY(s)??m.brand)(o):m.meta(o)}).replace(SY,o=>m.fileRef(o)).replace(vY,o=>m.meta(o))}G();import{pathToFileURL as EY}from"node:url";var xY="\x1B]8;;\x1B\\",TY=new Set(["iterm2","wezterm","kitty","vscode","ghostty","windows-terminal","konsole","gnome-terminal","alacritty"]),RY=5e3;function AY(e=process.env,t=process.stdout.isTTY===!0){let n=e.FORCE_HYPERLINK;if(n!==void 0&&n.length>0)return n!=="0"&&n.toLowerCase()!=="false";if(!t||e.CI!==void 0&&e.CI.length>0)return!1;let r=qa(e);if(!TY.has(r))return!1;if(r==="gnome-terminal"&&e.VTE_VERSION!==void 0){let o=Number.parseInt(e.VTE_VERSION,10);if(!Number.isFinite(o)||o<RY)return!1}return!0}var Ry;function zd(){return Ry===void 0&&(Ry=AY()),Ry}function CY(e,t){return`\x1B]8;;${t}\x1B\\${e}${xY}`}function qd(e,t){try{return CY(e,EY(t).href)}catch{return e}}var cP=/[\x00-\x1F\x7F-\x9F]/g;function tt(e){return $e(e).replace(cP," ").replace(/ {2,}/g," ").trim()}function Ay(e){return $e(e).replace(cP," ")}function nl(e){let t=/[a-z][a-z0-9+.-]*:\/\/[^\s<>\"`]+/gi,n="",r=0;for(let o of e.matchAll(t)){let s=o[0]??"",i=o.index??r;n+=uP(e.slice(r,i)),n+=s,r=i+s.length}return n+=uP(e.slice(r)),n}function uP(e){let t=zd();return e.replace(/\/(?:[^/\s,)]+\/){2,}([^/\s,)]+)/g,(n,r)=>t?qd(r,n):r)}function _Y(e){let t=/^(\s*[("]?\s*)cd\s+\S+\s+&&\s+(?!cd\s)(.+)$/.exec(e);return t?(t[1]??"")+(t[2]??""):e}var dP=60;function Cy(e,t){let n=e.trim().replace(/^\((.*)\)$/s,"$1"),r;try{r=JSON.parse(n)}catch{return e}if(!r||typeof r!="object")return e;let o=r;for(let s of t){let i=o[s];if(typeof i=="string"&&i.length>0){let a=tt(i);if(a.length===0)continue;return`(${a.length>dP?ie(a,dP,"\u2026"):a})`}}return e}function pP(e,t){if(e==="bash"||e==="Bash")return _Y(t);if(e==="compose"||e==="Compose"){let n=t.trim().replace(/^\((.*)\)$/s,"$1");try{let r=JSON.parse(n);if(r&&typeof r=="object"){let o=Array.isArray(r.nodes)?r.nodes.length:void 0,s=Array.isArray(r.edges)?r.edges.length:0;if(o!==void 0){let i=`${o} node${o===1?"":"s"}`,a=s>0?`, ${s} edge${s===1?"":"s"}`:"";return`(${i}${a})`}}}catch{}}return e==="agent"||e==="Agent"?Cy(t,["id_prefix","prompt"]):e==="Task"?Cy(t,["description","prompt"]):e==="skill"||e==="Skill"?Cy(t,["name","arguments"]):e==="ask_question"?IY(t):t}function IY(e){let t=e.trim().replace(/^\((.*)\)$/s,"$1");try{let n=JSON.parse(t);if(!n||typeof n!="object")return e;let r=n,o=typeof r.type=="string"?r.type:"text";if(o==="choice"||o==="multi_choice"){let s=r.choices,i=Array.isArray(s)?s.length:0;return i>0?`(${o}: ${i} option${i===1?"":"s"})`:`(${o})`}return`(${o})`}catch{return e}}function PY(e){return e.replace(/[\r\n]+/g," ")}var MY={"(":")","{":"}","[":"]"};function mP(e,t,n="\u2026"){let r=e.charAt(0),o=MY[r];return!(o&&e.endsWith(o)&&e.length>=2)||J(e)<=t?ie(e,t,n):t<3?t>=2?r+o:ie(e,t,n):ie(e,t-1,n)+o}function rr(e,t){let n=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/s.exec(e);if(n){let r=n[1],o=nl(pP(r,n[2]??"")),s=fn(r),{color:i,glyph:a}=si(r),l=Ng(s),c=l?` [${l}]`:"";if(t!==void 0){let d=(a+" ").length+r.length+c.length,p=Math.max(1,t-d);o=mP(o,p)}o=PY(o);let u=i(a+" ")+i.bold(r)+m.toolArg(o);return l?u+m.dim(c):u}return m.chrome("\u25CF ")+m.toolArg(e)}G();var fP=8,Jd=30;function OY(){let e=k.AFK_DIFF_LINES;if(e===void 0)return Jd;let t=e.trim();if(!/^\d+$/.test(t))return Jd;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:Jd}function $Y(){let e=k.AFK_SHOW_DIFFS;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"}function DY(e){let t=m.diffAdd(`+${e.addedLines}`),n=m.diffRemove(`-${e.removedLines}`),r=e.hunks.length,o=m.dim(`across ${r} hunk${r===1?"":"s"}`);return`${t} ${n} ${o}`}var LY=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;function FY(e){let t=$e(e.text).replace(LY,"");return e.kind==="+"?m.diffAdd("+ "+t):e.kind==="-"?m.diffRemove("- "+t):m.dim(" "+t)}var Iy=new WeakMap;function or(e,t,n){if($Y())return[];if(e.hunks.length===0)return[];let r=t==="overlay"?fP:OY(),o=t+"|"+n+"|"+r,s=Iy.get(e);if(s!==void 0){let f=s.get(o);if(f!==void 0)return f}let i=[];i.push(n+DY(e));let a=[];for(let f of e.hunks){let g=`@@ -${f.oldStart},${f.oldLines} +${f.newStart},${f.newLines} @@`;a.push({kind:"header",text:m.diffHunk(g)});for(let h of f.lines)a.push({kind:"body",text:FY(h)})}if(r===0){for(let f of a)i.push(n+f.text);return _y(e,o,i),i}let l=0;for(let f of a)f.kind==="body"&&l++;if(l<=r){for(let f of a)i.push(n+f.text);return _y(e,o,i),i}let c=0;for(let f of a)f.kind==="header"?i.push(n+f.text):c<r&&(i.push(n+f.text),c++);let u=l-r,d=`line${u===1?"":"s"}`,p=t==="flush"?" (set AFK_DIFF_LINES=0 to expand)":"";return i.push(n+m.dim(`\u2026 +${u} more diff ${d}${p}`)),_y(e,o,i),i}function _y(e,t,n){let r=Iy.get(e);r===void 0&&(r=new Map,Iy.set(e,r)),r.set(t,n)}var NY=m.success("\u2713"),BY=m.error("\u2717");function Br(e){return e?BY:NY}var rl=3,gP=2,hP=3;function yP(e){switch(fn(e)){case"read":return"Reading\u2026";case"write":return"Writing\u2026";case"web":return"Fetching\u2026";case"shell":return"Running\u2026";default:return"Running\u2026"}}function jY(e,t){return e?e==="grep"||e==="Grep"?t===1?"match":"matches":e==="glob"||e==="Glob"?t===1?"path":"paths":t===1?"line":"lines":t===1?"line":"lines"}function sr(e,t,n=60,r){let o=e.isError?m.error:m.dim,s=t??k.HOME??"___NOHOME___";if(e.display!==void 0&&!e.isError)return o(e.display);if(e.persistedPath){let a=e.persistedPath.startsWith(s)?"~"+e.persistedPath.slice(s.length):e.persistedPath,l=zd()?qd(a,e.persistedPath):a;return o(`saved \u2192 ${l}`)}if(e.lineCount!==void 0&&e.lineCount>1)return o(`${e.lineCount} ${jY(r,e.lineCount)}`);let i=e.content.length>n?e.content.slice(0,n-3)+"\u2026":e.content;return o(tt(i))}G();function ol(e,t){if(e.length<=t)return e;let n=e.slice(0,t),r=e.slice(t),o=wP(r);return[...n,{kind:"overflow",count:r.length,text:o}]}function UY(e,t){return t<=1||e.endsWith("s")||/(sh|ch|x|z)$/i.test(e)?e:e+"s"}var HY=5,bP=60;function wP(e){let t=new Map,n=0;for(let s of e)s.kind==="group"?(t.set(s.toolName,(t.get(s.toolName)??0)+s.entries.length),n+=s.entries.length):(t.set(s.toolName,(t.get(s.toolName)??0)+1),n+=1);if(n===0)return"";if(e.length>0&&e.every(s=>We.has(s.toolName))&&new Set(e.map(s=>s.toolName)).size===1){let s=[],i=!1;for(let a of e){let c=(a.kind==="group"?a.label:a.toolInput).trim();if(!c.startsWith("(")||!c.endsWith(")")){i=!0;break}let u=c.slice(1,-1),d=tt(u);if(!d){i=!0;break}let p=d.length>bP?d.slice(0,bP-1)+"\u2026":d,f=a.kind==="group"?a.entries.length:1;s.push({display:p,entries:f})}if(!i&&s.length>0){let a=s.slice(0,HY),l=a.map(({display:p,entries:f})=>f>1?`${p} \xD7${f}`:p),c=a.reduce((p,f)=>p+f.entries,0),u=n-c,d=l.join(", ")+(u>0?` (+${u})`:"");return`\u2026 +${n} more: ${d}`}}let o=[];for(let[s,i]of t)o.push(`${i} ${UY(s,i)}`);return`\u2026 +${n} (${o.join(", ")})`}function Vd(e,t=en()){return e.map((n,r)=>({sibling:n,connector:r===e.length-1?t.lastConnector:t.midConnector}))}function Py(e,t){return t?[...e,{kind:"resultSummary",summary:t}]:e}function My(e){if(e.length===0)return[];let t=new Map;for(let o of e){let s=SP(o),i=t.get(s);i||(i=[],t.set(s,i)),i.push(o)}let n=[],r=new Set;for(let o of e){let s=SP(o),i=t.get(s);i.length>=KY(o.toolName)?r.has(s)||(n.push({kind:"group",toolName:o.toolName,label:We.has(o.toolName)?o.toolInput:"",entries:i}),r.add(s)):n.push(o)}return n}function Oy(e){let t=e.entries.length,n=e.entries.filter(a=>a.result),r=n.filter(a=>a.result.isError),o=n.length,s;if(r.length>0){let a=o-r.length,l=[];a>0&&l.push(`${a} ok`),l.push(`${r.length} error${r.length===1?"":"s"}`),s=l.join(", ")}else o===t?s=`${t} done`:o===0?s=`${t} running`:s=`${o}/${t} done`;return rr(e.toolName+e.label)+m.dim(` \xD7${t} \u2014 ${s}`)}function SP(e){return We.has(e.toolName)?e.toolName+"::"+e.toolInput:e.toolName}function KY(e){return We.has(e)?gP:hP}function vP(e,t,n,r){return e>0||t?vi([...n,!0],r):vi(n,r)}function kP(e,t){return!We.has(e.toolName)||e.headerEmitted!==!0?!1:(t.get(e.toolUseId)??[]).every(r=>r.kind==="tool"&&kP(r,t))}function Yd(e,t,n,r=Q(),o=[],s=en(),i){let a=vi(o,s),l=sl(a,s),c=e.filter(h=>h.kind==="text"),u=e.filter(h=>h.kind==="tool").filter(h=>!kP(h,t)),d=My(u),p=ol(d,rl),f=Vd(p,s);for(let{sibling:h,connector:b}of f){let y=m.dim(b),S=b===s.lastConnector;if(h.kind==="overflow")n.push(Te(l+y+m.dim(h.text),r));else if(h.kind==="group")n.push(Te(l+y+Oy(h),r));else if(h.kind==="resultSummary")n.push(Te(l+y+m.dim(h.summary),r));else{let w=h,R=t.get(w.toolUseId);if(We.has(w.toolName)&&R&&R.length>0){w.headerEmitted?n.push(Te(l+y,r)):n.push(Te(l+y+w.prefix,r));let x=i??S;if(Yd(R,t,n,r,[...o,x],s,S),w.thinkingTail){let A=sl(vi([...o,x],s),s);n.push(Te(A+m.thinking("\u2307 "+tt(w.thinkingTail)),r))}}else if(!(We.has(w.toolName)&&w.headerEmitted))if(w.result){if(n.push(Te(l+y+w.prefix+m.dim(" \u2014 ")+Br(w.result.isError)+" "+sr(w.result,void 0,60,w.toolName),r)),w.diff&&!w.result.isError){let x=l+(S?s.spineClosed:m.dim(s.spine))+" ";for(let A of or(w.diff,"overlay",x))n.push(Te(A,r))}}else{n.push(Te(l+y+w.prefix,r));let x=l+(S?s.spineClosed:m.dim(s.spine))+" ";w.thinkingTail?n.push(Te(x+m.thinking("\u2307 "+tt(w.thinkingTail)),r)):n.push(Te(x+m.dim(yP(w.toolName)),r))}}}let g=vP(u.length,!1,o,s);for(let h of c)for(let b of $y(h.text,g,s))n.push(Te(b,r))}function il(e,t,n,r,o=Q(),s=[],i=en(),a){let l=vi(s,i),c=sl(l,i),u=[],d=e.filter(S=>S.kind==="text"),p=e.filter(S=>S.kind==="tool"),f=My(p),g=ol(f,rl),h=Py(g,r),b=Vd(h,i);for(let{sibling:S,connector:w}of b){let R=m.dim(w),x=w===i.lastConnector;if(S.kind==="overflow")u.push(Te(c+R+m.dim(S.text),o));else if(S.kind==="resultSummary")u.push(Te(c+R+m.dim(S.summary),o));else if(S.kind==="group")u.push(Te(c+R+Oy(S),o));else{let A=S,T=t.get(A.toolUseId);if(We.has(A.toolName)&&T&&T.length>0){if(A.headerEmitted){let _=A.toolInput?`${A.toolName} ${tt(A.toolInput)}`:A.toolName;u.push(Te(c+R+m.dim("\u21B3 "+_),o))}else u.push(Te(c+R+A.prefix,o));let v=a??x;u.push(...il(T,t,n,void 0,o,[...s,v],i,x))}else if(A.result){if(u.push(Te(c+R+A.prefix+m.dim(" \u2014 ")+Br(A.result.isError)+" "+sr(A.result,n,60,A.toolName),o)),A.diff&&!A.result.isError){let v=c+(x?i.spineClosed:m.dim(i.spine))+" ";for(let _ of or(A.diff,"flush",v))u.push(Te(_,o))}}else u.push(Te(c+R+A.prefix,o))}}let y=vP(p.length,r!=null,s,i);for(let S of d)for(let w of $y(S.text,y,i))u.push(Te(w,o));return u}function al(e,t,n,r,o=[]){let s=en(),i=t.filter(h=>h.kind==="tool"),l=i.filter(h=>h.result).reduce((h,b)=>h+(b.result.lineCount??0),0),c=[];i.length>rl&&(c.push(`${i.length} tools`),l>0&&c.push(`${l} lines`));let u=m.dim(s.spine.repeat(o.length)),d=o,p=m.dim(s.turnRoot),f=c.length>0?u+p+e.prefix+m.dim(" \u2014 "+c.join(" \xB7 ")):u+p+e.prefix,g=il(t,n,r,e.agentResultSummary,Q(),d,s);return[f,...g].join(`
1833
- `)}function Dy(e,t=[]){let n=en(),r=m.dim(n.spine.repeat(t.length)),o=m.dim(n.turnRoot);return r+o+e.prefix}function ll(e,t,n,r,o=[]){let s=en(),i=o;return il(t,n,r,e.agentResultSummary,Q(),i,s)}function ki(e,t,n){let r=[],o=Q();for(let s of t){let i=e.get(s);if(i.length===1){let a=i[0];if(a.result){if(r.push(" "+a.prefix+m.dim(" \u2014 ")+Br(a.result.isError)+" "+sr(a.result,n,60,a.toolName)),a.diff&&!a.result.isError)for(let l of or(a.diff,"flush"," "))r.push(Te(l,o))}else r.push(" "+a.prefix)}else{r.push(EP(s,i,n));let a=i.filter(c=>c.diff&&c.result&&!c.result.isError),l=a.length>1;for(let c of a){if(l){let u=tt(c.toolInput),d=nl(u).trim()||u.trim();r.push(" "+m.dim(`\u2500\u2500 ${d} \u2500\u2500`))}for(let u of or(c.diff,"flush"," "))r.push(Te(u,o))}}}return r}function EP(e,t,n){let{color:r,glyph:o}=si(e),s=t.map(u=>nl(tt(u.toolInput)).trim()),i=r(o+" ")+r.bold(e)+m.dim(` \xD7${t.length}`)+" "+m.toolArg(s.join(", ")),a=t.filter(u=>u.result),l=a.filter(u=>u.result.isError);if(l.length>0){let u=a.length-l.length,p=a.filter(g=>!g.result.isError).map(g=>g.result.lineCount).filter(g=>g!==void 0).reduce((g,h)=>g+h,0),f=[];return p>0&&f.push(`${p} lines`),u>0&&f.push(`${u} ok`),f.push(m.error(`${l.length} error${l.length>1?"s":""}`))," "+i+m.dim(" \u2014 ")+f.join(m.dim(", "))}let c=a.map(u=>u.result?.lineCount).filter(u=>u!==void 0);if(c.length===a.length&&c.length>0){if(c.every(p=>p===c[0]))return" "+i+m.dim(` \u2014 ${c[0]} lines each`);let d=c.reduce((p,f)=>p+f,0);return" "+i+m.dim(` \u2014 ${d} lines total`)}if(a.length>0){let u=a.map(d=>sr(d.result,n,60,d.toolName));return" "+i+m.dim(" \u2014 ")+u.join(m.dim(", "))}return" "+i}function Te(e,t){return ie(e,t)}var Ly=Object.freeze({spine:"\u2502 ",spineClosed:" ",lead:" ",turnRoot:"\u25C9 ",midConnector:"\u251C\u2500 ",lastConnector:"\u2570\u2500 ",textPrefix:"\u2502 "}),WY=Object.freeze({spine:"| ",spineClosed:" ",lead:" ",turnRoot:"o ",midConnector:"+- ",lastConnector:"\\- ",textPrefix:"| "}),XTe=Ly.midConnector,ZTe=Ly.lastConnector;function en(){let e=k.AGENT_AFK_ASCII;return e&&/^(1|true|yes)$/i.test(e)?WY:Ly}function vi(e,t){let n="";for(let r of e)n+=r?t.spineClosed:t.spine;return n+=t.spine,n}function sl(e,t){let n="";for(let r=0;r<e.length;r+=2){let o=e.slice(r,r+2);n+=o===t.spine?m.dim(o):o}return n}function $y(e,t,n){if(!e||!e.trim())return[];let r=m.dim(n.textPrefix),o=Math.max(1,Q()-t.length-2-2),s=sl(t,n),i=[];for(let a of e.split(`
1832
+ `)}constructor(t){this.stdout=t.stdout,this.stdin=t.stdin,this.onCancel=t.onCancel,this.onSoftStop=t.onSoftStop,this.onBackground=t.onBackground,this.onPauseInterrupt=t.onPauseInterrupt,this.onShiftTab=t.onShiftTab;let n=t.promptText;if(typeof n=="function")this.promptTextFn=n;else if(typeof n=="string")this.promptTextFn=()=>n;else{let r=" "+m.dim("\u23AF")+" ";this.promptTextFn=()=>r}this.history=t.history,this.autocompleteState=t.autocompleteState,this.formatInputBuffer=t.formatInputBuffer,this.scrollRegion=t.scrollRegion,this.spinnerController=new Fd({captureMode:t.captureMode??!1,onTick:()=>this.repaint()}),this.onSubmit=t.onSubmit,this.anchorRow=t.anchorRow,this.declaredAnchorRow=t.anchorRow,this.ghostEngine=t.suggest?.engine,this.ghostGetContext=t.suggest?.getContext}isArmed(){return this.armed}setAnchorRow(t){this.anchorRow=t,this.declaredAnchorRow=t}suspendInput(){rP(this)}resumeInput(){oP(this)}setOnSubmit(t){this.onSubmit=t??void 0}setOnCancel(t){this.onCancel=t??void 0}getOnCancel(){return this.onCancel}setOnSoftStop(t){this.onSoftStop=t??void 0}setOnBackground(t){this.onBackground=t??void 0}setOnShiftTab(t){this.onShiftTab=t??void 0}enterPickerMode(t){jI(this,t)}exitPickerMode(){UI(this)}repaintPicker(){HI(this)}setInputMode(t){KI(this,t)}getInputMode(){return WI(this)}async arm(){return sP(this)}disarm(){iP(this)}setOverlay(t){t!==this.overlay&&(this.debugLog("setOverlay",{framesLen:t.length,anchorRow:this.anchorRow??null}),this.overlay=t,this.repaint())}setSpinner(t){this.stdout.isTTY&&this.spinnerController.set(t)}commitAbove(t){OI(this,t)}clearCommittedBand(){Xa(this)}flushResizeGhostErase(){DI(this)}resetCommittedBand(){$I(this)}repositionCommittedBand(t,n,r){LI(this,t,n,r)}getBuffer(){return fI(this)}getPendingCount(){return this.pendingSubmissions.length}getAttachments(){return[...this.attachments]}renderInputLine(){return _I(this)}updateAutocomplete(){Hd(this)}updateGhost(){TI(this)}renderDropdownRows(){return II(this)}renderHintRow(){return PI(this)}repaint(){BI(this)}resetState(){aP(this)}applyEdit(t){return YI(this,t)}applyDropdownSelection(){return RI(this)}applyGhostAccept(){return AI(this)}};import bY from"chalk";var wY=/(?<=\s|^)(\/[A-Za-z][\w:-]*)(?=\s|$)/g,SY=/(?<=\s|^)(@[~\w./-]*)(?=\s|$)/g,vY=/\[Pasted text #[0-9a-f]+ \+\d+ (?:lines|chars)\]/g,lP={mint:m.mint};function kY(e){let t=lP[e];if(t)return t;let n=e.lastIndexOf(":");if(n>=0){let r=e.slice(n+1),o=lP[r];if(o)return o}return null}function Nr(e,t){return bY.level===0?e:e.replace(wY,o=>{let s=o.slice(1);return t.has(s)?(kY(s)??m.brand)(o):m.meta(o)}).replace(SY,o=>m.fileRef(o)).replace(vY,o=>m.meta(o))}G();import{pathToFileURL as EY}from"node:url";var xY="\x1B]8;;\x1B\\",TY=new Set(["iterm2","wezterm","kitty","vscode","ghostty","windows-terminal","konsole","gnome-terminal","alacritty"]),RY=5e3;function AY(e=process.env,t=process.stdout.isTTY===!0){let n=e.FORCE_HYPERLINK;if(n!==void 0&&n.length>0)return n!=="0"&&n.toLowerCase()!=="false";if(!t||e.CI!==void 0&&e.CI.length>0)return!1;let r=qa(e);if(!TY.has(r))return!1;if(r==="gnome-terminal"&&e.VTE_VERSION!==void 0){let o=Number.parseInt(e.VTE_VERSION,10);if(!Number.isFinite(o)||o<RY)return!1}return!0}var Ry;function zd(){return Ry===void 0&&(Ry=AY()),Ry}function CY(e,t){return`\x1B]8;;${t}\x1B\\${e}${xY}`}function qd(e,t){try{return CY(e,EY(t).href)}catch{return e}}var cP=/[\x00-\x1F\x7F-\x9F]/g;function tt(e){return $e(e).replace(cP," ").replace(/ {2,}/g," ").trim()}function Ay(e){return $e(e).replace(cP," ")}function nl(e){let t=/[a-z][a-z0-9+.-]*:\/\/[^\s<>\"`]+/gi,n="",r=0;for(let o of e.matchAll(t)){let s=o[0]??"",i=o.index??r;n+=uP(e.slice(r,i)),n+=s,r=i+s.length}return n+=uP(e.slice(r)),n}function uP(e){let t=zd();return e.replace(/\/(?:[^/\s,)]+\/){2,}([^/\s,)]+)/g,(n,r)=>t?qd(r,n):r)}function _Y(e){let t=/^(\s*[("]?\s*)cd\s+\S+\s+&&\s+(?!cd\s)(.+)$/.exec(e);return t?(t[1]??"")+(t[2]??""):e}var dP=60;function Cy(e,t){let n=e.trim().replace(/^\((.*)\)$/s,"$1"),r;try{r=JSON.parse(n)}catch{return e}if(!r||typeof r!="object")return e;let o=r;for(let s of t){let i=o[s];if(typeof i=="string"&&i.length>0){let a=tt(i);if(a.length===0)continue;return`(${a.length>dP?ie(a,dP,"\u2026"):a})`}}return e}function pP(e,t){if(e==="bash"||e==="Bash")return _Y(t);if(e==="compose"||e==="Compose"){let n=t.trim().replace(/^\((.*)\)$/s,"$1");try{let r=JSON.parse(n);if(r&&typeof r=="object"){let o=Array.isArray(r.nodes)?r.nodes.length:void 0,s=Array.isArray(r.edges)?r.edges.length:0;if(o!==void 0){let i=`${o} node${o===1?"":"s"}`,a=s>0?`, ${s} edge${s===1?"":"s"}`:"";return`(${i}${a})`}}}catch{}}return e==="agent"||e==="Agent"?Cy(t,["id_prefix","prompt"]):e==="Task"?Cy(t,["description","prompt"]):e==="skill"||e==="Skill"?Cy(t,["name","arguments"]):e==="ask_question"?IY(t):t}function IY(e){let t=e.trim().replace(/^\((.*)\)$/s,"$1");try{let n=JSON.parse(t);if(!n||typeof n!="object")return e;let r=n,o=typeof r.type=="string"?r.type:"text";if(o==="choice"||o==="multi_choice"){let s=r.choices,i=Array.isArray(s)?s.length:0;return i>0?`(${o}: ${i} option${i===1?"":"s"})`:`(${o})`}return`(${o})`}catch{return e}}function PY(e){return e.replace(/[\r\n]+/g," ")}var MY={"(":")","{":"}","[":"]"};function mP(e,t,n="\u2026"){let r=e.charAt(0),o=MY[r];return!(o&&e.endsWith(o)&&e.length>=2)||J(e)<=t?ie(e,t,n):t<3?t>=2?r+o:ie(e,t,n):ie(e,t-1,n)+o}function rr(e,t){let n=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/s.exec(e);if(n){let r=n[1],o=nl(pP(r,n[2]??"")),s=fn(r),{color:i,glyph:a}=si(r),l=Ng(s),c=l?` [${l}]`:"";if(t!==void 0){let d=(a+" ").length+r.length+c.length,p=Math.max(1,t-d);o=mP(o,p)}o=PY(o);let u=i(a+" ")+i.bold(r)+m.toolArg(o);return l?u+m.dim(c):u}return m.chrome("\u25CF ")+m.toolArg(e)}G();var fP=8,Jd=30;function OY(){let e=k.AFK_DIFF_LINES;if(e===void 0)return Jd;let t=e.trim();if(!/^\d+$/.test(t))return Jd;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:Jd}function $Y(){let e=k.AFK_SHOW_DIFFS;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"}function DY(e){let t=m.diffAdd(`+${e.addedLines}`),n=m.diffRemove(`-${e.removedLines}`),r=e.hunks.length,o=m.dim(`across ${r} hunk${r===1?"":"s"}`);return`${t} ${n} ${o}`}var LY=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;function FY(e){let t=$e(e.text).replace(LY,"");return e.kind==="+"?m.diffAdd("+ "+t):e.kind==="-"?m.diffRemove("- "+t):m.dim(" "+t)}var Iy=new WeakMap;function or(e,t,n){if($Y())return[];if(e.hunks.length===0)return[];let r=t==="overlay"?fP:OY(),o=t+"|"+n+"|"+r,s=Iy.get(e);if(s!==void 0){let f=s.get(o);if(f!==void 0)return f}let i=[];i.push(n+DY(e));let a=[];for(let f of e.hunks){let g=`@@ -${f.oldStart},${f.oldLines} +${f.newStart},${f.newLines} @@`;a.push({kind:"header",text:m.diffHunk(g)});for(let h of f.lines)a.push({kind:"body",text:FY(h)})}if(r===0){for(let f of a)i.push(n+f.text);return _y(e,o,i),i}let l=0;for(let f of a)f.kind==="body"&&l++;if(l<=r){for(let f of a)i.push(n+f.text);return _y(e,o,i),i}let c=0;for(let f of a)f.kind==="header"?i.push(n+f.text):c<r&&(i.push(n+f.text),c++);let u=l-r,d=`line${u===1?"":"s"}`,p=t==="flush"?" (set AFK_DIFF_LINES=0 to expand)":"";return i.push(n+m.dim(`\u2026 +${u} more diff ${d}${p}`)),_y(e,o,i),i}function _y(e,t,n){let r=Iy.get(e);r===void 0&&(r=new Map,Iy.set(e,r)),r.set(t,n)}var NY=m.success("\u2713"),BY=m.error("\u2717");function Br(e){return e?BY:NY}var rl=3,gP=2,hP=3;function yP(e){switch(fn(e)){case"read":return"Reading\u2026";case"write":return"Writing\u2026";case"web":return"Fetching\u2026";case"shell":return"Running\u2026";default:return"Running\u2026"}}function jY(e,t){return e?e==="grep"||e==="Grep"?t===1?"match":"matches":e==="glob"||e==="Glob"?t===1?"path":"paths":t===1?"line":"lines":t===1?"line":"lines"}function sr(e,t,n=60,r){let o=e.isError?m.error:m.dim,s=t??k.HOME??"___NOHOME___";if(e.display!==void 0&&!e.isError)return o(e.display);if(e.persistedPath){let a=e.persistedPath.startsWith(s)?"~"+e.persistedPath.slice(s.length):e.persistedPath,l=zd()?qd(a,e.persistedPath):a;return o(`saved \u2192 ${l}`)}if(e.lineCount!==void 0&&e.lineCount>1)return o(`${e.lineCount} ${jY(r,e.lineCount)}`);let i=e.content.length>n?e.content.slice(0,n-3)+"\u2026":e.content;return o(tt(i))}G();function ol(e,t){if(e.length<=t)return e;let n=e.slice(0,t),r=e.slice(t),o=wP(r);return[...n,{kind:"overflow",count:r.length,text:o}]}function UY(e,t){return t<=1||e.endsWith("s")||/(sh|ch|x|z)$/i.test(e)?e:e+"s"}var HY=5,bP=60;function wP(e){let t=new Map,n=0;for(let s of e)s.kind==="group"?(t.set(s.toolName,(t.get(s.toolName)??0)+s.entries.length),n+=s.entries.length):(t.set(s.toolName,(t.get(s.toolName)??0)+1),n+=1);if(n===0)return"";if(e.length>0&&e.every(s=>We.has(s.toolName))&&new Set(e.map(s=>s.toolName)).size===1){let s=[],i=!1;for(let a of e){let c=(a.kind==="group"?a.label:a.toolInput).trim();if(!c.startsWith("(")||!c.endsWith(")")){i=!0;break}let u=c.slice(1,-1),d=tt(u);if(!d){i=!0;break}let p=d.length>bP?d.slice(0,bP-1)+"\u2026":d,f=a.kind==="group"?a.entries.length:1;s.push({display:p,entries:f})}if(!i&&s.length>0){let a=s.slice(0,HY),l=a.map(({display:p,entries:f})=>f>1?`${p} \xD7${f}`:p),c=a.reduce((p,f)=>p+f.entries,0),u=n-c,d=l.join(", ")+(u>0?` (+${u})`:"");return`\u2026 +${n} more: ${d}`}}let o=[];for(let[s,i]of t)o.push(`${i} ${UY(s,i)}`);return`\u2026 +${n} (${o.join(", ")})`}function Vd(e,t=en()){return e.map((n,r)=>({sibling:n,connector:r===e.length-1?t.lastConnector:t.midConnector}))}function Py(e,t){return t?[...e,{kind:"resultSummary",summary:t}]:e}function My(e){if(e.length===0)return[];let t=new Map;for(let o of e){let s=SP(o),i=t.get(s);i||(i=[],t.set(s,i)),i.push(o)}let n=[],r=new Set;for(let o of e){let s=SP(o),i=t.get(s);i.length>=KY(o.toolName)?r.has(s)||(n.push({kind:"group",toolName:o.toolName,label:We.has(o.toolName)?o.toolInput:"",entries:i}),r.add(s)):n.push(o)}return n}function Oy(e){let t=e.entries.length,n=e.entries.filter(a=>a.result),r=n.filter(a=>a.result.isError),o=n.length,s;if(r.length>0){let a=o-r.length,l=[];a>0&&l.push(`${a} ok`),l.push(`${r.length} error${r.length===1?"":"s"}`),s=l.join(", ")}else o===t?s=`${t} done`:o===0?s=`${t} running`:s=`${o}/${t} done`;return rr(e.toolName+e.label)+m.dim(` \xD7${t} \u2014 ${s}`)}function SP(e){return We.has(e.toolName)?e.toolName+"::"+e.toolInput:e.toolName}function KY(e){return We.has(e)?gP:hP}function vP(e,t,n,r){return e>0||t?vi([...n,!0],r):vi(n,r)}function kP(e,t){return!We.has(e.toolName)||e.headerEmitted!==!0?!1:(t.get(e.toolUseId)??[]).every(r=>r.kind==="tool"&&kP(r,t))}function Yd(e,t,n,r=Q(),o=[],s=en(),i){let a=vi(o,s),l=sl(a,s),c=e.filter(h=>h.kind==="text"),u=e.filter(h=>h.kind==="tool").filter(h=>!kP(h,t)),d=My(u),p=ol(d,rl),f=Vd(p,s);for(let{sibling:h,connector:b}of f){let y=m.dim(b),S=b===s.lastConnector;if(h.kind==="overflow")n.push(Re(l+y+m.dim(h.text),r));else if(h.kind==="group")n.push(Re(l+y+Oy(h),r));else if(h.kind==="resultSummary")n.push(Re(l+y+m.dim(h.summary),r));else{let w=h,R=t.get(w.toolUseId);if(We.has(w.toolName)&&R&&R.length>0){w.headerEmitted?n.push(Re(l+y,r)):n.push(Re(l+y+w.prefix,r));let x=i??S;if(Yd(R,t,n,r,[...o,x],s,S),w.thinkingTail){let A=sl(vi([...o,x],s),s);n.push(Re(A+m.thinking("\u2307 "+tt(w.thinkingTail)),r))}}else if(!(We.has(w.toolName)&&w.headerEmitted))if(w.result){if(n.push(Re(l+y+w.prefix+m.dim(" \u2014 ")+Br(w.result.isError)+" "+sr(w.result,void 0,60,w.toolName),r)),w.diff&&!w.result.isError){let x=l+(S?s.spineClosed:m.dim(s.spine))+" ";for(let A of or(w.diff,"overlay",x))n.push(Re(A,r))}}else{n.push(Re(l+y+w.prefix,r));let x=l+(S?s.spineClosed:m.dim(s.spine))+" ";w.thinkingTail?n.push(Re(x+m.thinking("\u2307 "+tt(w.thinkingTail)),r)):n.push(Re(x+m.dim(yP(w.toolName)),r))}}}let g=vP(u.length,!1,o,s);for(let h of c)for(let b of $y(h.text,g,s))n.push(Re(b,r))}function il(e,t,n,r,o=Q(),s=[],i=en(),a){let l=vi(s,i),c=sl(l,i),u=[],d=e.filter(S=>S.kind==="text"),p=e.filter(S=>S.kind==="tool"),f=My(p),g=ol(f,rl),h=Py(g,r),b=Vd(h,i);for(let{sibling:S,connector:w}of b){let R=m.dim(w),x=w===i.lastConnector;if(S.kind==="overflow")u.push(Re(c+R+m.dim(S.text),o));else if(S.kind==="resultSummary")u.push(Re(c+R+m.dim(S.summary),o));else if(S.kind==="group")u.push(Re(c+R+Oy(S),o));else{let A=S,T=t.get(A.toolUseId);if(We.has(A.toolName)&&T&&T.length>0){if(A.headerEmitted){let _=A.toolInput?`${A.toolName} ${tt(A.toolInput)}`:A.toolName;u.push(Re(c+R+m.dim("\u21B3 "+_),o))}else u.push(Re(c+R+A.prefix,o));let v=a??x;u.push(...il(T,t,n,void 0,o,[...s,v],i,x))}else if(A.result){if(u.push(Re(c+R+A.prefix+m.dim(" \u2014 ")+Br(A.result.isError)+" "+sr(A.result,n,60,A.toolName),o)),A.diff&&!A.result.isError){let v=c+(x?i.spineClosed:m.dim(i.spine))+" ";for(let _ of or(A.diff,"flush",v))u.push(Re(_,o))}}else u.push(Re(c+R+A.prefix,o))}}let y=vP(p.length,r!=null,s,i);for(let S of d)for(let w of $y(S.text,y,i))u.push(Re(w,o));return u}function al(e,t,n,r,o=[]){let s=en(),i=t.filter(h=>h.kind==="tool"),l=i.filter(h=>h.result).reduce((h,b)=>h+(b.result.lineCount??0),0),c=[];i.length>rl&&(c.push(`${i.length} tools`),l>0&&c.push(`${l} lines`));let u=m.dim(s.spine.repeat(o.length)),d=o,p=m.dim(s.turnRoot),f=c.length>0?u+p+e.prefix+m.dim(" \u2014 "+c.join(" \xB7 ")):u+p+e.prefix,g=il(t,n,r,e.agentResultSummary,Q(),d,s);return[f,...g].join(`
1833
+ `)}function Dy(e,t=[]){let n=en(),r=m.dim(n.spine.repeat(t.length)),o=m.dim(n.turnRoot);return r+o+e.prefix}function ll(e,t,n,r,o=[]){let s=en(),i=o;return il(t,n,r,e.agentResultSummary,Q(),i,s)}function ki(e,t,n){let r=[],o=Q();for(let s of t){let i=e.get(s);if(i.length===1){let a=i[0];if(a.result){if(r.push(" "+a.prefix+m.dim(" \u2014 ")+Br(a.result.isError)+" "+sr(a.result,n,60,a.toolName)),a.diff&&!a.result.isError)for(let l of or(a.diff,"flush"," "))r.push(Re(l,o))}else r.push(" "+a.prefix)}else{r.push(EP(s,i,n));let a=i.filter(c=>c.diff&&c.result&&!c.result.isError),l=a.length>1;for(let c of a){if(l){let u=tt(c.toolInput),d=nl(u).trim()||u.trim();r.push(" "+m.dim(`\u2500\u2500 ${d} \u2500\u2500`))}for(let u of or(c.diff,"flush"," "))r.push(Re(u,o))}}}return r}function EP(e,t,n){let{color:r,glyph:o}=si(e),s=t.map(u=>nl(tt(u.toolInput)).trim()),i=r(o+" ")+r.bold(e)+m.dim(` \xD7${t.length}`)+" "+m.toolArg(s.join(", ")),a=t.filter(u=>u.result),l=a.filter(u=>u.result.isError);if(l.length>0){let u=a.length-l.length,p=a.filter(g=>!g.result.isError).map(g=>g.result.lineCount).filter(g=>g!==void 0).reduce((g,h)=>g+h,0),f=[];return p>0&&f.push(`${p} lines`),u>0&&f.push(`${u} ok`),f.push(m.error(`${l.length} error${l.length>1?"s":""}`))," "+i+m.dim(" \u2014 ")+f.join(m.dim(", "))}let c=a.map(u=>u.result?.lineCount).filter(u=>u!==void 0);if(c.length===a.length&&c.length>0){if(c.every(p=>p===c[0]))return" "+i+m.dim(` \u2014 ${c[0]} lines each`);let d=c.reduce((p,f)=>p+f,0);return" "+i+m.dim(` \u2014 ${d} lines total`)}if(a.length>0){let u=a.map(d=>sr(d.result,n,60,d.toolName));return" "+i+m.dim(" \u2014 ")+u.join(m.dim(", "))}return" "+i}function Re(e,t){return ie(e,t)}var Ly=Object.freeze({spine:"\u2502 ",spineClosed:" ",lead:" ",turnRoot:"\u25C9 ",midConnector:"\u251C\u2500 ",lastConnector:"\u2570\u2500 ",textPrefix:"\u2502 "}),WY=Object.freeze({spine:"| ",spineClosed:" ",lead:" ",turnRoot:"o ",midConnector:"+- ",lastConnector:"\\- ",textPrefix:"| "}),XTe=Ly.midConnector,ZTe=Ly.lastConnector;function en(){let e=k.AGENT_AFK_ASCII;return e&&/^(1|true|yes)$/i.test(e)?WY:Ly}function vi(e,t){let n="";for(let r of e)n+=r?t.spineClosed:t.spine;return n+=t.spine,n}function sl(e,t){let n="";for(let r=0;r<e.length;r+=2){let o=e.slice(r,r+2);n+=o===t.spine?m.dim(o):o}return n}function $y(e,t,n){if(!e||!e.trim())return[];let r=m.dim(n.textPrefix),o=Math.max(1,Q()-t.length-2-2),s=sl(t,n),i=[];for(let a of e.split(`
1834
1834
  `)){let l=Ay(a),c=de(l,o);for(let u of c.split(`
1835
1835
  `))i.push(s+r+u)}return i}var xP=6,cl=class{entries=new Map;order=[];agentIdStack=[];addStart(t,n,r){let o=$e(r),s=rr(n+o),i=this.agentIdStack.at(-1)??void 0,a={kind:"tool",toolUseId:t,toolName:n,toolInput:o,prefix:s,...i!==void 0?{agentContext:i}:{}};this.entries.set(t,a),this.order.push(t),xr.has(n)&&this.agentIdStack.push(t)}addStartWithAgentContext(t,n,r,o,s){let i=$e(r),a=this.entries.get(t);if(a?.kind==="tool"){a.toolInput=i,a.prefix=rr(n+i,s),o!==void 0&&(a.agentContext=o);return}let l=rr(n+i,s),c={kind:"tool",toolUseId:t,toolName:n,toolInput:i,prefix:l,...o!==void 0?{agentContext:o}:{}};this.entries.set(t,c),this.order.push(t)}mergeAgentLabel(t,n,r){let o=this.entries.get(t);if(o?.kind!=="tool"||!xr.has(o.toolName)||o.toolName==="Agent")return!1;let i=`(${$e(n)})`;return o.toolName="Agent",o.toolInput=i,o.prefix=rr("Agent"+i,r),!0}setAgentContext(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(n===void 0?delete r.agentContext:r.agentContext=n)}setAgentResultSummary(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.agentResultSummary=n)}setThinkingTail(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(n===void 0?delete r.thinkingTail:r.thinkingTail=n)}addResult(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.result=n),this.agentIdStack.at(-1)===t&&this.agentIdStack.pop()}addDiff(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.diff=n)}upsertTextChild(t,n,r){let o=this.entries.get(t);if(o?.kind==="text"){o.text=r,o.agentContext=n;return}let s={kind:"text",toolUseId:t,text:r,agentContext:n};this.entries.set(t,s),this.order.push(t)}removeTextChildrenUnder(t){let n=[];for(let[r,o]of this.entries)o.kind==="text"&&o.agentContext===t&&n.push(r);for(let r of n)this.entries.delete(r);if(n.length>0){let r=new Set(n);this.order=this.order.filter(o=>!r.has(o))}}hasPending(){return this.entries.size>0}hasEntry(t){return this.entries.get(t)?.kind==="tool"}findLastSkillEntryId(){for(let t=this.order.length-1;t>=0;t--){let n=this.order[t],r=this.entries.get(n);if(r?.kind==="tool"&&xa.has(r.toolName))return n}}getOverlay(){let t=this.buildChildMap(),n=[],r=en(),o=Q(),s=d=>ie(d,o),i=[];for(let d of this.order){let p=this.entries.get(d);!p||p.kind!=="tool"||p.agentContext||i.push(p)}let a=i,l=0;if(i.length>xP){let d=i.filter(h=>!h.result),p=i.filter(h=>h.result),f=Math.max(0,xP-d.length),g=new Set(p.slice(-f));l=p.length-g.size,a=i.filter(h=>!h.result||g.has(h))}let u=a.some(d=>We.has(d.toolName))?m.dim(r.turnRoot):" ";for(let d of a){let p=t.get(d.toolUseId);if(We.has(d.toolName)&&p&&p.length>0)d.headerEmitted?n.push(s(m.dim(r.turnRoot))):n.push(s(m.dim(r.turnRoot)+d.prefix)),Yd(p,t,n,o,void 0,r),d.thinkingTail&&n.push(s(m.dim(r.spine)+m.thinking("\u2307 "+tt(d.thinkingTail))));else if(!(We.has(d.toolName)&&d.headerEmitted))if(We.has(d.toolName))d.result?n.push(s(m.dim(r.turnRoot)+d.prefix+m.dim(" \u2014 ")+Br(d.result.isError)+" "+sr(d.result,void 0,60,d.toolName))):n.push(s(m.dim(r.turnRoot)+d.prefix+m.dim(" \u2026"))),d.thinkingTail&&n.push(s(m.dim(r.spine)+m.thinking("\u2307 "+tt(d.thinkingTail))));else if(d.result){if(n.push(s(u+d.prefix+m.dim(" \u2014 ")+Br(d.result.isError)+" "+sr(d.result,void 0,60,d.toolName))),d.diff&&!d.result.isError)for(let f of or(d.diff,"overlay"," "))n.push(s(f))}else n.push(s(u+d.prefix+m.dim(" \u2026"))),d.thinkingTail&&n.push(s(m.dim(r.spine)+m.thinking("\u2307 "+tt(d.thinkingTail))))}return l>0&&n.push(s(" "+m.dim(`\u2026 +${l} done`))),n.join(`
1836
1836
  `)}ancestorDepthOf(t){let n=new Set([t]),r=0,o=t,s=32;for(;o!==void 0&&r<s;){let i=this.entries.get(o);if(!i||i.kind!=="tool")break;let a=i.agentContext;if(a===void 0||n.has(a))break;n.add(a);let l=this.entries.get(a);if(!l||l.kind!=="tool")break;r+=1,o=a}return r}flushSource(t,n){let r=this.entries.get(t);if(!r||r.kind!=="tool")return[];let o=Array.from({length:this.ancestorDepthOf(t)},()=>!1),s=[];{let p=[],f=new Set([t]),g=r.agentContext;for(;g!==void 0&&!f.has(g);){f.add(g);let h=this.entries.get(g);if(!h||h.kind!=="tool")break;p.push({entry:h,depth:this.ancestorDepthOf(h.toolUseId)}),g=h.agentContext}p.reverse();for(let{entry:h,depth:b}of p)h.headerEmitted||(s.push(Dy(h,Array.from({length:b},()=>!1))),h.headerEmitted=!0)}let i=new Set([t]),a=[t];for(;a.length>0;){let p=a.shift();for(let[f,g]of this.entries){if(i.has(f))continue;(g.kind==="tool",g.agentContext)===p&&(i.add(f),g.kind==="tool"&&a.push(f))}}let l=new Map;for(let p of this.order){if(!i.has(p))continue;let f=this.entries.get(p);if(!f)continue;let g=(f.kind==="tool",f.agentContext);if(!g)continue;let h=l.get(g);h||(h=[],l.set(g,h)),h.push(f)}let c=l.get(r.toolUseId)??[],u=r.headerEmitted?ll(r,c,l,n,o).join(`
@@ -1990,7 +1990,7 @@ _ended: ${new Date().toISOString()}_
1990
1990
  ${R}${S}
1991
1991
  ${w}
1992
1992
  ${R}`})}return{fileBlocks:a,warnings:l}}async function Z0(e,t,n,r,o="summary",s,i){let a=FI(e.text,e.attachments);r.onUserMessage&&await Promise.resolve(r.onUserMessage(a)).catch(()=>{}),r.setInFlight(!0);let l="",c=0,u=!1,d=!1,p=!1,f=!1,g,h=!1,b=!1,y={abort:null},S=0,w=15e3,R=[],x=new Map,A=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,T=()=>{let D=r.subagentControl;D?.hasPromotableForeground()&&D.promoteActiveForeground().then(N=>{for(let B of N)(s??{fn:console.log}).fn(m.dim(` \u2192 subagent backgrounded as ${B.jobId}: ${B.label}`))}).catch(()=>{})},v=r.getCompositor?r.getCompositor():null,_=()=>new Ri({out:Ai(s),thinkingMode:o,...A?{activeSkillName:A}:{},onCancel:()=>{t.interrupt().catch(D=>{Ne()&&console.error(" "+m.error("session.interrupt() failed:"),D)})},...r.subagentControl?{onBackground:T}:{},...i?.history?{history:i.history}:{},...i?.autocompleteState?{autocompleteState:i.autocompleteState}:{},...i?.promptText!==void 0?{promptText:i.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...v?{compositor:v}:{},...r.onStageChange?{onStageChange:r.onStageChange}:{}}),I=_(),$=async()=>{if(!p){p=!0;try{await I.dispose()}catch{}}},O=async()=>{await I.arm();let D=I.getCompositor();if(s&&D){let N=D;s.fn=B=>N.commitAbove(B)}r.setActiveCompositor?.(D),r.setInterruptNotifier?.(N=>I.setInterrupting(N)),r.rearmStatus?.()};try{v?v.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{h=!0,t.interrupt().catch(F=>{Ne()&&console.error(" "+m.error("soft-stop session.interrupt() failed:"),F)})}),r.setPauseInterruptHandler&&r.setPauseInterruptHandler(()=>{b=!0,t.interrupt().catch(F=>{Ne()&&console.error(" "+m.error("pause-interrupt session.interrupt() failed:"),F)})}),await O(),r.setBackgroundHandler&&r.subagentControl&&r.setBackgroundHandler(T);let{fileBlocks:D,warnings:N}=X0(e.text,{rootDir:process.cwd()});for(let F of N)(s??{fn:console.log}).fn(m.dim(` @-file: ${F}`));let B=D.length>0||e.attachments.length>0?V0(e.text,e.attachments,void 0,D):e.text,U=t.sendMessageStream(B);if(await Ss((F,L)=>{I.process(F,L)},async()=>{for await(let F of U){if(h||b)break;if(F.type==="chunk"&&F.chunk.type==="content"?(l+=F.chunk.content,u=!0):F.type==="message"&&!u&&(l=F.message.content),F.type==="stream_retry"&&(l=l.slice(0,c)),F.type==="chunk"&&F.chunk.type==="tool_use_detail"){let L=F.chunk,M={toolName:L.toolName,toolUseId:L.toolUseId,input:L.toolInput,...L.toolInputRaw!==void 0&&{inputRaw:L.toolInputRaw}};x.set(L.toolUseId,M),R.push(M)}else if(F.type==="chunk"&&F.chunk.type==="tool_result"){let L=F.chunk;c=l.length;let M=x.get(L.toolUseId);if(M&&(M.result=L.content,M.isError=L.isError,x.delete(L.toolUseId)),r.onContextProgress){let q=Date.now();if(q-S>=w){S=q;try{let Y=r.onContextProgress();Y instanceof Promise&&await Y}catch(Y){Ne()&&console.error(" "+m.error("onContextProgress (status refresh) failed:"),Y)}}}}if(F.type==="paused"){if(r.setPausedState?.(!0),await $(),v&&F.autoResume===!0){let L=new AbortController;y.abort=L;let M=F.resetsAt?F.resetsAt.toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"}):null,q=M?`Keep waiting \u2014 auto-resumes at ${M}`:"Keep waiting \u2014 auto-resume in progress",Y="Switch model / provider (type /model after)",re="Stop waiting",X=[m.warning(" \u23F3 Usage limit reached.")+(M?m.dim(` Auto-resumes at ${M}.`):""),m.dim(" Tip: run `claude login` in another terminal to switch account \u2014 this turn resumes on it automatically."),""];jp(v,{header:X,options:[q,Y,re],signal:L.signal,initialIndex:0}).then(H=>{if(y.abort=null,!H)return;let ee=H[0];ee===void 0||ee===q||(b=!0,ee===Y&&(s??{fn:console.log}).fn(m.dim(" Hint: type /model <name> to switch, then send your message again.")),t.interrupt().catch(le=>{Ne()&&console.error(" "+m.error("picker pause-interrupt session.interrupt() failed:"),le)}))}).catch(H=>{Ne()&&console.error(" "+m.error("picker promise rejected:"),H)})}else(s??{fn:console.log}).fn(bS({reason:F.reason,...F.resetsAt!==void 0?{resetsAt:F.resetsAt}:{},...F.accountId!==void 0?{accountId:F.accountId}:{},...F.autoResume!==void 0?{autoResume:F.autoResume}:{}}));continue}if(F.type==="resumed"){r.setPausedState?.(!1),y.abort?.abort(),y.abort=null;let L=F.hotSwapped&&F.accountId?`\u25B6 Resumed on ${F.accountId}`:"\u25B6 Resumed";l="",c=0,u=!1,R.length=0,x.clear(),f=!1,g=void 0,d=!1,I=_(),p=!1,await O(),(s??{fn:console.log}).fn(m.success(L));continue}if(F.type==="error"){await $(),ds(as(F.error)),d=!0;continue}I.process(F),F.type==="done"&&(f=!0,g=F.metadata)}}),await $(),h){let F=s?s.fn:console.log;F(m.warning("\u23F8 Stopped \u2014 work so far kept.")+m.dim(" Send a message to continue.")),F("")}if(b){let F=s?s.fn:console.log;F(m.dim("\u25B6 Ending wait \u2014 running your next command\u2026")),F("")}if(f&&!h&&!b){ko(n,a,l,g,R),r.onTurnComplete&&await r.onTurnComplete(a,l).catch(()=>{}),hd(process.stdout);let F=M=>{s?s.fn(M):console.log(M)},L=q0(l);if(L){if(F(J0(L)),F(""),r.onTerminalState)try{r.onTerminalState(L)}catch{}n.permissionMode==="autonomous"&&c_(L)}if($6(g,n,F),r.onAfterTurn){let M=r.onAfterTurn();M instanceof Promise&&await M.catch(()=>{})}}}catch(D){await $(),d||ds(as(D))}finally{await $(),s&&(s.fn=s.idleFn),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setPausedState?.(!1),r.setPauseInterruptHandler?.(null),y.abort?.abort(),y.abort=null,r.setInFlight(!1),r.rearmStatus?.()}}function $6(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(ge(e.durationMs)),e.totalCostUsd!==void 0&&r.push(Xe(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),s=Number(e.usage?.output_tokens??0);o+s>0&&r.push(ae(o+s)+" tok"),r.length>0&&n(m.dim(" \u25E6 "+r.join(" \xB7 ")));let i=Zh(t),a=kt(t.model);if(i>=1){let l=Math.round((i-1)*a),c=Math.round(a/1e3);console.log(m.error(` context OVER ${c}k tok by ~${ae(l)} tok \u2014 model output may be silently truncated`))}else if(i>.5){let l=i>.8?m.error:m.warning;n(l(` context ${Math.round(i*100)}% used of ${ae(a)}`))}n("")}async function D6(e,t){if(e.firstTurnHook&&e.stats.totalTurns===0){let n=e.firstTurnHook;e.firstTurnHook=void 0;try{await n(t)}catch(r){e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(r instanceof Error?r.message:String(r)))}}}async function Q0(e,t,n,r,o,s,i,a){let{contextPane:l,loopStageBar:c,verdictLedger:u,shellPassthrough:d}=i,p=null,f=[];e.session.current.waitForInitialization().then(async y=>{Ne()&&(p=xd(y)),await hp(e.session.current),Ne()&&(f=FM())}).catch(()=>{});let g,h=!1,b=!1;for(;;){if(p&&(e.replRenderer.writeLine(p),e.replRenderer.writeLine(""),p=null),f.length>0){for(let v of f)e.replRenderer.writeLine(v);e.replRenderer.writeLine(""),f=[]}let y=d.drainNotifications();for(let{job:v,result:_}of y){let I=_.errorReason===void 0?"\u2713":"\u2717",$=_.errorReason==="abort"?"killed":_.errorReason==="timeout"?"timed out":_.errorReason==="signal-killed"?"killed by signal":`exit ${_.exitCode??0}`,O=Math.max(0,Math.round(_.durationMs/100)/10);e.replRenderer.writeLine(m.dim(` ${I} [${v.id}] ${$} \xB7 ${O}s \xB7 `)+v.command)}let S=l.renderIfChanged(e.stats.sessionId);if(S.length>0){for(let v of S)e.replRenderer.writeLine(v);e.replRenderer.writeLine("")}let w,R;if(g!==void 0){let v=g;g=void 0;let _=Oi(e.stats.model,e.stats.permissionMode),I=Co({buffer:v.text,promptText:_,isTTY:!!process.stdout.isTTY,attachmentSummary:wi([...v.attachments])});e.replRenderer.writeLine(I),w=v.text.trim(),R=v.attachments}else{let v=await o.readLine({promptFn:()=>Oi(e.stats.model,e.stats.permissionMode),onSigint:r,onShiftTab:()=>{nr(e.slashCtx).catch(()=>{}),e.statusLine.rearm()}});w=v.text.trim(),R=v.attachments}if(!w&&R.length===0)continue;if(w.startsWith("!")){let v=/^(0|false|off|no)$/i.test(k.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!v&&(h||(h=!0,e.replRenderer.writeLine(m.dim(" \u2139 ! prefix shells out. Pass --no-shell-passthrough (or set AFK_SHELL_PASSTHROUGH=0) to send ! text to the model instead."))),await d.dispatch(w))){e.statusLine.rearm();continue}}let x=!1;if(w.startsWith("/")){let v=await zC(w,e.slashCtx,R);if(v.handled){if(v.result==="exit"){e.rl.close();return}if((w==="/clear"||w.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),u.reset()),v.result!==null&&typeof v.result=="object"&&"kind"in v.result&&v.result.kind==="submit"){g={text:v.result.message,attachments:R??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}x=!0}a.push(w),await D6(e,w);let A=w;if(x){let v=Xh(w);if(v){let _=v.name.replace(/^\//,"").split(":").pop()??"";if(_&&ab(_)){let I={skillName:_,rawArgs:v.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},$=e.session.current.sessionId,O=Fo($),D=Date.now();V(`[afk trace] preflight.start commandName=${_}`);let N=!1,B=await Lo(I,{cwd:e.stats.cwd??process.cwd(),artifactDir:O},U=>{Ne()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${_}) failed: `)+(U instanceof Error?U.message:String(U)))});N=B!==null,V(`[afk trace] preflight.end commandName=${_} durationMs=${Date.now()-D} success=${N}`),A=cb(B?.manifestBlock,w)}}}let T=d.drainInjections();T.length>0&&(A=T+A),await Z0({text:A,attachments:R},e.session.current,e.stats,{setInFlight(v){n.turnInFlight=v},...e.subagentControl?{subagentControl:e.subagentControl}:{},async onUserMessage(v){await t.appendUser(v)},async onTurnComplete(v,_){if(await t.appendTurn(v,_),e.stats.sessionId)try{wn(e.stats)}catch(I){b||(b=!0,e.replRenderer.writeLine(m.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(I instanceof Error?I.message:String(I))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),e.statusLine.rearm(),c?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:v=>u?.push(v),setActiveCompositor:v=>{n.activeCompositor=v},setInterruptNotifier:v=>{n.notifyInterrupting=v},scrollRegion:e.statusLine,getCompositor:()=>o.getCompositor(),setBackgroundHandler:v=>o.setBackgroundHandler(v),setSoftStopHandler:s,setPausedState:v=>o.setPausedState(v),setPauseInterruptHandler:v=>o.setPauseInterruptHandler(v),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(tr(e.stats,e.contextSampler))},...c?{onStageChange:v=>c.repaint(v)}:{}},e.options.thinkingUi,e.completionWriter,o.toRunTurnRefs(Oi(e.stats.model,e.stats.permissionMode)))}}function L6(e,t){if(e!==void 0){let n=e.toLowerCase();return!(n==="0"||n==="false"||n==="off"||n==="no")}return typeof t=="boolean"?t:!0}async function eO(e,t,n,r){let o=await P0(),s=new Bp({rl:e.rl,history:o,statusLine:e.statusLine}),i=L6(k.AFK_SUGGEST_GHOST,e.suggestGhostConfig),a;try{let{installSoftStop:l}=await F0(e,s,n,t,r,i,{getLoopStageBar:()=>a?.loopStageBar});a=z0(e,n),await Q0(e,t,n,r,s,l,a,o)}finally{n.tryAbortShellForeground=null,a?.shellPassthrough.drainOnExit(),a?.loopStageBar.stop(),a?.bgStatusBar.stop(),a?.verdictLedger.stop(),a?.contextPane.dispose();let l=c=>console.log(c);e.completionWriter.fn=l,e.completionWriter.idleFn=l,await s.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}ca();import{execFile as F6}from"node:child_process";import{dirname as N6,isAbsolute as B6,resolve as j6}from"node:path";import{promisify as U6}from"node:util";var tO=U6(F6),H6=3e3,K6=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function W6(){let t=(await tO("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=B6(t)?t:j6(process.cwd(),t);return N6(n)}async function nO(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await W6()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),H6)});try{let o=En({execFile:tO,repoRoot:t,dryRun:!1,scope:"interactive",bypassSoftLaunch:!0}),s=await Promise.race([o,r]);if(s==="timeout")return{ran:!1,removedCount:0,skippedReason:"timeout"};let i=s;return i.warnings.some(c=>c.toLowerCase().includes("contested"))?{ran:!1,removedCount:0,skippedReason:"lock-contested"}:{ran:!0,removedCount:i.candidates.filter(c=>K6.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}ic();ca();import{promises as G6}from"node:fs";import{dirname as z6,join as sO}from"node:path";import{randomBytes as q6}from"node:crypto";var J6=["Generate a 2-4 word kebab-case slug describing this work request.","Rules:","- ASCII lowercase letters and digits only, separated by single hyphens","- 2 to 4 hyphen-separated words","- Maximum 30 characters total","- No prefix, no quotes, no punctuation other than hyphens","- Output ONLY the slug \u2014 no explanation, no preamble","Examples: fix-cleanup-race, add-telegram-allowlist, refactor-prompt-loader, debug-flaky-test"].join(`
1993
- `),rO=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Lb=30,V6=1024,Y6=8e3,X6="haiku";async function Z6(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=nX(n,V6),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??Y6),i=t.signal?rX([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await bs({token:t.token,model:t.model??X6,system:J6,user:r,maxTokens:32,signal:i})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(s)}let l=Q6(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=z6(t.worktreePath);return await eX(l,c)}function Q6(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(rO.test(t)&&t.length<=Lb)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let i=`${o}-${r[s]}`;if(i.length>Lb)break;o=i}return rO.test(o)?o:null}async function eX(e,t){if(!await tX(sO(t,e)))return e;let n=q6(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Lb-5)}-${n}`}async function tX(e){try{return await G6.access(e),!0}catch{return!1}}function nX(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function rX(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function iO(e){let t,n,r=sO(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await Z6(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),s=t??"unknown",i=n;if(o!==null){let l=`${Lc(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return oO(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){s="create-failed",i=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return oO(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:s,...i!==void 0?{detail:i}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function oO(e,t){e&&e.setCwd(t),oX(t)}function oX(e){try{process.chdir(e)}catch{}}He();Nt();W();import{spawn as lO}from"child_process";import{existsSync as cO,mkdirSync as cX,readFileSync as uO,unlinkSync as aO,writeFileSync as uX}from"fs";import{get as dX}from"https";import{join as dO}from"path";import{readFileSync as sX}from"fs";import{dirname as iX,join as aX}from"path";import{fileURLToPath as lX}from"url";function lr(){try{return"4.23.2"}catch{}try{let e=iX(lX(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(sX(aX(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}G();var pX=64*1024,mX=1440*60*1e3,fX=3600*1e3,gX="update-check.json",hX="pending-update.json";function pO(){return dO(jl(),gX)}function vl(){return dO(jl(),hX)}function mO(){let e=jl();cO(e)||cX(e,{recursive:!0})}function yX(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),s=n(t).split(".").map(Number),i=Math.max(o.length,s.length);for(let a=0;a<i;a++){let l=o[a]??0,c=s[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function bX(){try{let e=uO(pO(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function wX(){try{mO();let e=`
1993
+ `),rO=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Lb=30,V6=1024,Y6=8e3,X6="haiku";async function Z6(e,t){let n=e.trim();if(n.length===0)return t.onSkip?.("empty-message"),null;if(n.startsWith("/"))return t.onSkip?.("slash-command"),null;let r=nX(n,V6),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??Y6),i=t.signal?rX([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await bs({token:t.token,model:t.model??X6,system:J6,user:r,maxTokens:32,signal:i})}catch(d){let p=d instanceof Error?d.message:String(d);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(s)}let l=Q6(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=z6(t.worktreePath);return await eX(l,c)}function Q6(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(rO.test(t)&&t.length<=Lb)return t;let n=t.replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"");if(n.length===0)return null;let r=n.split("-").filter(s=>s.length>0).slice(0,4);if(r.length<2)return null;let o=r[0];for(let s=1;s<r.length;s++){let i=`${o}-${r[s]}`;if(i.length>Lb)break;o=i}return rO.test(o)?o:null}async function eX(e,t){if(!await tX(sO(t,e)))return e;let n=q6(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Lb-5)}-${n}`}async function tX(e){try{return await G6.access(e),!0}catch{return!1}}function nX(e,t){let n=Buffer.from(e,"utf8");if(n.length<=t)return e;let r=t;for(;r>0&&n[r]!==void 0&&(n[r]&192)===128;)r--;return n.slice(0,r).toString("utf8")}function rX(e){let t=AbortSignal.any;if(typeof t=="function")return t.call(AbortSignal,e);let n=new AbortController;for(let r of e){if(r.aborted)return n.abort(r.reason),n.signal;r.addEventListener("abort",()=>n.abort(r.reason),{once:!0})}return n.signal}async function iO(e){let t,n,r=sO(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await Z6(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:r,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(a,l)=>{t=a,n=l}}),s=t??"unknown",i=n;if(o!==null){let l=`${Lc(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return oO(e.session,c.path),{status:"created",path:c.path,branch:c.branch,slug:o}}catch(c){s="create-failed",i=(c instanceof Error?c.message:String(c)).slice(0,200)}}try{let a=await e.deferred.create(!0);return oO(e.session,a.path),{status:"created-fallback",path:a.path,branch:a.branch,reason:s,...i!==void 0?{detail:i}:{}}}catch(a){return{status:"failed",reason:a instanceof Error?a.message:String(a)}}}function oO(e,t){e&&e.setCwd(t),oX(t)}function oX(e){try{process.chdir(e)}catch{}}He();Nt();W();import{spawn as lO}from"child_process";import{existsSync as cO,mkdirSync as cX,readFileSync as uO,unlinkSync as aO,writeFileSync as uX}from"fs";import{get as dX}from"https";import{join as dO}from"path";import{readFileSync as sX}from"fs";import{dirname as iX,join as aX}from"path";import{fileURLToPath as lX}from"url";function lr(){try{return"4.24.0"}catch{}try{let e=iX(lX(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(sX(aX(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}G();var pX=64*1024,mX=1440*60*1e3,fX=3600*1e3,gX="update-check.json",hX="pending-update.json";function pO(){return dO(jl(),gX)}function vl(){return dO(jl(),hX)}function mO(){let e=jl();cO(e)||cX(e,{recursive:!0})}function yX(e,t){let n=a=>a.split(/[-+]/,1)[0]??a,r=a=>a.includes("-"),o=n(e).split(".").map(Number),s=n(t).split(".").map(Number),i=Math.max(o.length,s.length);for(let a=0;a<i;a++){let l=o[a]??0,c=s[a]??0;if(c>l)return!0;if(c<l)return!1}return r(e)&&!r(t)}function bX(){try{let e=uO(pO(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function wX(){try{mO();let e=`
1994
1994
  const https = require('https');
1995
1995
  const fs = require('fs');
1996
1996
  const url = 'https://registry.npmjs.org/agent-afk/latest';