agent-afk 3.26.0 → 3.26.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.
- package/dist/cli.mjs +2 -2
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -2003,7 +2003,7 @@ ${d}`}function Id(e,t){let n=Sb[t.status];e.out.line(` ${n} ${m.bold(t.jobId)}
|
|
|
2003
2003
|
end try
|
|
2004
2004
|
return "no"
|
|
2005
2005
|
end try
|
|
2006
|
-
`;return new Promise(r=>{let o=Kb("osascript",["-e",n],{stdio:["ignore","pipe","pipe"]}),s="",i="";o.stdout?.on("data",a=>{s+=a.toString("utf8")}),o.stderr?.on("data",a=>{i+=a.toString("utf8")}),o.on("error",()=>r({ok:!1,exitCode:null,stderr:i})),o.on("close",a=>{r({ok:a===0&&s.trim()==="ok",exitCode:a,stderr:i})})})}function Z0(e){return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function e$(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=4&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56?"image/gif":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":null}var Jb=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],r$=5e3;function o$(e){let t=Date.now()-e;if(t<r$)return"";let n=Math.floor(t/1e3);if(n<60)return m.dim(` ${n}s`);let r=Math.floor(n/60),o=n%60;return m.dim(` ${r}m${o.toString().padStart(2,"0")}s`)}function s$(e,t){let n=" \u{1F4A1} ",r=Math.max(8,t-n.length-1),o=e.length>r?e.slice(0,r-1)+"\u2026":e;return m.dim(n+o)}var Gr=class e{stdout;stdin;onCancel;onBackground;onShiftTab;promptTextFn;history;autocompleteState;formatInputBuffer;scrollRegion;captureMode;onSubmit;attachments=[];pasting=!1;pasteStartBufferLen=0;clipboardInFlight=!1;clipboardFailureMsg=null;inputMode="streaming";armed=!1;canceled=!1;backgrounded=!1;wasRaw=!1;logUpdate=null;overlay="";input=G.seed("");queued=!1;handleKeypress=null;resizeUnsub=null;spinner=null;spinnerInterval=null;committing=!1;static MAX_DROPDOWN_ROWS=6;constructor(t){this.stdout=t.stdout,this.stdin=t.stdin,this.onCancel=t.onCancel,this.onBackground=t.onBackground,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.captureMode=t.captureMode??!1,this.onSubmit=t.onSubmit}isArmed(){return this.armed}setOnSubmit(t){this.onSubmit=t??void 0}setOnCancel(t){this.onCancel=t??void 0}getOnCancel(){return this.onCancel}setOnBackground(t){this.onBackground=t??void 0}setOnShiftTab(t){this.onShiftTab=t??void 0}setInputMode(t){let n=this.inputMode;if(this.inputMode=t,n==="idle"&&t==="streaming"){this.canceled=!1,this.backgrounded=!1,this.autocompleteState?.reset(),this.repaint();return}if(t==="idle"&&this.queued&&this.onSubmit){let r=this.input.buffer,o=[...this.attachments],s=this.onSubmit;this.queued=!1,this.input=G.seed(""),this.attachments=[],this.repaint(),s({text:r,attachments:o});return}n!==t&&this.repaint()}getInputMode(){return this.inputMode}async arm(){if(this.armed)throw new Error("TerminalCompositor: arm() called while already armed");if(!(!this.stdout.isTTY||!this.stdin.isTTY)){this.logUpdate||(this.logUpdate=n$(this.stdout)),this.wasRaw=this.stdin.isRaw??!1;try{this.stdin.setRawMode(!0)}catch{this.logUpdate=null,this.wasRaw=!1;return}try{this.stdout.write("\x1B[?2004h")}catch{}this.stdin.resume(),t$(this.stdin),this.handleKeypress=(t,n)=>this.dispatchKey(t,n),this.stdin.on("keypress",this.handleKeypress),this.resizeUnsub=Ge.subscribe(()=>{this.armed&&(this.anchor(),this.repaint())}),this.armed=!0,this.canceled=!1,this.anchor(),this.repaint()}}anchor(){if(!this.stdout.isTTY)return;let t=this.stdout.rows,n=typeof t=="number"&&t>0?t:24,r=Math.max(1,n-1);try{this.stdout.write(`\x1B[${r};1H`)}catch{}}disarm(){if(this.spinnerInterval&&(clearInterval(this.spinnerInterval),this.spinnerInterval=null),this.spinner=null,!this.armed){this.resetState();return}if(this.handleKeypress&&(this.stdin.removeListener("keypress",this.handleKeypress),this.handleKeypress=null),this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null),this.logUpdate)try{this.logUpdate.clear(),this.logUpdate.done()}catch{}if(this.stdout.isTTY&&this.stdin.isTTY){try{this.stdout.write("\x1B[?2004l")}catch{}try{this.stdin.setRawMode(this.wasRaw)}catch{}}this.armed=!1,this.resetState()}setOverlay(t){t!==this.overlay&&(this.overlay=t,this.repaint())}setSpinner(t){if(!this.stdout.isTTY)return;if(!t.enabled){this.spinnerInterval&&(clearInterval(this.spinnerInterval),this.spinnerInterval=null),this.spinner&&(this.spinner=null,this.repaint());return}if(this.captureMode||this.spinner)return;let n=t.rotateVerbEveryMs??3500,r=Date.now();this.spinner={frameIndex:0,verb:Fd(),nextVerbRotateAt:r+n,startedAt:r,tipPool:Lb(),currentTip:null},this.spinnerInterval=setInterval(()=>this.tickSpinner(n),80),this.repaint()}tickSpinner(t){if(!this.spinner)return;this.spinner.frameIndex=(this.spinner.frameIndex+1)%Jb.length;let n=Date.now();n>=this.spinner.nextVerbRotateAt&&(this.spinner.verb=Fd(),this.spinner.nextVerbRotateAt=n+t),this.spinner.currentTip=Fb(this.spinner.tipPool,{startedAt:this.spinner.startedAt,now:n}),this.repaint()}commitAbove(t){let n=r=>{this.scrollRegion?this.scrollRegion.withFullScrollRegion(r):r()};if(!this.armed||!this.logUpdate){n(()=>{this.stdout.write(t+`
|
|
2006
|
+
`;return new Promise(r=>{let o=Kb("osascript",["-e",n],{stdio:["ignore","pipe","pipe"]}),s="",i="";o.stdout?.on("data",a=>{s+=a.toString("utf8")}),o.stderr?.on("data",a=>{i+=a.toString("utf8")}),o.on("error",()=>r({ok:!1,exitCode:null,stderr:i})),o.on("close",a=>{r({ok:a===0&&s.trim()==="ok",exitCode:a,stderr:i})})})}function Z0(e){return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function e$(e){return e.length>=8&&e[0]===137&&e[1]===80&&e[2]===78&&e[3]===71?"image/png":e.length>=3&&e[0]===255&&e[1]===216&&e[2]===255?"image/jpeg":e.length>=4&&e[0]===71&&e[1]===73&&e[2]===70&&e[3]===56?"image/gif":e.length>=12&&e[0]===82&&e[1]===73&&e[2]===70&&e[3]===70&&e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":null}var Jb=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],r$=5e3;function o$(e){let t=Date.now()-e;if(t<r$)return"";let n=Math.floor(t/1e3);if(n<60)return m.dim(` ${n}s`);let r=Math.floor(n/60),o=n%60;return m.dim(` ${r}m${o.toString().padStart(2,"0")}s`)}function s$(e,t){let n=" \u{1F4A1} ",r=Math.max(8,t-n.length-1),o=e.length>r?e.slice(0,r-1)+"\u2026":e;return m.dim(n+o)}var Gr=class e{stdout;stdin;onCancel;onBackground;onShiftTab;promptTextFn;history;autocompleteState;formatInputBuffer;scrollRegion;captureMode;onSubmit;attachments=[];pasting=!1;pasteStartBufferLen=0;clipboardInFlight=!1;clipboardFailureMsg=null;inputMode="streaming";armed=!1;canceled=!1;backgrounded=!1;wasRaw=!1;logUpdate=null;firstArm=!0;overlay="";input=G.seed("");queued=!1;handleKeypress=null;resizeUnsub=null;spinner=null;spinnerInterval=null;committing=!1;static MAX_DROPDOWN_ROWS=6;constructor(t){this.stdout=t.stdout,this.stdin=t.stdin,this.onCancel=t.onCancel,this.onBackground=t.onBackground,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.captureMode=t.captureMode??!1,this.onSubmit=t.onSubmit}isArmed(){return this.armed}setOnSubmit(t){this.onSubmit=t??void 0}setOnCancel(t){this.onCancel=t??void 0}getOnCancel(){return this.onCancel}setOnBackground(t){this.onBackground=t??void 0}setOnShiftTab(t){this.onShiftTab=t??void 0}setInputMode(t){let n=this.inputMode;if(this.inputMode=t,n==="idle"&&t==="streaming"){this.canceled=!1,this.backgrounded=!1,this.autocompleteState?.reset(),this.repaint();return}if(t==="idle"&&this.queued&&this.onSubmit){let r=this.input.buffer,o=[...this.attachments],s=this.onSubmit;this.queued=!1,this.input=G.seed(""),this.attachments=[],this.repaint(),s({text:r,attachments:o});return}n!==t&&this.repaint()}getInputMode(){return this.inputMode}async arm(){if(this.armed)throw new Error("TerminalCompositor: arm() called while already armed");if(!(!this.stdout.isTTY||!this.stdin.isTTY)){this.logUpdate||(this.logUpdate=n$(this.stdout)),this.wasRaw=this.stdin.isRaw??!1;try{this.stdin.setRawMode(!0)}catch{this.logUpdate=null,this.wasRaw=!1;return}try{this.stdout.write("\x1B[?2004h")}catch{}this.stdin.resume(),t$(this.stdin),this.handleKeypress=(t,n)=>this.dispatchKey(t,n),this.stdin.on("keypress",this.handleKeypress),this.resizeUnsub=Ge.subscribe(()=>{this.armed&&(this.anchor(),this.repaint())}),this.armed=!0,this.canceled=!1,this.firstArm?this.firstArm=!1:this.anchor(),this.repaint()}}anchor(){if(!this.stdout.isTTY)return;let t=this.stdout.rows,n=typeof t=="number"&&t>0?t:24,r=Math.max(1,n-1);try{this.stdout.write(`\x1B[${r};1H`)}catch{}}disarm(){if(this.spinnerInterval&&(clearInterval(this.spinnerInterval),this.spinnerInterval=null),this.spinner=null,!this.armed){this.resetState();return}if(this.handleKeypress&&(this.stdin.removeListener("keypress",this.handleKeypress),this.handleKeypress=null),this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null),this.logUpdate)try{this.logUpdate.clear(),this.logUpdate.done()}catch{}if(this.stdout.isTTY&&this.stdin.isTTY){try{this.stdout.write("\x1B[?2004l")}catch{}try{this.stdin.setRawMode(this.wasRaw)}catch{}}this.armed=!1,this.resetState()}setOverlay(t){t!==this.overlay&&(this.overlay=t,this.repaint())}setSpinner(t){if(!this.stdout.isTTY)return;if(!t.enabled){this.spinnerInterval&&(clearInterval(this.spinnerInterval),this.spinnerInterval=null),this.spinner&&(this.spinner=null,this.repaint());return}if(this.captureMode||this.spinner)return;let n=t.rotateVerbEveryMs??3500,r=Date.now();this.spinner={frameIndex:0,verb:Fd(),nextVerbRotateAt:r+n,startedAt:r,tipPool:Lb(),currentTip:null},this.spinnerInterval=setInterval(()=>this.tickSpinner(n),80),this.repaint()}tickSpinner(t){if(!this.spinner)return;this.spinner.frameIndex=(this.spinner.frameIndex+1)%Jb.length;let n=Date.now();n>=this.spinner.nextVerbRotateAt&&(this.spinner.verb=Fd(),this.spinner.nextVerbRotateAt=n+t),this.spinner.currentTip=Fb(this.spinner.tipPool,{startedAt:this.spinner.startedAt,now:n}),this.repaint()}commitAbove(t){let n=r=>{this.scrollRegion?this.scrollRegion.withFullScrollRegion(r):r()};if(!this.armed||!this.logUpdate){n(()=>{this.stdout.write(t+`
|
|
2007
2007
|
`)});return}this.committing=!0;try{this.logUpdate.clear(),n(()=>{this.stdout.write(t+`
|
|
2008
2008
|
`)})}finally{this.committing=!1}this.repaint()}getBuffer(){return{text:this.input.buffer,queued:this.queued}}getAttachments(){return[...this.attachments]}renderInputLine(){let t=this.queued?" "+m.dim("[queued]"):"",n=this.input.buffer.slice(0,this.input.cursor),r=ko(this.input.buffer,this.input.cursor),o=this.input.cursor<this.input.buffer.length?this.input.buffer.slice(this.input.cursor,r):" ",s=this.input.cursor<this.input.buffer.length?this.input.buffer.slice(r):"",i=this.formatInputBuffer?.(n)??n,a=this.formatInputBuffer?.(s)??s,l=m.user.inverse(o);return this.promptTextFn()+i+l+a+t}updateAutocomplete(){let t=this.autocompleteState;if(!t)return;t.trigger=es(this.input.buffer,this.input.cursor);let n=`${this.input.cursor}:${this.input.buffer}`;t.suppressedSignature!==null&&t.suppressedSignature!==n&&(t.suppressedSignature=null),t.trigger&&t.suppressedSignature===null?(t.trigger.kind==="slash"?t.candidates=ya(t.trigger.query).slice(0,12):t.trigger.kind==="file"?t.candidates=ba(t.trigger.query).slice(0,12):t.candidates=ts(t.trigger.command,t.trigger.query),t.dropdownOpen=t.candidates.length>0):(t.dropdownOpen=!1,t.candidates=[]),t.selectedIndex>=t.candidates.length&&(t.selectedIndex=Math.max(0,t.candidates.length-1)),t.viewportStart>t.selectedIndex&&(t.viewportStart=t.selectedIndex),t.selectedIndex>=t.viewportStart+e.MAX_DROPDOWN_ROWS&&(t.viewportStart=t.selectedIndex-e.MAX_DROPDOWN_ROWS+1)}renderDropdownRows(){let t=this.autocompleteState;if(!t?.dropdownOpen)return[];let n=this.stdout.columns||80;if(n<=40)return[];let r=Math.min(n-4,60),o=Math.min(t.candidates.length-t.viewportStart,e.MAX_DROPDOWN_ROWS),s=[];for(let i=0;i<o;i++){let a=t.viewportStart+i,l=t.candidates[a];if(!l)continue;let c=ha(l,a===t.selectedIndex,r,t.trigger?.kind),d=Pe(c).length,u=Math.max(0,Math.ceil(d/n)-1);s.push(c);for(let p=0;p<u;p++)s.push("")}return s}repaint(){if(!this.armed||!this.logUpdate||this.committing)return;let t=this.renderInputLine(),n=this.overlay?this.overlay.split(`
|
|
2009
2009
|
`):[],r=this.spinner?m.meta(`${Jb[this.spinner.frameIndex]} ${this.spinner.verb}...`)+o$(this.spinner.startedAt):null,o=this.spinner?.currentTip?s$(this.spinner.currentTip.text,this.stdout.columns??80):null,s=null;this.attachments.length>0?s=ka(this.attachments):this.clipboardFailureMsg!==null&&(s=m.dim(this.clipboardFailureMsg),this.clipboardFailureMsg=null);let i=this.renderDropdownRows(),a=Math.max(1,(this.stdout.rows??24)-1),l=(r?1:0)+(o?1:0)+(s?1:0)+1+i.length,c=Math.max(0,a-l),d=n.length>c?n.slice(-c):n,u=[];u.push(...d),r&&u.push(r),o&&u.push(o),s&&u.push(s),u.push(t),u.push(...i),this.logUpdate(u.join(`
|
|
@@ -2123,7 +2123,7 @@ _ended: ${new Date().toISOString()}_
|
|
|
2123
2123
|
`)}function sF(e){let t=[],n=(r,o)=>{o&&o.trim().length>0&&t.push({label:r,value:o.trim()})};switch(e.kind){case"done":n("done",e.whatWasDone),n("evidence",e.evidence),n("deferred",e.deferred);break;case"blocked":n("blocks",e.whatBlocks),n("unblock",e.unblockCondition),n("progress",e.alreadyDone);break;case"asking":n("question",e.question),n("resolves",e.assumption),n("after",e.followup);break;case"interrupted":n("was doing",e.whatWasInProgress),n("saved at",e.stateLocation),n("resume",e.resumeRequires);break}return t}function eS(e,t,n){let r=[];n&&n.trim().length>0&&r.push({type:"text",text:n}),e&&r.push({type:"text",text:e});for(let o of t)r.push({type:"image",source:{type:"base64",media_type:o.mediaType,data:o.bytes.toString("base64")}});return r}async function tS(e,t,n,r,o="summary",s,i,a){let l=Hb(e.text,e.attachments);r.setInFlight(!0);let c="",d=!1,u=!1,p=!1,f=!1,g,h=!1,b=[],y=new Map,w=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,E=r.getCompositor?r.getCompositor():null,x=()=>new Jr({out:Yr(s),thinkingMode:o,...w?{activeSkillName:w}:{},onCancel:()=>{t.interrupt().catch(R=>{ze()&&console.error(" "+m.error("session.interrupt() failed:"),R)})},...i?{onBackground:()=>{h=!0}}:{},...a?.history?{history:a.history}:{},...a?.autocompleteState?{autocompleteState:a.autocompleteState}:{},...a?.promptText!==void 0?{promptText:a.promptText}:{},...r.scrollRegion?{scrollRegion:r.scrollRegion}:{},...E?{compositor:E}:{}}),v=x(),S=async()=>{if(!p){p=!0;try{await v.dispose()}catch{}}},A=async()=>{await v.arm();let R=v.getCompositor();if(s&&R){let D=R;s.fn=_=>D.commitAbove(_)}r.setActiveCompositor?.(R),r.rearmStatus?.()};try{E?E.commitAbove(""):console.log(),await A(),i&&r.setBackgroundHandler&&r.setBackgroundHandler(()=>{h=!0});let R=e.attachments.length===0?e.text:eS(e.text,e.attachments),D=t.sendMessageStream(R);if(await rn((P,I)=>{v.process(P,I)},async()=>{for await(let P of D){if(h&&i){let I=w??e.text.slice(0,40),O=i.register(I),F=ia(O,i);aa(D,c,l,O,i,F,n,r.onTurnComplete,t.abortSignal),await S(),(s??{fn:console.log}).fn(m.dim(` \u2192 backgrounded as ${O.id}: ${O.label}`)),r.setInFlight(!1),r.rearmStatus?.();return}if(P.type==="chunk"&&P.chunk.type==="content"?(c+=P.chunk.content,d=!0):P.type==="message"&&!d&&(c=P.message.content),P.type==="chunk"&&P.chunk.type==="tool_use_detail"){let I=P.chunk,O={toolName:I.toolName,toolUseId:I.toolUseId,input:I.toolInput};y.set(I.toolUseId,O),b.push(O)}else if(P.type==="chunk"&&P.chunk.type==="tool_result"){let I=P.chunk,O=y.get(I.toolUseId);O&&(O.result=I.content,O.isError=I.isError,y.delete(I.toolUseId))}if(P.type==="paused"){await S(),(s??{fn:console.log}).fn(mm({reason:P.reason,...P.resetsAt!==void 0?{resetsAt:P.resetsAt}:{},...P.accountId!==void 0?{accountId:P.accountId}:{},...P.autoResume!==void 0?{autoResume:P.autoResume}:{}}));continue}if(P.type==="resumed"){let I=P.hotSwapped&&P.accountId?`\u25B6 Resumed on ${P.accountId}`:"\u25B6 Resumed";c="",d=!1,b.length=0,y.clear(),f=!1,g=void 0,u=!1,h=!1,v=x(),p=!1,await A(),(s??{fn:console.log}).fn(m.success(I));continue}if(P.type==="error"){await S(),gr(fr(P.error)),u=!0;continue}v.process(P),P.type==="done"&&(f=!0,g=P.metadata)}}),await S(),f){Kn(n,l,c,g,b),r.onTurnComplete&&await r.onTurnComplete(l,c).catch(()=>{});let P=O=>{s?s.fn(O):console.log(O)};(d||b.length>0)&&P(`
|
|
2124
2124
|
`);let I=Qw(c);if(I&&(P(Zw(I)),P(""),r.onTerminalState))try{r.onTerminalState(I)}catch{}if(iF(g,n,P),r.onAfterTurn){let O=r.onAfterTurn();O instanceof Promise&&await O.catch(()=>{})}}}catch(R){await S(),u||gr(fr(R))}finally{await S(),s&&(s.fn=R=>console.log(R)),r.setActiveCompositor?.(null),r.setBackgroundHandler?.(null),r.setInFlight(!1),r.rearmStatus?.()}}function iF(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(ie(e.durationMs)),e.totalCostUsd!==void 0&&r.push(Ue(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),s=Number(e.usage?.output_tokens??0);o+s>0&&r.push(Z(o+s)+" tok"),r.length>0&&n(m.dim(" \u25E6 "+r.join(" \xB7 ")));let i=wd(t),a=et(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 ~${Z(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 ${Z(a)}`))}n("")}function nS(e={}){let t=e.load??ra,n=e.onResize??(i=>Ge.subscribe(i)),r="",o,s=n(()=>{r=""});return{renderIfChanged(i){let a=i??"unbound",l=t(a),c=ib(l);return a===o&&c===r?[]:(o=a,r=c,c===""?[]:oa(l))},invalidate(){r=""},dispose(){try{s()}catch{}}}}var Au={done:{glyph:"\u2713",color:m.success,label:"done"},blocked:{glyph:"\u2298",color:m.error,label:"blocked"},asking:{glyph:"?",color:m.warning,label:"asking"},interrupted:{glyph:"\u23F8",color:m.meta,label:"interrupted"}};function rS(e={}){let t=Math.max(2,e.capacity??8),n=[];return{push(r){n.push(r.kind),n.length>t&&(n=n.slice(n.length-t))},reset(){n=[]},entries(){return n},render(){if(n.length===0)return null;let r=m.dim(" ledger "),o=m.dim(" \xB7 "),s=n.map(d=>{let u=Au[d];return u.color(`${u.glyph} ${u.label}`)}),i=m.dim(` (${n.length} turn${n.length===1?"":"s"})`),a=r+s.join(o)+i,l=Math.max(20,ne()-2);if(z(a)<=l)return a;let c=r+n.map(d=>Au[d].color(Au[d].glyph)).join(m.dim(" "))+i;return ce(c,l)}}}var Ru=["\u25D0","\u25D1","\u25D2","\u25D3"],ll=class{stream;manager;registry;throttleMs;started=!1;lastRepaint=0;spinnerIndex=0;spinnerInterval=null;resizeUnsub=null;updateHandler=null;registryStartedHandler=null;registrySettledHandler=null;rowCount=0;onRowCountChange;constructor(t,n,r={}){this.manager=t,this.registry=n,this.stream=r.stream??process.stdout,this.throttleMs=r.throttleMs??200}setRowCountChangeHandler(t){this.onRowCountChange=t}start(){this.started||(this.started=!0,this.updateHandler=()=>this.scheduleRepaint(),this.manager.on("update",this.updateHandler),this.manager.on("complete",this.updateHandler),this.registry&&(this.registryStartedHandler=t=>{this.scheduleRepaint()},this.registrySettledHandler=t=>{this.scheduleRepaint()},this.registry.on("started",this.registryStartedHandler),this.registry.on("settled",this.registrySettledHandler)),this.resizeUnsub=Ge.subscribe(()=>this.repaint()),this.spinnerInterval=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%Ru.length,this.rowCount>0&&this.repaint()},Math.max(this.throttleMs,50)))}stop(){this.started&&(this.started=!1,this.updateHandler&&(this.manager.removeListener("update",this.updateHandler),this.manager.removeListener("complete",this.updateHandler),this.updateHandler=null),this.registry&&(this.registryStartedHandler&&(this.registry.off("started",this.registryStartedHandler),this.registryStartedHandler=null),this.registrySettledHandler&&(this.registry.off("settled",this.registrySettledHandler),this.registrySettledHandler=null)),this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null),this.spinnerInterval&&(clearInterval(this.spinnerInterval),this.spinnerInterval=null),this.rowCount>0&&(this.clearRows(),this.rowCount=0,this.onRowCountChange?.(0)))}scheduleRepaint(){Date.now()-this.lastRepaint<this.throttleMs||this.repaint()}repaint(){if(!this.started||!this.stream.isTTY)return;this.lastRepaint=Date.now();let t=[...this.manager.running().map(s=>({kind:"turn",task:s})),...(this.registry?.list()??[]).filter(s=>s.status==="running").map(s=>({kind:"subagent",job:s}))],n=this.stream.rows??24,r=Math.max(0,Math.min(t.length,n-1));if(r!==this.rowCount&&(this.rowCount>0&&this.clearRows(),this.rowCount=r,this.onRowCountChange?.(r)),r===0)return;let o=Math.max(1,n-r);this.stream.write("\x1B[s");for(let s=0;s<r;s++){let i=t[s],a=o+s;this.stream.write(`\x1B[${a};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatItemLine(i))}this.stream.write("\x1B[u")}clearRows(){if(!this.stream.isTTY)return;let t=this.stream.rows??24,n=Math.min(this.rowCount,t-1),r=Math.max(1,t-n);this.stream.write("\x1B[s");for(let o=0;o<n;o++)this.stream.write(`\x1B[${r+o};1H`),this.stream.write("\x1B[2K");this.stream.write("\x1B[u")}formatItemLine(t){return t.kind==="turn"?this.formatTaskLine(t.task):this.formatJobLine(t.job)}formatTaskLine(t){let n=Math.max(4,(this.stream.columns??80)-2),r=m.brand(Ru[this.spinnerIndex]),o=m.dim(t.id),s=m.bold(t.label),i=[r,o,s];t.progressDescription&&i.push(m.dim(t.progressDescription));let a=[];t.stats.toolUses>0&&a.push(`${t.stats.toolUses} tool${t.stats.toolUses===1?"":"s"}`),t.stats.tokens>0&&a.push(`${Z(t.stats.tokens)} tok`);let l=Date.now()-t.startedAt;return a.push(ie(l)),a.length>0&&i.push(m.dim(a.join(" \xB7 "))),ce(" "+i.join(" "),n)}formatJobLine(t){let n=Math.max(4,(this.stream.columns??80)-2),r=m.brand(Ru[this.spinnerIndex]),o=m.dim(t.jobId),s=m.bold(t.label||t.jobId),i=[r,o,s],a=Date.now()-t.startedAt;return i.push(m.dim(ie(a))),ce(" "+i.join(" "),n)}};function cl(e,t){let n=m.brand("afk")+m.dim(` (${e})`),r=t?m.warning(" \u25CF plan"):"";return n+r+m.dim(" \u203A ")}async function oS(e,t,n,r){let o=null,s=[];e.session.current.waitForInitialization().then(async p=>{ze()&&(o=Zi(p)),await Oa(e.session.current),ze()&&(s=Yk())}).catch(()=>{});let i=await qw(),a=new al({rl:e.rl,history:i,statusLine:e.statusLine}),l,c,d,u;try{await a.armCompositor({promptFn:()=>cl(e.stats.model,e.stats.planMode),onCancel:r,onShiftTab:()=>{let h=e.slashCtx;h.stats.planMode&&h.stats.pendingPlanExit?(h.stats.pendingPlanExit=!1,bt(h,!1,{closureSummarySkipped:!0}).catch(()=>{})):bt(h).catch(()=>{}),e.statusLine.rearm()},scrollRegion:e.statusLine}),e.replRenderer.setCompositor(a.getCompositor()),e.slashCtx.getCompositor=()=>a.getCompositor(),c=nS();let p=rS();e.clearVerdictLedger=()=>p.reset(),d=new sa,yb(d),Tb(d),Ab(d),Eb(e.backgroundRegistry),u=new ll(d,e.backgroundRegistry),u.setRowCountChangeHandler(h=>{e.statusLine.setExtraRows(h)}),u.start();let f=50,g=[];for(d.on("complete",h=>{g.length>=f&&g.shift(),g.push(h)});;){if(o&&(e.replRenderer.writeLine(o),e.replRenderer.writeLine(""),o=null),s.length>0){for(let S of s)e.replRenderer.writeLine(S);e.replRenderer.writeLine(""),s=[]}for(;g.length>0;){let S=g.shift(),A=S.status==="succeeded"?"\u2713":"\u2717",R=[];if(S.resultText){let _=S.resultText.trim().split(`
|
|
2125
2125
|
`)[0]?.slice(0,80)??"";_&&R.push(_)}S.error&&R.push(S.error.message);let D=[S.stats.toolUses>0?`${S.stats.toolUses} tools`:"",S.stats.tokens>0?`${Math.round(S.stats.tokens/1e3)}k tok`:"",S.stats.durationMs>0?`${Math.round(S.stats.durationMs/1e3)}s`:""].filter(Boolean).join(" \xB7 ");D&&R.push(D),e.replRenderer.writeLine(Zt({kind:S.status==="succeeded"?"checkpoint":"diagnosis",title:`${A} ${S.id} ${S.label}`,body:R})),e.replRenderer.writeLine("")}let h=c.renderIfChanged(e.stats.sessionId);if(h.length>0){for(let S of h)e.replRenderer.writeLine(S);e.replRenderer.writeLine("")}let b=p.render();b&&e.replRenderer.writeLine(b);let y,w;if(l!==void 0){let S=l;l=void 0;let A=cl(e.stats.model,e.stats.planMode),R=zn({buffer:S.text,promptText:A,isTTY:!!process.stdout.isTTY,attachmentSummary:Kr([...S.attachments])});e.replRenderer.writeLine(R),y=S.text.trim(),w=S.attachments}else{let S=await a.readLine({promptFn:()=>cl(e.stats.model,e.stats.planMode),onSigint:r,onShiftTab:()=>{let A=e.slashCtx;A.stats.planMode&&A.stats.pendingPlanExit?(A.stats.pendingPlanExit=!1,bt(A,!1,{closureSummarySkipped:!0}).catch(()=>{})):bt(A).catch(()=>{}),e.statusLine.rearm()}});y=S.text.trim(),w=S.attachments}if(!y&&w.length===0)continue;let E=!1;if(y.startsWith("/")){let S=await jy(y,e.slashCtx,w);if(S.handled){if(S.result==="exit"){e.rl.close();return}if((y==="/clear"||y.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(m.dim(` transcript: ${t.path()}`)),p.reset()),S.result!==null&&typeof S.result=="object"&&"kind"in S.result&&S.result.kind==="submit"){l={text:S.result.message,attachments:w??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}E=!0}i.push(y);let x=y;if(E){let S=kd(y);if(S){let A=S.name.replace(/^\//,"").split(":").pop()??"";if(A&&nu(A)){let R={skillName:A,rawArgs:S.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},D=e.session.current.sessionId,_=is(D),P=Date.now();K(`[afk trace] preflight.start commandName=${A}`);let I=!1,O=await ss(R,{cwd:e.stats.cwd??process.cwd(),artifactDir:_},F=>{ze()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${A}) failed: `)+(F instanceof Error?F.message:String(F)))});I=O!==null,K(`[afk trace] preflight.end commandName=${A} durationMs=${Date.now()-P} success=${I}`),x=su(O?.manifestBlock,y)}}}let v;if(e.firstTurnHook&&e.stats.totalTurns===0){let S=e.firstTurnHook;e.firstTurnHook=void 0,v=Promise.resolve().then(()=>S(y)).catch(A=>{e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(A instanceof Error?A.message:String(A)))})}await tS({text:x,attachments:w},e.session.current,e.stats,{setInFlight(S){n.turnInFlight=S},async onTurnComplete(S,A){await t.appendTurn(S,A)},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await Xy(e.slashCtx),e.statusLine.rearm()},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:S=>p.push(S),setActiveCompositor:S=>{n.activeCompositor=S},scrollRegion:e.statusLine,getCompositor:()=>a.getCompositor(),setBackgroundHandler:S=>a.setBackgroundHandler(S)},e.options.thinkingUi,e.completionWriter,d,a.toRunTurnRefs(cl(e.stats.model,e.stats.planMode))),v!==void 0&&await v}}finally{if(d!==void 0)for(let p of d.running())d.cancel(p.id);u?.stop(),c?.dispose(),await a.dispose()}}import{execFile as aF}from"node:child_process";import{dirname as lF,isAbsolute as cF,resolve as dF}from"node:path";import{promisify as uF}from"node:util";var sS=uF(aF),pF=3e3,mF=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function fF(){let t=(await sS("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=cF(t)?t:dF(process.cwd(),t);return lF(n)}async function iS(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await fF()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),pF)});try{let o=Pt({execFile:sS,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=>mF.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}import{promises as gF}from"node:fs";import{dirname as hF,join as yF}from"node:path";import{randomBytes as bF}from"node:crypto";var kF=["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(`
|
|
2126
|
-
`),aS=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Cu=30,wF=1024,SF=8e3,vF="haiku";async function TF(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=RF(n,wF),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??SF),i=t.signal?CF([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await Xa({token:t.token,model:t.model??vF,system:kF,user:r,maxTokens:32,signal:i})}catch(u){let p=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(s)}let l=EF(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=hF(t.worktreePath);return await xF(l,c)}function EF(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(aS.test(t)&&t.length<=Cu)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>Cu)break;o=i}return aS.test(o)?o:null}async function xF(e,t){if(!await AF(yF(t,e)))return e;let n=bF(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Cu-5)}-${n}`}async function AF(e){try{return await gF.access(e),!0}catch{return!1}}function RF(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 CF(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 lS(e){let t,n,r=await TF(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:e.handle.path,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(i,a)=>{t=i,n=a}});if(r===null)return{status:"skipped",reason:t??"unknown",...n!==void 0?{detail:n}:{}};let s=await(e.renameFn??$g)(e.handle,r,e.branchPrefix!==void 0?{branchPrefix:e.branchPrefix}:void 0);return s.ok?(e.session&&e.session.setCwd(s.newPath),{status:"renamed",oldPath:s.oldPath,newPath:s.newPath,oldBranch:s.oldBranch,newBranch:s.newBranch}):(s.partial==="branch"&&e.session&&e.session.setCwd(e.handle.path),{status:"failed",reason:s.reason,...s.partial!==void 0?{partial:s.partial}:{}})}N();import{spawn as cS}from"child_process";import{existsSync as $F,mkdirSync as OF,readFileSync as dS,unlinkSync as DF,writeFileSync as LF}from"fs";import{get as FF}from"https";import{join as uS}from"path";import{readFileSync as _F}from"fs";import{dirname as IF,join as PF}from"path";import{fileURLToPath as MF}from"url";function Gt(){try{return"3.26.
|
|
2126
|
+
`),aS=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Cu=30,wF=1024,SF=8e3,vF="haiku";async function TF(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=RF(n,wF),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??SF),i=t.signal?CF([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await Xa({token:t.token,model:t.model??vF,system:kF,user:r,maxTokens:32,signal:i})}catch(u){let p=u instanceof Error?u.message:String(u);return t.onSkip?.("slug-generator-error",p.slice(0,200)),null}finally{clearTimeout(s)}let l=EF(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=hF(t.worktreePath);return await xF(l,c)}function EF(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(aS.test(t)&&t.length<=Cu)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>Cu)break;o=i}return aS.test(o)?o:null}async function xF(e,t){if(!await AF(yF(t,e)))return e;let n=bF(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Cu-5)}-${n}`}async function AF(e){try{return await gF.access(e),!0}catch{return!1}}function RF(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 CF(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 lS(e){let t,n,r=await TF(e.message,{token:e.token,...e.model!==void 0?{model:e.model}:{},...e.timeoutMs!==void 0?{timeoutMs:e.timeoutMs}:{},worktreePath:e.handle.path,...e.signal!==void 0?{signal:e.signal}:{},...e.slugGenerator!==void 0?{slugGenerator:e.slugGenerator}:{},onSkip:(i,a)=>{t=i,n=a}});if(r===null)return{status:"skipped",reason:t??"unknown",...n!==void 0?{detail:n}:{}};let s=await(e.renameFn??$g)(e.handle,r,e.branchPrefix!==void 0?{branchPrefix:e.branchPrefix}:void 0);return s.ok?(e.session&&e.session.setCwd(s.newPath),{status:"renamed",oldPath:s.oldPath,newPath:s.newPath,oldBranch:s.oldBranch,newBranch:s.newBranch}):(s.partial==="branch"&&e.session&&e.session.setCwd(e.handle.path),{status:"failed",reason:s.reason,...s.partial!==void 0?{partial:s.partial}:{}})}N();import{spawn as cS}from"child_process";import{existsSync as $F,mkdirSync as OF,readFileSync as dS,unlinkSync as DF,writeFileSync as LF}from"fs";import{get as FF}from"https";import{join as uS}from"path";import{readFileSync as _F}from"fs";import{dirname as IF,join as PF}from"path";import{fileURLToPath as MF}from"url";function Gt(){try{return"3.26.1"}catch{}try{let e=IF(MF(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(_F(PF(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}H();var NF=64*1024,jF=1440*60*1e3,UF="update-check.json",BF="pending-update.json";function pS(){return uS(Os(),UF)}function _u(){return uS(Os(),BF)}function mS(){let e=Os();$F(e)||OF(e,{recursive:!0})}function WF(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 HF(){try{let e=dS(pS(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function KF(){try{mS();let e=`
|
|
2127
2127
|
const https = require('https');
|
|
2128
2128
|
const fs = require('fs');
|
|
2129
2129
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|