agent-afk 2.14.3 → 2.15.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.
Files changed (2) hide show
  1. package/dist/cli.mjs +4 -4
  2. package/package.json +1 -1
package/dist/cli.mjs CHANGED
@@ -1858,17 +1858,17 @@ ${a}
1858
1858
  \u258D streaming code\u2026
1859
1859
  `:this.hasMarkdownContent(this.buffer)?t=Ve(this.buffer,{maxWidth:o}):t=this.buffer;let s=Z(t,o),i=this.applyIndent(s);if(this.compositor){this.compositor.setOverlay(i);return}this.logUpdate||await this.initLogUpdate(),this.logUpdate&&(this.flushing||this.logUpdate(i))}push(t){if(this.flushing)return;this.buffer+=t;let n=this.findBlockBoundary(this.buffer);for(;n!==-1;){let r=this.buffer.slice(0,n);this.buffer=this.buffer.slice(n),this.commitBlock(r),n=this.findBlockBoundary(this.buffer)}this.scheduleRepaint()}async flush(){this.throttleTimer&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.flushing=!0,this.compositor&&this.compositor.setOverlay(""),this.buffer.trim()&&(this.commitBlock(this.buffer),this.buffer=""),!this.compositor&&(this.isTTY&&this.logUpdate?(this.logUpdate.clear(),this.out.write(this.committed+`
1860
1860
  `)):this.committed&&this.out.write(this.committed+`
1861
- `))}getCommittedOutput(){return this.committed}getPendingBuffer(){return this.buffer}commitPending(){this.buffer.trim()&&(this.commitBlock(this.buffer),this.buffer="",this.compositor&&this.compositor.setOverlay(""))}dispose(){this.throttleTimer&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.logUpdate&&(this.logUpdate.clear(),this.logUpdate=null),this.buffer="",this.committed=""}};var Iv=["observing","modeling","choosing","acting","updating"],Mv={observing:"observe",modeling:"model",choosing:"choose",acting:"act",updating:"update"};function Gp(){return{stage:"observing",pendingTools:new Set}}function zp(e,t){let n=e.stage;switch(t.type){case"chunk":{let r=t.chunk;r.type==="tool_use_detail"?(e.pendingTools.add(r.toolUseId),e.stage="acting"):r.type==="tool_result"?(e.pendingTools.delete(r.toolUseId),e.stage=e.pendingTools.size>0?"acting":"updating"):r.type==="thinking"?e.pendingTools.size===0&&(e.stage="modeling"):r.type==="content"&&e.pendingTools.size===0&&(e.stage="choosing");break}case"done":e.pendingTools.clear();break;default:break}return e.stage!==n}function qp(e,t){return Iv.map(r=>{let o=r===e,s=o?"\u25C6":"\u25C7",i=Mv[r],a=`${s} ${i}`;return o?t.accent(t.bold(a)):t.dim(a)}).join(t.dim(" \xB7 "))}function Yp(e,t,n,r){switch(n.stageTracker&&zp(n.stageTracker,e)&&n.isTTY&&en(n,r),e.type){case"progress":r.set(e.progress.taskId,e.progress),n.isTTY&&en(n,r);return;case"chunk":{let o=e.chunk;if(o.type==="tool_use_detail")n.streamingMarkdown.current?.commitPending(),n.toolLane.addStartWithAgentContext(o.toolUseId,o.toolName,o.toolInput,void 0),t.stats.toolUses+=1,n.isTTY&&n.compositor&&n.compositor.setSpinner({enabled:!0,rotateVerbEveryMs:3500}),n.isTTY&&en(n,r);else if(o.type==="tool_result")n.streamingMarkdown.current?.commitPending(),n.toolLane.addResult(o.toolUseId,o),n.isTTY&&en(n,r);else if(o.type==="content"){let s=Ni(o.content);if(n.activeSkillName&&!n.skillBadgeEmitted){let i=Fi(s,n.activeSkillName);if(s=i.text,i.found){n.skillBadgeEmitted=!0;let{color:a,glyph:l}=Si("skill"),c=" "+a(l+" ")+a.bold(n.activeSkillName);n.isTTY&&n.compositor?n.compositor.commitAbove(c):n.out.line(c)}}else n.activeSkillName&&(s=Fi(s,n.activeSkillName).text);if(!s)return;t.contentBuffer+=s,n.isTTY&&(n.compositor&&n.compositor.setSpinner({enabled:!1}),qi(n,{afterContent:!!n.streamingMarkdown.current}),n.streamingMarkdown.current||(n.streamingMarkdown.current=new Ko({...n.compositor?{compositor:n.compositor}:{}})),n.streamingMarkdown.current.push(s))}else if(o.type==="thinking"){if(n.thinkingMode==="off")return;n.thinkingLane.push(o.content),n.thinkingMode==="live"&&n.isTTY&&en(n,r)}return}case"message":t.contentBuffer||(t.contentBuffer=Ni(e.message.content));return;case"error":t.errored=!0,Dv(e.error,n.out);return;case"done":t.done=!0,e.metadata&&(t.responseMetadata=e.metadata),Ov(t,n);return;case"suggestion":return;case"panel":$v(e.spec,t,n);return}}function $v(e,t,n){n.streamingMarkdown.current?n.streamingMarkdown.current.commitPending():t.contentBuffer.trim()&&(Vp(t.contentBuffer,n.out),t.contentBuffer=""),qi(n,{afterContent:!0});let o=wt(e).split(`
1861
+ `))}getCommittedOutput(){return this.committed}hasEmitted(){return this.buffer.length>0||this.committed.length>0}getPendingBuffer(){return this.buffer}commitPending(){this.buffer.trim()&&(this.commitBlock(this.buffer),this.buffer="",this.compositor&&this.compositor.setOverlay(""))}dispose(){this.throttleTimer&&(clearTimeout(this.throttleTimer),this.throttleTimer=null),this.logUpdate&&(this.logUpdate.clear(),this.logUpdate=null),this.buffer="",this.committed=""}};var Iv=["observing","modeling","choosing","acting","updating"],Mv={observing:"observe",modeling:"model",choosing:"choose",acting:"act",updating:"update"};function Gp(){return{stage:"observing",pendingTools:new Set}}function zp(e,t){let n=e.stage;switch(t.type){case"chunk":{let r=t.chunk;r.type==="tool_use_detail"?(e.pendingTools.add(r.toolUseId),e.stage="acting"):r.type==="tool_result"?(e.pendingTools.delete(r.toolUseId),e.stage=e.pendingTools.size>0?"acting":"updating"):r.type==="thinking"?e.pendingTools.size===0&&(e.stage="modeling"):r.type==="content"&&e.pendingTools.size===0&&(e.stage="choosing");break}case"done":e.pendingTools.clear();break;default:break}return e.stage!==n}function qp(e,t){return Iv.map(r=>{let o=r===e,s=o?"\u25C6":"\u25C7",i=Mv[r],a=`${s} ${i}`;return o?t.accent(t.bold(a)):t.dim(a)}).join(t.dim(" \xB7 "))}function Yp(e,t,n,r){switch(n.stageTracker&&zp(n.stageTracker,e)&&n.isTTY&&en(n,r),e.type){case"progress":r.set(e.progress.taskId,e.progress),n.isTTY&&en(n,r);return;case"chunk":{let o=e.chunk;if(o.type==="tool_use_detail")n.streamingMarkdown.current?.commitPending(),n.toolLane.addStartWithAgentContext(o.toolUseId,o.toolName,o.toolInput,void 0),t.stats.toolUses+=1,n.isTTY&&n.compositor&&n.compositor.setSpinner({enabled:!0,rotateVerbEveryMs:3500}),n.isTTY&&en(n,r);else if(o.type==="tool_result")n.streamingMarkdown.current?.commitPending(),n.toolLane.addResult(o.toolUseId,o),n.isTTY&&en(n,r);else if(o.type==="content"){let s=Ni(o.content);if(n.activeSkillName&&!n.skillBadgeEmitted){let i=Fi(s,n.activeSkillName);if(s=i.text,i.found){n.skillBadgeEmitted=!0;let{color:a,glyph:l}=Si("skill"),c=" "+a(l+" ")+a.bold(n.activeSkillName);n.isTTY&&n.compositor?n.compositor.commitAbove(c):n.out.line(c)}}else n.activeSkillName&&(s=Fi(s,n.activeSkillName).text);if(!s)return;t.contentBuffer+=s,n.isTTY&&(n.compositor&&n.compositor.setSpinner({enabled:!1}),qi(n,{afterContent:!!n.streamingMarkdown.current}),n.streamingMarkdown.current||(n.streamingMarkdown.current=new Ko({...n.compositor?{compositor:n.compositor}:{}})),n.streamingMarkdown.current.push(s))}else if(o.type==="thinking"){if(n.thinkingMode==="off")return;n.thinkingLane.push(o.content),n.thinkingMode==="live"&&n.isTTY&&en(n,r)}return}case"message":t.contentBuffer||(t.contentBuffer=Ni(e.message.content));return;case"error":t.errored=!0,Dv(e.error,n.out);return;case"done":t.done=!0,e.metadata&&(t.responseMetadata=e.metadata),Ov(t,n);return;case"suggestion":return;case"panel":$v(e.spec,t,n);return}}function $v(e,t,n){n.streamingMarkdown.current?n.streamingMarkdown.current.commitPending():t.contentBuffer.trim()&&(Vp(t.contentBuffer,n.out),t.contentBuffer=""),qi(n,{afterContent:!0});let o=wt(e).split(`
1862
1862
  `);if(n.isTTY&&n.compositor)for(let s of o)n.compositor.commitAbove(s);else for(let s of o)n.out.line(s)}function Ov(e,t){if(!t.streamingMarkdown.current&&e.contentBuffer.trim()&&Vp(e.contentBuffer,t.out),e.contentBuffer="",t.coordinator){if(t.toolLane.hasPending()){let n=t.toolLane.flush(),r=t.compositor,o=t.isTTY,s=t.out;t.coordinator.schedule({anchor:"before-content",commits:[()=>{if(o&&r){r.commitAbove("");for(let i of n)r.commitAbove(i);r.commitAbove(""),r.setOverlay("")}else{s.line("");for(let i of n)s.line(i);s.line("")}}]})}if(t.thinkingMode!=="off"){let n=t.thinkingLane.collapse();if(n){let r=n,o=t.compositor,s=t.isTTY,i=t.out;t.coordinator.schedule({anchor:"after-content",commits:[()=>{s&&o?o.commitAbove(r):i.line(r)}]})}}}else if(qi(t,{afterContent:!0}),t.thinkingMode!=="off"){let n=t.thinkingLane.collapse();n&&(t.isTTY&&t.compositor?t.compositor.commitAbove(n):t.out.line(n))}}function Vp(e,t){let n=Ve(e);for(let r of n.split(`
1863
1863
  `))t.line(r)}function Dv(e,t){let n=Ir(e.message,e.stack);for(let r of n.split(`
1864
1864
  `))t.line(r)}function qi(e,t){if(!e.toolLane.hasPending())return;let n=e.toolLane.flush(),r=t?.afterContent??!1;if(e.isTTY&&e.compositor){r&&e.compositor.commitAbove("");for(let o of n)e.compositor.commitAbove(o);e.compositor.commitAbove(""),e.compositor.setOverlay("")}else{r&&e.out.line("");for(let o of n)e.out.line(o);e.out.line("")}}function en(e,t){if(!e.compositor)return;let n=[];if(e.stageTracker&&n.push(" "+qp(e.stageTracker.stage,{dim:d.dim,accent:d.brand,bold:d.bold})),e.thinkingMode==="live"&&e.thinkingLane.hasBufferedContent()){let o=e.thinkingLane.peek(),s=80,i=[...o],a=i.length>s,c=(a?i.slice(-s).join(""):o).replace(/\s+/g," ").trim(),p=a?"\u2026":"";n.push(" "+d.thinking("\u25C6 "+p+c))}e.toolLane.hasPending()&&n.push(e.toolLane.getOverlay());let r=[];for(let o of t.values())r.push(...cd(o));r.length>0&&n.push(r.join(`
1865
1865
  `)),e.compositor.setOverlay(n.join(`
1866
1866
  `))}var Go=class{beforeContent=[];afterSubagent=new Map;afterContent=[];schedule(t){let{anchor:n}=t;if(n==="before-content")this.beforeContent.push(t);else if(n==="after-content")this.afterContent.push(t);else{let r=n.slice(15),o=this.afterSubagent.get(r);o||(o=[],this.afterSubagent.set(r,o)),o.push(t)}}drainSubagent(t){for(let r of this.beforeContent.splice(0))for(let o of r.commits)o();let n=this.afterSubagent.get(t);if(n){this.afterSubagent.delete(t);for(let r of n)for(let o of r.commits)o()}}async flushAll(t){for(let n of this.beforeContent.splice(0))for(let r of n.commits)r();if(t)try{await t()}catch{}for(let[n,r]of Array.from(this.afterSubagent)){this.afterSubagent.delete(n);for(let o of r)for(let s of o.commits)s()}for(let n of this.afterContent.splice(0))for(let r of n.commits)r()}};function Jp(e,t){let n=e.trimEnd();if(!n.trim())return"";let r=Math.max(t*4,400),o=n.length>r?n.slice(-r):n,s=/[.!?](?=\s)|\n+/g,i=-1,a;for(;(a=s.exec(o))!==null;)i=a.index+a[0].length;let l=i>=0?o.slice(i):o;return l=l.replace(/\s+/g," ").trim(),l?(l.length>t&&(l=l.slice(0,Math.max(1,t-1))+"\u2026"),l):""}function Yi(e,t){if(!(!e||!e.trim())&&!t.isTTY)for(let n of Lv(e))t.out.line(n)}function Lv(e){if(!e)return[];let t=d.dim("\u2502 "),n=" ",r=Math.max(1,J()-n.length-2-2),o=[];for(let s of e.split(`
1867
1867
  `)){let i=Z(s,r);for(let a of i.split(`
1868
- `))o.push(n+t+a)}return o}function Xp(e,t,n,r){if(t.syntheticAgentToolUseId)return;let o=t.agentType?.trim()||"agent";if(r!==void 0&&n.toolLane.mergeAgentLabel(r,o)){t.syntheticAgentToolUseId=r;return}let s=`__synth_agent_${e}`;n.toolLane.addStartWithAgentContext(s,"Agent",`(${o})`,r),t.syntheticAgentToolUseId=s}function Zp(e,t,n,r){let o=n.syntheticAgentToolUseId;if(o)switch(e.type){case"progress":e.progress.totalTokens&&(n.stats.tokens=e.progress.totalTokens),e.progress.toolUses!==void 0&&(n.stats.progressReportedToolUses=e.progress.toolUses);return;case"chunk":{let s=e.chunk;if(s.type==="tool_use_detail"){n.currentTextEntryId=void 0;let i=r.streamingMarkdown.get(t);i&&i.commitPending(),r.toolLane.setThinkingTail(o,void 0);let a=process.stdout.columns??100,l=Math.max(20,a-14);r.toolLane.addStartWithAgentContext(s.toolUseId,s.toolName,s.toolInput,o,l),n.stats.toolUses+=1,r.isTTY&&r.compositor&&r.compositor.setOverlay(r.toolLane.getOverlay())}else if(s.type==="tool_result"){let i=r.streamingMarkdown.get(t);i&&i.commitPending(),r.toolLane.addResult(s.toolUseId,s),r.isTTY&&r.compositor&&r.compositor.setOverlay(r.toolLane.getOverlay())}else if(s.type==="content")if(n.currentTextEntryId||(n.currentTextEntryId="__in_text_block__"),n.contentBuffer+=s.content,r.isTTY&&r.compositor){if(s.content.trim()){let i=process.stdout.columns??100,a=Math.max(20,i-14),l=Jp(n.contentBuffer,a);r.toolLane.setThinkingTail(o,l||void 0)}r.compositor.setOverlay(r.toolLane.getOverlay())}else{let i=n.contentBuffer.lastIndexOf(`
1868
+ `))o.push(n+t+a)}return o}function Xp(e,t,n,r){if(t.syntheticAgentToolUseId)return;let o=t.agentType?.trim()||"agent",s=process.stdout.columns??100,i=Math.max(20,s-14);if(r!==void 0&&n.toolLane.mergeAgentLabel(r,o,i)){t.syntheticAgentToolUseId=r;return}let a=`__synth_agent_${e}`;n.toolLane.addStartWithAgentContext(a,"Agent",`(${o})`,r,i),t.syntheticAgentToolUseId=a}function Zp(e,t,n,r){let o=n.syntheticAgentToolUseId;if(o)switch(e.type){case"progress":e.progress.totalTokens&&(n.stats.tokens=e.progress.totalTokens),e.progress.toolUses!==void 0&&(n.stats.progressReportedToolUses=e.progress.toolUses);return;case"chunk":{let s=e.chunk;if(s.type==="tool_use_detail"){n.currentTextEntryId=void 0;let i=r.streamingMarkdown.get(t);i&&i.commitPending(),r.toolLane.setThinkingTail(o,void 0);let a=process.stdout.columns??100,l=Math.max(20,a-14);r.toolLane.addStartWithAgentContext(s.toolUseId,s.toolName,s.toolInput,o,l),n.stats.toolUses+=1,r.isTTY&&r.compositor&&r.compositor.setOverlay(r.toolLane.getOverlay())}else if(s.type==="tool_result"){let i=r.streamingMarkdown.get(t);i&&i.commitPending(),r.toolLane.addResult(s.toolUseId,s),r.isTTY&&r.compositor&&r.compositor.setOverlay(r.toolLane.getOverlay())}else if(s.type==="content")if(n.currentTextEntryId||(n.currentTextEntryId="__in_text_block__"),n.contentBuffer+=s.content,r.isTTY&&r.compositor){if(s.content.trim()){let i=process.stdout.columns??100,a=Math.max(20,i-14),l=Jp(n.contentBuffer,a);r.toolLane.setThinkingTail(o,l||void 0)}r.compositor.setOverlay(r.toolLane.getOverlay())}else{let i=n.contentBuffer.lastIndexOf(`
1869
1869
  `);if(i!==-1){let a=n.contentBuffer.slice(0,i);n.contentBuffer=n.contentBuffer.slice(i+1),Yi(a,r)}}else if(s.type==="thinking"){if(r.thinkingMode==="off")return;if(n.thinkingLane||(n.thinkingLane=new An),n.thinkingLane.push(s.content),r.thinkingMode==="live"&&r.isTTY&&r.compositor){let i=process.stdout.columns??100,a=Math.max(20,i-14),l=Jp(n.thinkingLane.peek(),a);l&&r.toolLane.setThinkingTail(o,l),r.compositor.setOverlay(r.toolLane.getOverlay())}}return}case"message":return;case"error":n.errored=!0,r.toolLane.setThinkingTail(o,void 0),r.toolLane.addResult(o,pr(`error \u2014 ${e.error.message}`,!0)),r.isTTY&&r.compositor&&r.compositor.setOverlay(r.toolLane.getOverlay());return;case"done":n.done=!0,e.metadata&&(n.responseMetadata=e.metadata),Fv(t,n,r);return;case"suggestion":return;case"panel":Nv(e.spec,t,n,r);return}}function Nv(e,t,n,r){if(r.isTTY){let s=n.syntheticAgentToolUseId;s&&r.toolLane.setThinkingTail(s,void 0),n.contentBuffer=""}else n.contentBuffer.trim()&&(Yi(n.contentBuffer,r),n.contentBuffer="");let o=wt(e);for(let s of o.split(`
1870
1870
  `))r.isTTY&&r.compositor?r.compositor.commitAbove(s):r.out.line(s)}function Fv(e,t,n){let r=t.syntheticAgentToolUseId;if(!r||t.errored)return;if(!n.isTTY&&t.contentBuffer&&Yi(t.contentBuffer,n),t.contentBuffer="",!n.isTTY&&t.thinkingLane?.hasBufferedContent()){let s=t.thinkingLane.collapse();s&&n.out.line(s)}n.toolLane.setThinkingTail(r,void 0);let o=Kp(t);n.toolLane.setAgentResultSummary(r,o),n.toolLane.addResult(r,pr(o,!1)),n.isTTY&&n.compositor&&n.compositor.setOverlay(n.toolLane.getOverlay())}var Uv=3e4,jv=" \xB7 paused ",Bv=375,Lt=class{out;thinkingMode;isTTY;onCancel;onBackground;activeSkillName;coordinator=new Go;compositor=null;streamingMarkdownRef={current:null};toolLane=new dr;thinkingLane=new An;stageTracker=Gp();sources=new Map;subagentMarkdown=new Map;lastProgressByTask=new Map;disposed=!1;pauseTickInterval=null;sink;constructor(t){this.out=t.out,this.thinkingMode=t.thinkingMode??(t.verbose===!0?"live":"summary"),this.onCancel=t.onCancel,this.onBackground=t.onBackground,this.isTTY=!(t.forceNonTty??!1)&&!!process.stdout.isTTY&&!!process.stdin.isTTY,this.activeSkillName=t.activeSkillName,this.sink=(n,r)=>this.process(n,r)}async arm(){if(this.disposed||!this.isTTY||this.compositor)return;let t=new Wo({stdout:process.stdout,stdin:process.stdin,...this.onCancel?{onCancel:this.onCancel}:{},...this.onBackground?{onBackground:this.onBackground}:{}});await t.arm(),this.compositor=t,t.setSpinner({enabled:!0,rotateVerbEveryMs:3500}),this.pauseTickInterval=setInterval(()=>this.checkPauseAnnotations(),80)}makeOrchestratorCtx(){return{out:this.out,isTTY:this.isTTY,compositor:this.compositor,toolLane:this.toolLane,thinkingLane:this.thinkingLane,thinkingMode:this.thinkingMode,streamingMarkdown:this.streamingMarkdownRef,coordinator:this.coordinator,...this.isTTY?{stageTracker:this.stageTracker}:{},...this.activeSkillName?{activeSkillName:this.activeSkillName}:{}}}getCompositor(){return this.compositor}makeSubagentCtx(){return{isTTY:this.isTTY,compositor:this.compositor,toolLane:this.toolLane,out:this.out,streamingMarkdown:this.subagentMarkdown,thinkingMode:this.thinkingMode}}process(t,n){if(this.disposed)return;let r=n?.subagentId??zi,o=r===zi,s=this.sources.get(r);if(!s&&(s=Hp(n?.agentType),this.sources.set(r,s),!o)){let i;if(n?.parentId!==void 0){let a=this.sources.get(n.parentId);a!==void 0?i=a.syntheticAgentToolUseId:this.toolLane.hasEntry(n.parentId)?i=n.parentId:xe()&&process.stderr.write(`[stream-renderer] parentId_fallback_unresolved ${JSON.stringify({parentId:n.parentId,sourceId:r})}
1871
- `)}Xp(r,s,this.makeSubagentCtx(),i)}if(o)Yp(t,s,this.makeOrchestratorCtx(),this.lastProgressByTask);else{if(Zp(t,r,s,this.makeSubagentCtx()),s.lastEventAt=Date.now(),s.pauseAnnotation!==void 0&&s.syntheticAgentToolUseId){s.pauseAnnotation=void 0,s.stalledTicks=0;let i=s.agentType??r;this.toolLane.addStartWithAgentContext(s.syntheticAgentToolUseId,"Agent",`(${i})`,void 0)}if(t.type==="done"&&this.isTTY){let i=s.syntheticAgentToolUseId;if(i&&this.toolLane.hasEntry(i)){let l=this.toolLane.flushSource(i),c=this.compositor,p=this.toolLane,u=this.out;this.coordinator.schedule({anchor:`after-subagent:${r}`,commits:[()=>{if(c){for(let m of l)c.commitAbove(m);c.setOverlay(p.getOverlay())}else for(let m of l)u.line(m)}]}),this.streamingMarkdownRef.current||this.coordinator.drainSubagent(r)}let a=this.makeOrchestratorCtx();en(a,this.lastProgressByTask)}}}async dispose(){if(this.disposed)return;this.disposed=!0;let t=this.streamingMarkdownRef.current?()=>this.streamingMarkdownRef.current.flush():void 0;await this.coordinator.flushAll(t),this.streamingMarkdownRef.current&&(this.streamingMarkdownRef.current.dispose(),this.streamingMarkdownRef.current=null);for(let n of this.subagentMarkdown.values()){try{await n.flush()}catch{}n.dispose()}if(this.subagentMarkdown.clear(),this.toolLane.hasPending()){let n=this.toolLane.flush();if(this.isTTY&&this.compositor){for(let r of n)this.compositor.commitAbove(r);this.compositor.setOverlay(this.toolLane.getOverlay())}else for(let r of n)this.out.line(r)}if(this.pauseTickInterval&&(clearInterval(this.pauseTickInterval),this.pauseTickInterval=null),this.compositor){try{this.compositor.disarm()}catch{}this.compositor=null}}checkPauseAnnotations(){if(this.disposed)return;let t=!1,n=Date.now();for(let[r,o]of this.sources){if(o.done||o.errored||!o.syntheticAgentToolUseId)continue;let s=n-o.lastEventAt;if(s>Uv)if(o.stalledTicks+=1,o.stalledTicks>=Bv*2)xe()&&process.stderr.write(`[stream-renderer] auto_settle_timeout ${JSON.stringify({sourceId:r,elapsedMs:s,syntheticAgentToolUseId:o.syntheticAgentToolUseId})}
1871
+ `)}Xp(r,s,this.makeSubagentCtx(),i)}if(o)Yp(t,s,this.makeOrchestratorCtx(),this.lastProgressByTask);else{if(Zp(t,r,s,this.makeSubagentCtx()),s.lastEventAt=Date.now(),s.pauseAnnotation!==void 0&&s.syntheticAgentToolUseId){s.pauseAnnotation=void 0,s.stalledTicks=0;let i=s.agentType??r;this.toolLane.addStartWithAgentContext(s.syntheticAgentToolUseId,"Agent",`(${i})`,void 0)}if(t.type==="done"&&this.isTTY){let i=s.syntheticAgentToolUseId;if(i&&this.toolLane.hasEntry(i)){let l=this.toolLane.flushSource(i),c=this.compositor,p=this.toolLane,u=this.out;this.coordinator.schedule({anchor:`after-subagent:${r}`,commits:[()=>{if(c){for(let m of l)c.commitAbove(m);c.setOverlay(p.getOverlay())}else for(let m of l)u.line(m)}]}),(!this.streamingMarkdownRef.current||!this.streamingMarkdownRef.current.hasEmitted())&&this.coordinator.drainSubagent(r)}let a=this.makeOrchestratorCtx();en(a,this.lastProgressByTask)}}}async dispose(){if(this.disposed)return;this.disposed=!0;let t=this.streamingMarkdownRef.current?()=>this.streamingMarkdownRef.current.flush():void 0;await this.coordinator.flushAll(t),this.streamingMarkdownRef.current&&(this.streamingMarkdownRef.current.dispose(),this.streamingMarkdownRef.current=null);for(let n of this.subagentMarkdown.values()){try{await n.flush()}catch{}n.dispose()}if(this.subagentMarkdown.clear(),this.toolLane.hasPending()){let n=this.toolLane.flush();if(this.isTTY&&this.compositor){for(let r of n)this.compositor.commitAbove(r);this.compositor.setOverlay(this.toolLane.getOverlay())}else for(let r of n)this.out.line(r)}if(this.pauseTickInterval&&(clearInterval(this.pauseTickInterval),this.pauseTickInterval=null),this.compositor){try{this.compositor.disarm()}catch{}this.compositor=null}}checkPauseAnnotations(){if(this.disposed)return;let t=!1,n=Date.now();for(let[r,o]of this.sources){if(o.done||o.errored||!o.syntheticAgentToolUseId)continue;let s=n-o.lastEventAt;if(s>Uv)if(o.stalledTicks+=1,o.stalledTicks>=Bv*2)xe()&&process.stderr.write(`[stream-renderer] auto_settle_timeout ${JSON.stringify({sourceId:r,elapsedMs:s,syntheticAgentToolUseId:o.syntheticAgentToolUseId})}
1872
1872
  `),this.toolLane.addResult(o.syntheticAgentToolUseId,pr("[no-result \u2014 timed out]",!1)),o.done=!0,t=!0;else{let i=o.agentType??r,a=jv+de(s);o.pauseAnnotation!==a&&(o.pauseAnnotation=a,this.toolLane.addStartWithAgentContext(o.syntheticAgentToolUseId,"Agent",`(${i})${a}`,void 0),t=!0)}}t&&this.isTTY&&this.compositor&&this.compositor.setOverlay(this.toolLane.getOverlay())}};function _n(){return{line(e=""){console.log(e)},raw(e){process.stdout.write(e)},success(e){console.log(d.success("\u2713 ")+e)},info(e){console.log(d.info("\u2139 ")+e)},warn(e){console.log(d.warning("\u26A0 ")+e)},error(e){console.log(d.error("\u2717 ")+e)}}}var Wv="You are initializing this project for use with AFK (an AI agent CLI).\n\nYour job: scan this project and generate an `AFK.md` file in the project root. AFK.md is a plain markdown file (no YAML frontmatter) that serves as the system prompt for all AFK sessions in this project.\n\n## Steps\n\n1. **Discover project metadata** \u2014 read these files if they exist:\n - `package.json`, `tsconfig.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`, `Makefile`, `CMakeLists.txt`\n - `.github/workflows/` (CI config)\n - `docker-compose.yml`, `Dockerfile`\n - `README.md` or `README`\n - Any existing `CLAUDE.md` or `AGENTS.md` (borrow relevant context)\n\n2. **Scan directory structure** \u2014 list top-level directories and key subdirectories to understand the project layout.\n\n3. **Generate AFK.md** with these sections:\n - **What This Is** \u2014 one-paragraph description of the project (language, framework, purpose)\n - **Commands** \u2014 build, test, lint, dev commands (extracted from package.json scripts, Makefile targets, etc.)\n - **Architecture** \u2014 key directories and their purpose, entry points, major subsystems\n - **Conventions** \u2014 coding style, naming patterns, anything notable from config files (strictness levels, linting rules)\n - Only include sections where you found real content. Skip empty sections.\n\n4. **Write the file** \u2014 write AFK.md to the project root. Keep it concise \u2014 under 150 lines. This file is loaded into every session, so brevity matters.\n\n## Format rules\n- Plain markdown, no YAML frontmatter\n- Use code blocks for commands\n- Use tables for directory layouts\n- Don't include boilerplate or filler \u2014 every line should earn its place",tm={name:"/init",summary:"Scan project and generate AFK.md",async handler(e,t){let n=em(process.cwd(),"AFK.md"),r=em(process.cwd(),"CLAUDE.md"),o=[];o.push({type:"text",text:jo("init",t)});let s=Wv;if(Qp(n)&&!t.includes("--force")&&(s+=`
1873
1873
 
1874
1874
  ## Existing AFK.md detected
@@ -1950,7 +1950,7 @@ _ended: ${new Date().toISOString()}_
1950
1950
  `)&&(s+=`
1951
1951
  `),s+=`${n}
1952
1952
  `,await ma.writeFile(t,s,"utf8")}function lE(e,t,n){if(!ds(e))return new Error(`git worktree add failed: ${String(e)}`);let r=e.stderr??"",o=e.message??"",s=`${r}
1953
- ${o}`;return s.includes("already checked out")||s.includes("is already used by worktree")?new Error(`Branch '${t}' is already checked out in another worktree. Pick a different name.`):s.includes("already exists")?new Error(`Worktree path '${n}' already exists. Remove it or pick a different branch name.`):new Error(o||r||"git worktree add failed")}async function bf(e,t){let n=t?.execFile??nE,r=await iE(n),o=e===!0?oE():e;sE(o);let s=o.replaceAll("/","-"),i=fa(r,".afk-worktrees",s);await aE(r);try{await n("git",["-C",r,"worktree","add","-b",o,i])}catch(l){throw lE(l,o,i)}let a=async()=>{let l;try{l=await n("git",["-C",i,"status","--porcelain"])}catch(c){let p=ds(c)?c.message||c.stderr||"":String(c);console.warn(`Worktree cleanup: could not check status at ${i} (${p}). Skipping removal \u2014 manual cleanup may be needed.`);return}if(l.stdout.trim().length>0){console.log(`Worktree preserved at ${i} (branch: ${o}) \u2014 uncommitted changes.`);return}try{await n("git",["-C",r,"worktree","remove","--force",i])}catch(c){let p=ds(c)?c.message||c.stderr||"":String(c);console.warn(`Worktree cleanup: 'git worktree remove --force ${i}' failed (${p}). Manual removal may be needed.`);return}try{await n("git",["-C",r,"branch","-d",o])}catch(c){let p=ds(c)?c.message||c.stderr||"":String(c);console.warn(`Could not delete branch '${o}': ${p}`)}};try{let l="",c="";try{l=(await n("git",["-C",r,"rev-parse","HEAD"])).stdout.trim()}catch{}try{c=(await n("git",["-C",r,"symbolic-ref","--short","HEAD"])).stdout.trim()}catch{}let p={owner:"interactive",createdAt:new Date().toISOString(),baseSha:l,baseBranch:c};await ma.writeFile(fa(i,".afk-worktree-meta.json"),JSON.stringify(p,null,2),"utf-8")}catch{}return{path:i,branch:o,cleanup:a}}import{spawn as kf}from"child_process";import{existsSync as mE,mkdirSync as fE,readFileSync as wf,unlinkSync as gE,writeFileSync as hE}from"fs";import{get as yE}from"https";import{join as Sf}from"path";import{readFileSync as cE}from"fs";import{dirname as uE,join as dE}from"path";import{fileURLToPath as pE}from"url";function an(){try{return"2.14.3"}catch{}try{let e=uE(pE(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(cE(dE(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}var bE=64*1024,kE=1440*60*1e3,wE="update-check.json",SE="pending-update.json";function vf(){return Sf(Tr(),wE)}function ga(){return Sf(Tr(),SE)}function Tf(){let e=Tr();mE(e)||fE(e,{recursive:!0})}function vE(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 TE(){try{let e=wf(vf(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function xE(){try{Tf();let e=`
1953
+ ${o}`;return s.includes("already checked out")||s.includes("is already used by worktree")?new Error(`Branch '${t}' is already checked out in another worktree. Pick a different name.`):s.includes("already exists")?new Error(`Worktree path '${n}' already exists. Remove it or pick a different branch name.`):new Error(o||r||"git worktree add failed")}async function bf(e,t){let n=t?.execFile??nE,r=await iE(n),o=e===!0?oE():e;sE(o);let s=o.replaceAll("/","-"),i=fa(r,".afk-worktrees",s);await aE(r);try{await n("git",["-C",r,"worktree","add","-b",o,i])}catch(l){throw lE(l,o,i)}let a=async()=>{let l;try{l=await n("git",["-C",i,"status","--porcelain"])}catch(c){let p=ds(c)?c.message||c.stderr||"":String(c);console.warn(`Worktree cleanup: could not check status at ${i} (${p}). Skipping removal \u2014 manual cleanup may be needed.`);return}if(l.stdout.trim().length>0){console.log(`Worktree preserved at ${i} (branch: ${o}) \u2014 uncommitted changes.`);return}try{await n("git",["-C",r,"worktree","remove","--force",i])}catch(c){let p=ds(c)?c.message||c.stderr||"":String(c);console.warn(`Worktree cleanup: 'git worktree remove --force ${i}' failed (${p}). Manual removal may be needed.`);return}try{await n("git",["-C",r,"branch","-d",o])}catch(c){let p=ds(c)?c.message||c.stderr||"":String(c);console.warn(`Could not delete branch '${o}': ${p}`)}};try{let l="",c="";try{l=(await n("git",["-C",r,"rev-parse","HEAD"])).stdout.trim()}catch{}try{c=(await n("git",["-C",r,"symbolic-ref","--short","HEAD"])).stdout.trim()}catch{}let p={owner:"interactive",createdAt:new Date().toISOString(),baseSha:l,baseBranch:c};await ma.writeFile(fa(i,".afk-worktree-meta.json"),JSON.stringify(p,null,2),"utf-8")}catch{}return{path:i,branch:o,cleanup:a}}import{spawn as kf}from"child_process";import{existsSync as mE,mkdirSync as fE,readFileSync as wf,unlinkSync as gE,writeFileSync as hE}from"fs";import{get as yE}from"https";import{join as Sf}from"path";import{readFileSync as cE}from"fs";import{dirname as uE,join as dE}from"path";import{fileURLToPath as pE}from"url";function an(){try{return"2.15.0"}catch{}try{let e=uE(pE(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(cE(dE(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}var bE=64*1024,kE=1440*60*1e3,wE="update-check.json",SE="pending-update.json";function vf(){return Sf(Tr(),wE)}function ga(){return Sf(Tr(),SE)}function Tf(){let e=Tr();mE(e)||fE(e,{recursive:!0})}function vE(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 TE(){try{let e=wf(vf(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function xE(){try{Tf();let e=`
1954
1954
  const https = require('https');
1955
1955
  const fs = require('fs');
1956
1956
  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": "2.14.3",
3
+ "version": "2.15.0",
4
4
  "description": "CLI tool for interacting with AI agents via multiple interfaces",
5
5
  "main": "dist/index.mjs",
6
6
  "type": "module",