agent-afk 3.81.0 → 3.81.1

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.
Files changed (2) hide show
  1. package/dist/cli.mjs +2 -2
  2. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -1746,7 +1746,7 @@ ${u}`}function Ap(e,t){let n=$k[t.status];e.out.line(` ${n} ${m.bold(t.jobId)}
1746
1746
  `),b),this.repositionCommittedBand(w,S,b)}resetState(){this.overlay="",this.input=U.seed(""),this.queued=!1,this.canceled=!1,this.backgrounded=!1,this.softStopped=!1,this.activeGhost=null,this.anchorRow=void 0,this.hasCommitted=!1,this.clearCommittedBand(),this.commitInFlight=!1,this.pendingResizeErase=null,this.lastKnownRows=0,this.pickerController=null,this.inputMode="streaming",this.attachments=[],this.pasting=!1,this.pasteStartBufferLen=0,this.pasteStartCursor=0,this.pasteRegistry.clear(),this.clipboardFailureMsg=null,this.autocompleteState?.reset(),this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null),this.resizeImmediateUnsub&&(this.resizeImmediateUnsub(),this.resizeImmediateUnsub=null)}applyEdit(t){return t===this.input?!1:(this.input=t,this.queued=!1,this.pasting||(this.updateAutocomplete(),this.updateGhost(),this.repaint()),!0)}applyDropdownSelection(){return yv(this)}applyGhostAccept(){return bv(this)}dispatchKey(t,n){Pv(this,t,n)}};import rU from"chalk";var oU=/(?<=\s|^)(\/[A-Za-z][\w:-]*)(?=\s|$)/g,sU=/(?<=\s|^)(@[~\w./-]*)(?=\s|$)/g,iU=/\[Pasted text #[0-9a-f]+ \+\d+ (?:lines|chars)\]/g,Mv={mint:m.mint};function aU(e){let t=Mv[e];if(t)return t;let n=e.lastIndexOf(":");if(n>=0){let r=e.slice(n+1),o=Mv[r];if(o)return o}return null}function jn(e,t){return rU.level===0?e:e.replace(oU,o=>{let s=o.slice(1);return t.has(s)?(aU(s)??m.brand)(o):m.meta(o)}).replace(sU,o=>m.fileRef(o)).replace(iU,o=>m.meta(o))}z();var Ov=/[\x00-\x1F\x7F-\x9F]/g;function We(e){return Ee(e).replace(Ov," ").replace(/ {2,}/g," ").trim()}function Up(e){return Ee(e).replace(Ov," ")}function si(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+=$v(e.slice(r,i)),n+=s,r=i+s.length}return n+=$v(e.slice(r)),n}function $v(e){return e.replace(/\/(?:[^/\s,)]+\/){2,}([^/\s,)]+)/g,"$1")}function lU(e){let t=/^(\s*[("]?\s*)cd\s+\S+\s+&&\s+(?!cd\s)(.+)$/.exec(e);return t?(t[1]??"")+(t[2]??""):e}var Dv=60;function jp(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=We(i);if(a.length===0)continue;return`(${a.length>Dv?oe(a,Dv,"\u2026"):a})`}}return e}function Lv(e,t){if(e==="bash"||e==="Bash")return lU(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"?jp(t,["id_prefix","prompt"]):e==="Task"?jp(t,["description","prompt"]):e==="skill"||e==="Skill"?jp(t,["name","arguments"]):e==="ask_question"?cU(t):t}function cU(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 uU(e){return e.replace(/[\r\n]+/g," ")}var dU={"(":")","{":"}","[":"]"};function Fv(e,t,n="\u2026"){let r=e.charAt(0),o=dU[r];return!(o&&e.endsWith(o)&&e.length>=2)||q(e)<=t?oe(e,t,n):t<3?t>=2?r+o:oe(e,t,n):oe(e,t-1,n)+o}function pn(e,t){let n=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/s.exec(e);if(n){let r=n[1],o=si(Lv(r,n[2]??"")),s=In(r),{color:i,glyph:a}=Co(r),l=Td(s),c=l?` [${l}]`:"";if(t!==void 0){let d=(a+" ").length+r.length+c.length,p=Math.max(1,t-d);o=Fv(o,p)}o=uU(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)}z();var Nv=8,jl=30;function pU(){let e=T.AFK_DIFF_LINES;if(e===void 0)return jl;let t=e.trim();if(!/^\d+$/.test(t))return jl;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:jl}function mU(){let e=T.AFK_SHOW_DIFFS;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"}function fU(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 gU=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;function hU(e){let t=Ee(e.text).replace(gU,"");return e.kind==="+"?m.diffAdd("+ "+t):e.kind==="-"?m.diffRemove("- "+t):m.dim(" "+t)}var Wp=new WeakMap;function mn(e,t,n){if(mU())return[];if(e.hunks.length===0)return[];let r=t==="overlay"?Nv:pU(),o=t+"|"+n+"|"+r,s=Wp.get(e);if(s!==void 0){let f=s.get(o);if(f!==void 0)return f}let i=[];i.push(n+fU(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:hU(h)})}if(r===0){for(let f of a)i.push(n+f.text);return Hp(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 Hp(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}`)),Hp(e,o,i),i}function Hp(e,t,n){let r=Wp.get(e);r===void 0&&(r=new Map,Wp.set(e,r)),r.set(t,n)}var yU=m.success("\u2713"),bU=m.error("\u2717");function Hn(e){return e?bU:yU}var ii=3,Bv=2,Uv=3;function jv(e){switch(In(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 wU(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 fn(e,t,n=60,r){let o=e.isError?m.error:m.dim,s=t??T.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;return o(`saved \u2192 ${a}`)}if(e.lineCount!==void 0&&e.lineCount>1)return o(`${e.lineCount} ${wU(r,e.lineCount)}`);let i=e.content.length>n?e.content.slice(0,n-3)+"\u2026":e.content;return o(We(i))}z();function ai(e,t){if(e.length<=t)return e;let n=e.slice(0,t),r=e.slice(t),o=Wv(r);return[...n,{kind:"overflow",count:r.length,text:o}]}function SU(e,t){return t<=1||e.endsWith("s")||/(sh|ch|x|z)$/i.test(e)?e:e+"s"}var kU=5,Hv=60;function Wv(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=>$e.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=We(u);if(!d){i=!0;break}let p=d.length>Hv?d.slice(0,Hv-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,kU),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} ${SU(s,i)}`);return`\u2026 +${n} (${o.join(", ")})`}function Hl(e,t=Rt()){return e.map((n,r)=>({sibling:n,connector:r===e.length-1?t.lastConnector:t.midConnector}))}function Kp(e,t){return t?[...e,{kind:"resultSummary",summary:t}]:e}function Gp(e){if(e.length===0)return[];let t=new Map;for(let o of e){let s=Kv(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=Kv(o),i=t.get(s);i.length>=vU(o.toolName)?r.has(s)||(n.push({kind:"group",toolName:o.toolName,label:$e.has(o.toolName)?o.toolInput:"",entries:i}),r.add(s)):n.push(o)}return n}function zp(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 pn(e.toolName+e.label)+m.dim(` \xD7${t} \u2014 ${s}`)}function Kv(e){return $e.has(e.toolName)?e.toolName+"::"+e.toolInput:e.toolName}function vU(e){return $e.has(e)?Bv:Uv}function Gv(e,t,n,r){return e>0||t?Ho([...n,!0],r):Ho(n,r)}function zv(e,t){return!$e.has(e.toolName)||e.headerEmitted!==!0?!1:(t.get(e.toolUseId)??[]).every(r=>r.kind==="tool"&&zv(r,t))}function Wl(e,t,n,r=Z(),o=[],s=Rt(),i){let a=Ho(o,s),l=li(a,s),c=e.filter(h=>h.kind==="text"),u=e.filter(h=>h.kind==="tool").filter(h=>!zv(h,t)),d=Gp(u),p=ai(d,ii),f=Hl(p,s);for(let{sibling:h,connector:b}of f){let y=m.dim(b),w=b===s.lastConnector;if(h.kind==="overflow")n.push(Ie(l+y+m.dim(h.text),r));else if(h.kind==="group")n.push(Ie(l+y+zp(h),r));else if(h.kind==="resultSummary")n.push(Ie(l+y+m.dim(h.summary),r));else{let S=h,E=t.get(S.toolUseId);if($e.has(S.toolName)&&E&&E.length>0){S.headerEmitted?n.push(Ie(l+y,r)):n.push(Ie(l+y+S.prefix,r));let k=i??w;if(Wl(E,t,n,r,[...o,k],s,w),S.thinkingTail){let R=li(Ho([...o,k],s),s);n.push(Ie(R+m.thinking("\u2307 "+We(S.thinkingTail)),r))}}else if(!($e.has(S.toolName)&&S.headerEmitted))if(S.result){if(n.push(Ie(l+y+S.prefix+m.dim(" \u2014 ")+Hn(S.result.isError)+" "+fn(S.result,void 0,60,S.toolName),r)),S.diff&&!S.result.isError){let k=l+(w?s.spineClosed:m.dim(s.spine))+" ";for(let R of mn(S.diff,"overlay",k))n.push(R)}}else{n.push(Ie(l+y+S.prefix,r));let k=l+(w?s.spineClosed:m.dim(s.spine))+" ";S.thinkingTail?n.push(Ie(k+m.thinking("\u2307 "+We(S.thinkingTail)),r)):n.push(Ie(k+m.dim(jv(S.toolName)),r))}}}let g=Gv(u.length,!1,o,s);for(let h of c)for(let b of qp(h.text,g,s))n.push(Ie(b,r))}function ci(e,t,n,r,o=Z(),s=[],i=Rt(),a){let l=Ho(s,i),c=li(l,i),u=[],d=e.filter(w=>w.kind==="text"),p=e.filter(w=>w.kind==="tool"),f=Gp(p),g=ai(f,ii),h=Kp(g,r),b=Hl(h,i);for(let{sibling:w,connector:S}of b){let E=m.dim(S),k=S===i.lastConnector;if(w.kind==="overflow")u.push(Ie(c+E+m.dim(w.text),o));else if(w.kind==="resultSummary")u.push(Ie(c+E+m.dim(w.summary),o));else if(w.kind==="group")u.push(Ie(c+E+zp(w),o));else{let R=w,_=t.get(R.toolUseId);if($e.has(R.toolName)&&_&&_.length>0){if(R.headerEmitted){let P=R.toolInput?`${R.toolName} ${We(R.toolInput)}`:R.toolName;u.push(Ie(c+E+m.dim("\u21B3 "+P),o))}else u.push(Ie(c+E+R.prefix,o));let A=a??k;u.push(...ci(_,t,n,void 0,o,[...s,A],i,k))}else if(R.result){if(u.push(Ie(c+E+R.prefix+m.dim(" \u2014 ")+Hn(R.result.isError)+" "+fn(R.result,n,60,R.toolName),o)),R.diff&&!R.result.isError){let A=c+(k?i.spineClosed:m.dim(i.spine))+" ";for(let P of mn(R.diff,"flush",A))u.push(P)}}else u.push(Ie(c+E+R.prefix,o))}}let y=Gv(p.length,r!=null,s,i);for(let w of d)for(let S of qp(w.text,y,i))u.push(Ie(S,o));return u}function ui(e,t,n,r,o=[]){let s=Rt(),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>ii&&(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=ci(t,n,r,e.agentResultSummary,Z(),d,s);return[f,...g].join(`
1747
1747
  `)}function Jp(e,t=[]){let n=Rt(),r=m.dim(n.spine.repeat(t.length)),o=m.dim(n.turnRoot);return r+o+e.prefix}function di(e,t,n,r,o=[]){let s=Rt(),i=o;return ci(t,n,r,e.agentResultSummary,Z(),i,s)}function Wo(e,t,n){let r=[];for(let o of t){let s=e.get(o);if(s.length===1){let i=s[0];if(i.result){if(r.push(" "+i.prefix+m.dim(" \u2014 ")+Hn(i.result.isError)+" "+fn(i.result,n,60,i.toolName)),i.diff&&!i.result.isError)for(let a of mn(i.diff,"flush"," "))r.push(a)}else r.push(" "+i.prefix)}else{r.push(qv(o,s,n));let i=s.filter(l=>l.diff&&l.result&&!l.result.isError),a=i.length>1;for(let l of i){if(a){let c=We(si(l.toolInput).trim()||l.toolInput.trim());r.push(" "+m.dim(`\u2500\u2500 ${c} \u2500\u2500`))}for(let c of mn(l.diff,"flush"," "))r.push(c)}}}return r}function qv(e,t,n){let{color:r,glyph:o}=Co(e),s=t.map(u=>We(si(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=>fn(d.result,n,60,d.toolName));return" "+i+m.dim(" \u2014 ")+u.join(m.dim(", "))}return" "+i}function Ie(e,t){return oe(e,t)}var Yp=Object.freeze({spine:"\u2502 ",spineClosed:" ",lead:" ",turnRoot:"\u25C9 ",midConnector:"\u251C\u2500 ",lastConnector:"\u2570\u2500 ",textPrefix:"\u2502 "}),TU=Object.freeze({spine:"| ",spineClosed:" ",lead:" ",turnRoot:"o ",midConnector:"+- ",lastConnector:"\\- ",textPrefix:"| "}),Sle=Yp.midConnector,kle=Yp.lastConnector;function Rt(){let e=T.AGENT_AFK_ASCII;return e&&/^(1|true|yes)$/i.test(e)?TU:Yp}function Ho(e,t){let n="";for(let r of e)n+=r?t.spineClosed:t.spine;return n+=t.spine,n}function li(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 qp(e,t,n){if(!e||!e.trim())return[];let r=m.dim(n.textPrefix),o=Math.max(1,Z()-t.length-2-2),s=li(t,n),i=[];for(let a of e.split(`
1748
1748
  `)){let l=Up(a),c=ue(l,o);for(let u of c.split(`
1749
- `))i.push(s+r+u)}return i}var Jv=6,pi=class{entries=new Map;order=[];agentIdStack=[];addStart(t,n,r){let o=Ee(r),s=pn(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),io.has(n)&&this.agentIdStack.push(t)}addStartWithAgentContext(t,n,r,o,s){let i=Ee(r),a=this.entries.get(t);if(a?.kind==="tool"){a.toolInput=i,a.prefix=pn(n+i,s),o!==void 0&&(a.agentContext=o);return}let l=pn(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"||!io.has(o.toolName)||o.toolName==="Agent")return!1;let i=`(${Ee(n)})`;return o.toolName="Agent",o.toolInput=i,o.prefix=pn("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"}getOverlay(){let t=this.buildChildMap(),n=[],r=Rt(),o=Z(),s=c=>oe(c,o),i=[];for(let c of this.order){let u=this.entries.get(c);!u||u.kind!=="tool"||u.agentContext||i.push(u)}let a=i,l=0;if(i.length>Jv){let c=i.filter(f=>!f.result),u=i.filter(f=>f.result),d=Math.max(0,Jv-c.length),p=new Set(u.slice(-d));l=u.length-p.size,a=i.filter(f=>!f.result||p.has(f))}for(let c of a){let u=t.get(c.toolUseId);if($e.has(c.toolName)&&u&&u.length>0)c.headerEmitted?n.push(s(m.dim(r.turnRoot))):n.push(s(m.dim(r.turnRoot)+c.prefix)),Wl(u,t,n,o,void 0,r),c.thinkingTail&&n.push(s(m.dim(r.spine)+m.thinking("\u2307 "+We(c.thinkingTail))));else if(!($e.has(c.toolName)&&c.headerEmitted))if($e.has(c.toolName))c.result?n.push(s(m.dim(r.turnRoot)+c.prefix+m.dim(" \u2014 ")+Hn(c.result.isError)+" "+fn(c.result,void 0,60,c.toolName))):n.push(s(m.dim(r.turnRoot)+c.prefix+m.dim(" \u2026"))),c.thinkingTail&&n.push(s(m.dim(r.spine)+m.thinking("\u2307 "+We(c.thinkingTail))));else if(c.result){if(n.push(s(" "+c.prefix+m.dim(" \u2014 ")+Hn(c.result.isError)+" "+fn(c.result,void 0,60,c.toolName))),c.diff&&!c.result.isError)for(let d of mn(c.diff,"overlay"," "))n.push(s(d))}else n.push(s(" "+c.prefix+m.dim(" \u2026"))),c.thinkingTail&&n.push(s(m.dim(r.spine)+m.thinking("\u2307 "+We(c.thinkingTail))))}return l>0&&n.push(s(" "+m.dim(`\u2026 +${l} done`))),n.join(`
1749
+ `))i.push(s+r+u)}return i}var Jv=6,pi=class{entries=new Map;order=[];agentIdStack=[];addStart(t,n,r){let o=Ee(r),s=pn(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),io.has(n)&&this.agentIdStack.push(t)}addStartWithAgentContext(t,n,r,o,s){let i=Ee(r),a=this.entries.get(t);if(a?.kind==="tool"){a.toolInput=i,a.prefix=pn(n+i,s),o!==void 0&&(a.agentContext=o);return}let l=pn(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"||!io.has(o.toolName)||o.toolName==="Agent")return!1;let i=`(${Ee(n)})`;return o.toolName="Agent",o.toolInput=i,o.prefix=pn("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"}getOverlay(){let t=this.buildChildMap(),n=[],r=Rt(),o=Z(),s=d=>oe(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>Jv){let d=i.filter(h=>!h.result),p=i.filter(h=>h.result),f=Math.max(0,Jv-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=>$e.has(d.toolName))?m.dim(r.turnRoot):" ";for(let d of a){let p=t.get(d.toolUseId);if($e.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)),Wl(p,t,n,o,void 0,r),d.thinkingTail&&n.push(s(m.dim(r.spine)+m.thinking("\u2307 "+We(d.thinkingTail))));else if(!($e.has(d.toolName)&&d.headerEmitted))if($e.has(d.toolName))d.result?n.push(s(m.dim(r.turnRoot)+d.prefix+m.dim(" \u2014 ")+Hn(d.result.isError)+" "+fn(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 "+We(d.thinkingTail))));else if(d.result){if(n.push(s(u+d.prefix+m.dim(" \u2014 ")+Hn(d.result.isError)+" "+fn(d.result,void 0,60,d.toolName))),d.diff&&!d.result.isError)for(let f of mn(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 "+We(d.thinkingTail))))}return l>0&&n.push(s(" "+m.dim(`\u2026 +${l} done`))),n.join(`
1750
1750
  `)}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(Jp(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?di(r,c,l,n,o).join(`
1751
1751
  `):ui(r,c,l,n,o);for(let p of i)this.entries.delete(p);this.order=this.order.filter(p=>!i.has(p));let d=u===""?[]:[u];return[...s,...d]}flushCompletedRoots(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let c of this.order){let u=this.entries.get(c);!u||u.kind!=="tool"||u.agentContext||u.result!==void 0&&r.push(c)}if(r.length===0)return[];let o=[],s=new Map,i=[];for(let c of r){let u=this.entries.get(c);if(!u||u.kind!=="tool")continue;let d=n.get(u.toolUseId);if($e.has(u.toolName))if(o.push(...Wo(s,i,t)),s.clear(),i.length=0,u.headerEmitted){let p=di(u,d??[],n,t,[]);o.push(...p)}else o.push(ui(u,d??[],n,t));else s.has(u.toolName)||(s.set(u.toolName,[]),i.push(u.toolName)),s.get(u.toolName).push(u)}o.push(...Wo(s,i,t));let a=new Set(r),l=[...r];for(;l.length>0;){let c=l.shift();for(let[u,d]of this.entries){if(a.has(u))continue;(d.kind==="tool",d.agentContext)===c&&(a.add(u),d.kind==="tool"&&l.push(u))}}for(let c of a)this.entries.delete(c);return this.order=this.order.filter(c=>!a.has(c)),o}flush(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let a of this.order){let l=this.entries.get(a);!l||l.kind!=="tool"||l.agentContext||r.push(a)}let o=[],s=new Map,i=[];for(let a of r){let l=this.entries.get(a);if(!l||l.kind!=="tool")continue;let c=n.get(l.toolUseId);if($e.has(l.toolName))if(o.push(...Wo(s,i,t)),s.clear(),i.length=0,l.headerEmitted){let u=di(l,c??[],n,t,[]);o.push(...u)}else o.push(ui(l,c??[],n,t));else s.has(l.toolName)||(s.set(l.toolName,[]),i.push(l.toolName)),s.get(l.toolName).push(l)}return o.push(...Wo(s,i,t)),this.entries.clear(),this.order=[],this.agentIdStack=[],o}buildChildMap(){let t=new Map;for(let n of this.order){let r=this.entries.get(n);if(!r)continue;let o=(r.kind==="tool",r.agentContext);if(!o)continue;let s=t.get(o);s||(s=[],t.set(o,s)),s.push(r)}return t}};function Vp(e,t){let n=Math.max(0,e),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(t/4);return` ${m.thinking("\u25C6 thought for "+r+" \xB7 "+o+" tok")}`}var Ko=class{buffer="";startedAt=null;endedAt=null;hasEmitted=!1;committedUpTo=0;push(t){this.hasEmitted||(this.buffer+=t,this.startedAt||(this.startedAt=Date.now()))}markEnded(){this.endedAt===null&&this.startedAt!==null&&(this.endedAt=Date.now())}isActive(){return!this.hasEmitted}hasBufferedContent(){return this.buffer.trim().length>0}peek(){return this.buffer}consume(){return this.hasEmitted=!0,this.buffer}peekPhase(){return this.buffer.slice(this.committedUpTo)}drainPhase(){let t=this.buffer.slice(this.committedUpTo);return this.committedUpTo=this.buffer.length,t}collapse(){if(this.hasEmitted||!this.startedAt)return!this.startedAt&&!this.hasEmitted&&Ue()&&console.error("[afk:thinking] collapse() short-circuited: no thinking chunks received this turn. Model may not support extended thinking, or API ignored the thinking parameter."),null;this.hasEmitted=!0;let t=this.endedAt??Date.now();return Vp(t-this.startedAt,this.buffer.length)}inlineSummary(){if(!this.startedAt||!this.hasBufferedContent())return null;let t=this.endedAt??Date.now(),n=Math.max(0,t-this.startedAt),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(this.buffer.length/4);return`thought ${r} \xB7 ${o} tok`}};var Xp="__main__";function Vv(e){let t={startedAt:Date.now(),lastEventAt:Date.now(),stats:{tokens:0,toolUses:0},contentBuffer:"",done:!1,errored:!1,stalledTicks:0};return e!==void 0&&(t.agentType=e),t}function Go(e,t){return{type:"tool_result",toolUseId:"synthetic",content:e,isError:t}}function Xv(e){let t=["Done"],n=[];e.stats.toolUses&&n.push(`${e.stats.toolUses} tool${e.stats.toolUses===1?"":"s"}`),e.stats.tokens&&n.push(`${ne(e.stats.tokens)} tok`);let r=e.responseMetadata?.durationMs,o=Date.now()-e.startedAt;typeof r=="number"&&(n.push(te(r)),o>r*1.5&&o-r>=1e3&&n.push(`${te(o)} wall`)),n.length===0&&o>0&&n.push(te(o));let s=e.thinkingLane?.inlineSummary();return s&&n.push(s),n.length>0&&t.push(`(${n.join(" \xB7 ")})`),t.join(" ")}function Zp(e){let t=Math.max(1,Z()-2);return Math.max(1,t-e)}function Zv(e,t){return xU(e)?kt(e,{maxWidth:t}):ue(e,t)}function Qv(e,t,n){if(!n||!e.trim())return"";let r;return tT(e)?r=`
1752
1752
  \u258D streaming code\u2026
@@ -1877,7 +1877,7 @@ ${E}`})}return{fileBlocks:a,warnings:l}}async function aE(e,t,n,r,o="summary",s,
1877
1877
  `))!==-1;){let u=n.slice(0,c);n=n.slice(c+1),this.opts.writeLine(u)}},s={command:t,mode:"foreground",onChunk:c=>{r||(n+=c.toString("utf8"),o())}},i=this.opts.getCwd();i!==void 0&&(s.cwd=i);let{job:a,handle:l}=this.registry.start(s);this.activeFgJobId=a.id;try{let c=await l.promise;r=!0,n.length>0&&(this.opts.writeLine(n),n=""),this.opts.writeLine(KW(a,c)),this.queueInjection({command:t,mode:"foreground",result:c})}finally{this.activeFgJobId=null}}startBackground(t){let n={command:t,mode:"background"},r=this.opts.getCwd();r!==void 0&&(n.cwd=r);let{job:o}=this.registry.start(n);this.opts.writeLine(m.dim(` [${o.id}] background: `)+t)}queueInjection(t){this.pendingInjections.push(t),this.pendingInjections.length>e.MAX_PENDING_INJECTIONS&&this.pendingInjections.shift()}};function zW(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 qW(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)))}}}function Lc(e,t){let n=m.brand("afk")+m.dim(` (${e})`),r=t?m.warning(" \u25CF plan"):"";return n+r+m.dim(" \u203A ")}async function gE(e,t,n,r){let o=null,s=[];e.session.current.waitForInitialization().then(async S=>{Ue()&&(o=gl(S)),await lc(e.session.current),Ue()&&(s=sx())}).catch(()=>{});let i=await Yx(),a=new Oc({rl:e.rl,history:i,statusLine:e.statusLine}),l,c,u,d,p,f,g,h=!1,b=!1,y=gv({onError:S=>Y("[afk suggest] Tier-2 completion failed:",S)}),w=zW(T.AFK_SUGGEST_GHOST,e.suggestGhostConfig);try{await a.armCompositor({promptFn:()=>Lc(e.stats.model,e.stats.planMode),onCancel:r,onShiftTab:()=>{let C=e.slashCtx;C.stats.planMode&&C.stats.pendingPlanExit?(C.stats.pendingPlanExit=!1,Et(C,!1,{closureSummarySkipped:!0}).catch(()=>{})):Et(C).catch(()=>{}),e.statusLine.rearm()},scrollRegion:e.statusLine,...e.preArmAnchorRow!==void 0?{anchorRow:e.preArmAnchorRow}:{},...w?{suggest:{engine:y,getContext:()=>({model:e.stats.model,apiKey:e.suggestApiKey,baseUrl:e.suggestBaseUrl,cwd:e.stats.cwd??process.cwd(),getHistory:()=>{let C=a.history;return C.getEntries?[...C.getEntries()]:[]},getDropdownTopCandidate:C=>{let D=a.autocompleteState.candidates[0];return D&&D.value.startsWith(C)&&D.value.length>C.length?D.value:null},getTranscriptTail:()=>"",getRecentCommands:()=>[],llmEnabled:()=>/^(1|true|yes|on)$/i.test(T.AFK_SUGGEST_ENABLED??"")})}}:{}});let S=a.getCompositor();Ft.install(dl({readLine:C=>a.readLine({promptFn:()=>C}).then(L=>L.text),writer:{line:(C="")=>{let L=a.getCompositor();L?L.commitAbove(C):process.stdout.write(C+`
1878
1878
  `)}},pendingCount:()=>Ft.pendingCount(),...S?{pickFromList:C=>eE(S,C),readTextOverlay:C=>tE(S,C)}:{}})),e.replRenderer.setCompositor(a.getCompositor()),e.slashCtx.getCompositor=()=>a.getCompositor();let E=a.getCompositor();if(E){let C=L=>E.commitAbove(L);e.completionWriter.fn=C,e.completionWriter.idleFn=C}e.slashCtx.setSoftStopHandler=C=>a.setSoftStopHandler(C),e.inputSurfaceRef&&(e.inputSurfaceRef.current=a),c=lE(),g=cE(),e.clearVerdictLedger=()=>g?.reset(),u=new vl,Ik(u),Bk(u),Hk(u),Uk(e.backgroundRegistry);let k=0,R=0,_=1,A=()=>e.statusLine.setExtraRows(_+k+R);g.setRowCountChangeHandler(C=>{R=C,A(),d?.redraw(),p?.redraw()}),d=new $c(u,e.backgroundRegistry,{getAdjacentRows:()=>R}),d.setRowCountChangeHandler(C=>{k=C,A()}),p=new Gl({getExtraRows:()=>e.statusLine.getExtraRows()}),p.setRowCountChangeHandler(C=>{A()}),e.statusLine.setAfterScrollRestore(()=>{g?.repaint(),d?.redraw(),p?.redraw()}),d.start(),p.start(),g.start({stream:process.stdout});let P=50,I=[];for(u.on("complete",C=>{I.length>=P&&I.shift(),I.push(C)}),f=new Dc({writeLine:C=>e.replRenderer.writeLine(C),getCwd:()=>e.stats.cwd}),Fk(f),n.tryAbortShellForeground=()=>f.abortActiveForeground();;){if(o&&(e.replRenderer.writeLine(o),e.replRenderer.writeLine(""),o=null),s.length>0){for(let x of s)e.replRenderer.writeLine(x);e.replRenderer.writeLine(""),s=[]}for(;I.length>0;){let x=I.shift(),O=x.status==="succeeded"?"\u2713":"\u2717",B=[];if(x.resultText){let H=x.resultText.trim().split(`
1879
1879
  `)[0]?.slice(0,80)??"";H&&B.push(H)}x.error&&B.push(x.error.message);let J=[x.stats.toolUses>0?`${x.stats.toolUses} tools`:"",x.stats.tokens>0?`${Math.round(x.stats.tokens/1e3)}k tok`:"",x.stats.durationMs>0?`${Math.round(x.stats.durationMs/1e3)}s`:""].filter(Boolean).join(" \xB7 ");J&&B.push(J),e.replRenderer.writeLine(xn({kind:x.status==="succeeded"?"checkpoint":"diagnosis",title:`${O} ${x.id} ${x.label}`,body:B})),e.replRenderer.writeLine("")}let C=f.drainNotifications();for(let{job:x,result:O}of C){let B=O.errorReason===void 0?"\u2713":"\u2717",J=O.errorReason==="abort"?"killed":O.errorReason==="timeout"?"timed out":O.errorReason==="signal-killed"?"killed by signal":`exit ${O.exitCode??0}`,H=Math.max(0,Math.round(O.durationMs/100)/10);e.replRenderer.writeLine(m.dim(` ${B} [${x.id}] ${J} \xB7 ${H}s \xB7 `)+x.command)}let L=c.renderIfChanged(e.stats.sessionId);if(L.length>0){for(let x of L)e.replRenderer.writeLine(x);e.replRenderer.writeLine("")}let D,j;if(l!==void 0){let x=l;l=void 0;let O=Lc(e.stats.model,e.stats.planMode),B=br({buffer:x.text,promptText:O,isTTY:!!process.stdout.isTTY,attachmentSummary:Bo([...x.attachments])});e.replRenderer.writeLine(B),D=x.text.trim(),j=x.attachments}else{let x=await a.readLine({promptFn:()=>Lc(e.stats.model,e.stats.planMode),onSigint:r,onShiftTab:()=>{let O=e.slashCtx;O.stats.planMode&&O.stats.pendingPlanExit?(O.stats.pendingPlanExit=!1,Et(O,!1,{closureSummarySkipped:!0}).catch(()=>{})):Et(O).catch(()=>{}),e.statusLine.rearm()}});D=x.text.trim(),j=x.attachments}if(!D&&j.length===0)continue;if(D.startsWith("!")){let x=/^(0|false|off|no)$/i.test(T.AFK_SHELL_PASSTHROUGH??"");if(e.options.shellPassthrough!==!1&&!x&&(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 f.dispatch(D))){e.statusLine.rearm();continue}}let N=!1;if(D.startsWith("/")){let x=await GS(D,e.slashCtx,j);if(x.handled){if(x.result==="exit"){e.rl.close();return}if((D==="/clear"||D.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),g.reset()),x.result!==null&&typeof x.result=="object"&&"kind"in x.result&&x.result.kind==="submit"){l={text:x.result.message,attachments:j??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}N=!0}i.push(D),await qW(e,D);let W=D;if(N){let x=mp(D);if(x){let O=x.name.replace(/^\//,"").split(":").pop()??"";if(O&&gm(O)){let B={skillName:O,rawArgs:x.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},J=e.session.current.sessionId,H=Cr(J),F=Date.now();Y(`[afk trace] preflight.start commandName=${O}`);let V=!1,ye=await Ar(B,{cwd:e.stats.cwd??process.cwd(),artifactDir:H},Ne=>{Ue()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${O}) failed: `)+(Ne instanceof Error?Ne.message:String(Ne)))});V=ye!==null,Y(`[afk trace] preflight.end commandName=${O} durationMs=${Date.now()-F} success=${V}`),W=bm(ye?.manifestBlock,D)}}}let M=f.drainInjections();M.length>0&&(W=M+W),await aE({text:W,attachments:j},e.session.current,e.stats,{setInFlight(x){n.turnInFlight=x},async onTurnComplete(x,O){if(await t.appendTurn(x,O),e.stats.sessionId)try{Ht(e.stats)}catch(B){b||(b=!0,e.replRenderer.writeLine(m.warning("\u26A0 ")+"session autosave failed \u2014 this conversation may not be resumable: "+(B instanceof Error?B.message:String(B))))}},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await sk(e.slashCtx),e.statusLine.rearm(),p?.repaint("observing")},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:x=>g?.push(x),setActiveCompositor:x=>{n.activeCompositor=x},setInterruptNotifier:x=>{n.notifyInterrupting=x},scrollRegion:e.statusLine,getCompositor:()=>a.getCompositor(),setBackgroundHandler:x=>a.setBackgroundHandler(x),setSoftStopHandler:x=>a.setSoftStopHandler(x),async onContextProgress(){await e.contextSampler.refresh(),e.statusLine.repaint(yr(e.stats,e.contextSampler))},...p?{onStageChange:x=>p.repaint(x)}:{}},e.options.thinkingUi,e.completionWriter,u,a.toRunTurnRefs(Lc(e.stats.model,e.stats.planMode)))}}finally{if(u!==void 0)for(let E of u.running())u.cancel(E.id);n.tryAbortShellForeground=null,f?.drainOnExit(),p?.stop(),d?.stop(),g?.stop(),c?.dispose();let S=E=>console.log(E);e.completionWriter.fn=S,e.completionWriter.idleFn=S,await a.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}import{execFile as JW}from"node:child_process";import{dirname as YW,isAbsolute as VW,resolve as XW}from"node:path";import{promisify as ZW}from"node:util";var hE=ZW(JW),QW=3e3,eK=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function tK(){let t=(await hE("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=VW(t)?t:XW(process.cwd(),t);return YW(n)}async function yE(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await tK()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),QW)});try{let o=zt({execFile:hE,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=>eK.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}import{promises as nK}from"node:fs";import{dirname as rK,join as SE}from"node:path";import{randomBytes as oK}from"node:crypto";var sK=["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(`
1880
- `),bE=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Wm=30,iK=1024,aK=8e3,lK="haiku";async function cK(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=mK(n,iK),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??aK),i=t.signal?fK([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await Zr({token:t.token,model:t.model??lK,system:sK,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=uK(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=rK(t.worktreePath);return await dK(l,c)}function uK(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(bE.test(t)&&t.length<=Wm)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>Wm)break;o=i}return bE.test(o)?o:null}async function dK(e,t){if(!await pK(SE(t,e)))return e;let n=oK(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Wm-5)}-${n}`}async function pK(e){try{return await nK.access(e),!0}catch{return!1}}function mK(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 fK(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 kE(e){let t,n,r=SE(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await cK(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=`${Ba(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return wE(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 wE(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 wE(e,t){e&&e.setCwd(t),gK(t)}function gK(e){try{process.chdir(e)}catch{}}K();import{spawn as vE}from"child_process";import{existsSync as SK,mkdirSync as kK,readFileSync as TE,unlinkSync as vK,writeFileSync as TK}from"fs";import{get as xK}from"https";import{join as xE}from"path";import{readFileSync as hK}from"fs";import{dirname as yK,join as bK}from"path";import{fileURLToPath as wK}from"url";function yn(){try{return"3.81.0"}catch{}try{let e=yK(wK(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(hK(bK(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}z();var EK=64*1024,RK=1440*60*1e3,AK="update-check.json",CK="pending-update.json";function EE(){return xE(Hi(),AK)}function Km(){return xE(Hi(),CK)}function RE(){let e=Hi();SK(e)||kK(e,{recursive:!0})}function _K(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){let i=n[s]??0,a=r[s]??0;if(a>i)return!0;if(a<i)return!1}return!1}function IK(){try{let e=TE(EE(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function PK(){try{RE();let e=`
1880
+ `),bE=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Wm=30,iK=1024,aK=8e3,lK="haiku";async function cK(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=mK(n,iK),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??aK),i=t.signal?fK([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await Zr({token:t.token,model:t.model??lK,system:sK,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=uK(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=rK(t.worktreePath);return await dK(l,c)}function uK(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(bE.test(t)&&t.length<=Wm)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>Wm)break;o=i}return bE.test(o)?o:null}async function dK(e,t){if(!await pK(SE(t,e)))return e;let n=oK(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Wm-5)}-${n}`}async function pK(e){try{return await nK.access(e),!0}catch{return!1}}function mK(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 fK(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 kE(e){let t,n,r=SE(e.deferred.repoRoot,".afk-worktrees","unnamed"),o=await cK(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=`${Ba(e.branchPrefix)}${o}`;try{let c=await e.deferred.create(l);return wE(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 wE(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 wE(e,t){e&&e.setCwd(t),gK(t)}function gK(e){try{process.chdir(e)}catch{}}K();import{spawn as vE}from"child_process";import{existsSync as SK,mkdirSync as kK,readFileSync as TE,unlinkSync as vK,writeFileSync as TK}from"fs";import{get as xK}from"https";import{join as xE}from"path";import{readFileSync as hK}from"fs";import{dirname as yK,join as bK}from"path";import{fileURLToPath as wK}from"url";function yn(){try{return"3.81.1"}catch{}try{let e=yK(wK(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(hK(bK(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}z();var EK=64*1024,RK=1440*60*1e3,AK="update-check.json",CK="pending-update.json";function EE(){return xE(Hi(),AK)}function Km(){return xE(Hi(),CK)}function RE(){let e=Hi();SK(e)||kK(e,{recursive:!0})}function _K(e,t){let n=e.split(".").map(Number),r=t.split(".").map(Number),o=Math.max(n.length,r.length);for(let s=0;s<o;s++){let i=n[s]??0,a=r[s]??0;if(a>i)return!0;if(a<i)return!1}return!1}function IK(){try{let e=TE(EE(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function PK(){try{RE();let e=`
1881
1881
  const https = require('https');
1882
1882
  const fs = require('fs');
1883
1883
  const url = 'https://registry.npmjs.org/agent-afk/latest';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-afk",
3
- "version": "3.81.0",
3
+ "version": "3.81.1",
4
4
  "description": "CLI tool for interacting with AI agents via multiple interfaces",
5
5
  "main": "dist/index.mjs",
6
6
  "type": "module",