agent-afk 3.55.0 → 3.55.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 +12 -11
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -2064,18 +2064,19 @@ ${u}`}function rp(e,t){let n=VS[t.status];e.out.line(` ${n} ${m.bold(t.jobId)}
|
|
|
2064
2064
|
end try
|
|
2065
2065
|
return "no"
|
|
2066
2066
|
end try
|
|
2067
|
-
`;return new Promise(r=>{let o=Sk("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 XF(e){return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function ZF(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 yl=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],QF=5e3;function fp(e){let t=Date.now()-e;if(t<QF)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 gp(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 xo=class e{stdout;stdin;onCancel;onSoftStop;softStopped=!1;onBackground;onShiftTab;promptTextFn;history;autocompleteState;formatInputBuffer;scrollRegion;captureMode;anchorRow;declaredAnchorRow;onSubmit;attachments=[];pasting=!1;pasteStartBufferLen=0;clipboardInFlight=!1;clipboardFailureMsg=null;inputMode="streaming";pickerController=null;pickerSavedMode="streaming";armed=!1;suspended=!1;canceled=!1;backgrounded=!1;wasRaw=!1;logUpdate=null;overlay="";input=j.seed("");queued=!1;handleKeypress=null;resizeUnsub=null;resizeImmediateUnsub=null;spinner=null;spinnerInterval=null;committing=!1;debugCompositor=!!v.AFK_DEBUG_COMPOSITOR;debugLog(t,n={}){if(!this.debugCompositor)return;let r=process.hrtime.bigint(),o=Object.entries(n).map(([s,i])=>{let a=typeof i=="string"?JSON.stringify(i.length>60?i.slice(0,57)+"...":i):String(i);return`${s}=${a}`}).join(" ");process.stderr.write(`[compositor] t=${r} ${t}${o?" "+o:""}
|
|
2068
|
-
`)}static MAX_DROPDOWN_ROWS=6;constructor(t){this.stdout=t.stdout,this.stdin=t.stdin,this.onCancel=t.onCancel,this.onSoftStop=t.onSoftStop,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,this.anchorRow=t.anchorRow,this.declaredAnchorRow=t.anchorRow}isArmed(){return this.armed}setAnchorRow(t){this.anchorRow=t,this.declaredAnchorRow=t}suspendInput(){if(!(!this.armed||this.suspended)){if(this.logUpdate)try{this.logUpdate.clear(this.scrollRegion?.getExtraRows()??0),this.logUpdate.done()}catch{}this.handleKeypress&&this.stdin.removeListener("keypress",this.handleKeypress);try{this.stdin.setRawMode(!1)}catch{}this.suspended=!0}}resumeInput(){if(!(!this.armed||!this.suspended)){try{this.stdin.setRawMode(!0)}catch{}this.handleKeypress&&this.stdin.on("keypress",this.handleKeypress),this.suspended=!1,this.repaint()}}setOnSubmit(t){this.onSubmit=t??void 0}setOnCancel(t){this.onCancel=t??void 0}getOnCancel(){return this.onCancel}setOnSoftStop(t){this.onSoftStop=t??void 0}setOnBackground(t){this.onBackground=t??void 0}setOnShiftTab(t){this.onShiftTab=t??void 0}enterPickerMode(t){if(this.pickerController)throw new Error("enterPickerMode: a picker is already active; call exitPickerMode first");this.pickerSavedMode=this.inputMode,this.pickerController=t,this.inputMode="picker",this.autocompleteState?.reset(),this.repaint()}exitPickerMode(){this.pickerController&&(this.pickerController=null,this.inputMode=this.pickerSavedMode,this.repaint())}repaintPicker(){this.pickerController&&this.repaint()}setInputMode(t){let n=this.inputMode;if(this.inputMode=t,n==="idle"&&t==="streaming"){this.canceled=!1,this.backgrounded=!1,this.softStopped=!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=j.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.anchorRow=this.declaredAnchorRow,this.logUpdate||(this.logUpdate=new pl(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(),eN(this.stdin),this.handleKeypress=(t,n)=>this.dispatchKey(t,n),this.stdin.on("keypress",this.handleKeypress),this.armed=!0,this.canceled=!1,this.resizeUnsub=ze.subscribe(()=>{this.armed&&this.repaint()}),this.resizeImmediateUnsub=ze.subscribeImmediate(()=>{this.armed&&this.logUpdate?.resetGeometry?.()}),this.repaint()}}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.resizeImmediateUnsub&&(this.resizeImmediateUnsub(),this.resizeImmediateUnsub=null),this.logUpdate)try{this.logUpdate.clear(this.scrollRegion?.getExtraRows()??0),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.debugLog("setOverlay",{framesLen:t.length,anchorRow:this.anchorRow??null}),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:dp(),nextVerbRotateAt:r+n,startedAt:r,tipPool:mk(),currentTip:null},this.spinnerInterval=setInterval(()=>this.tickSpinner(n),80),this.repaint()}tickSpinner(t){if(!this.spinner)return;this.spinner.frameIndex=(this.spinner.frameIndex+1)%yl.length;let n=Date.now();n>=this.spinner.nextVerbRotateAt&&(this.spinner.verb=dp(),this.spinner.nextVerbRotateAt=n+t),this.spinner.currentTip=fk(this.spinner.tipPool,{startedAt:this.spinner.startedAt,now:n}),this.repaint()}commitAbove(t){this.debugLog("commitAbove:enter",{textLen:t.length,anchorRow:this.anchorRow??null,committing:this.committing,topRow:this.logUpdate?.topRow??null});let n=
|
|
2067
|
+
`;return new Promise(r=>{let o=Sk("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 XF(e){return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}function ZF(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 yl=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],QF=5e3;function fp(e){let t=Date.now()-e;if(t<QF)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 gp(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 xo=class e{stdout;stdin;onCancel;onSoftStop;softStopped=!1;onBackground;onShiftTab;promptTextFn;history;autocompleteState;formatInputBuffer;scrollRegion;captureMode;anchorRow;declaredAnchorRow;onSubmit;attachments=[];pasting=!1;pasteStartBufferLen=0;clipboardInFlight=!1;clipboardFailureMsg=null;inputMode="streaming";pickerController=null;pickerSavedMode="streaming";armed=!1;suspended=!1;canceled=!1;backgrounded=!1;wasRaw=!1;logUpdate=null;overlay="";input=j.seed("");queued=!1;handleKeypress=null;resizeUnsub=null;resizeImmediateUnsub=null;spinner=null;spinnerInterval=null;committing=!1;hasCommitted=!1;debugCompositor=!!v.AFK_DEBUG_COMPOSITOR;debugLog(t,n={}){if(!this.debugCompositor)return;let r=process.hrtime.bigint(),o=Object.entries(n).map(([s,i])=>{let a=typeof i=="string"?JSON.stringify(i.length>60?i.slice(0,57)+"...":i):String(i);return`${s}=${a}`}).join(" ");process.stderr.write(`[compositor] t=${r} ${t}${o?" "+o:""}
|
|
2068
|
+
`)}static MAX_DROPDOWN_ROWS=6;constructor(t){this.stdout=t.stdout,this.stdin=t.stdin,this.onCancel=t.onCancel,this.onSoftStop=t.onSoftStop,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,this.anchorRow=t.anchorRow,this.declaredAnchorRow=t.anchorRow}isArmed(){return this.armed}setAnchorRow(t){this.anchorRow=t,this.declaredAnchorRow=t}suspendInput(){if(!(!this.armed||this.suspended)){if(this.logUpdate)try{this.logUpdate.clear(this.scrollRegion?.getExtraRows()??0),this.logUpdate.done()}catch{}this.handleKeypress&&this.stdin.removeListener("keypress",this.handleKeypress);try{this.stdin.setRawMode(!1)}catch{}this.suspended=!0}}resumeInput(){if(!(!this.armed||!this.suspended)){try{this.stdin.setRawMode(!0)}catch{}this.handleKeypress&&this.stdin.on("keypress",this.handleKeypress),this.suspended=!1,this.repaint()}}setOnSubmit(t){this.onSubmit=t??void 0}setOnCancel(t){this.onCancel=t??void 0}getOnCancel(){return this.onCancel}setOnSoftStop(t){this.onSoftStop=t??void 0}setOnBackground(t){this.onBackground=t??void 0}setOnShiftTab(t){this.onShiftTab=t??void 0}enterPickerMode(t){if(this.pickerController)throw new Error("enterPickerMode: a picker is already active; call exitPickerMode first");this.pickerSavedMode=this.inputMode,this.pickerController=t,this.inputMode="picker",this.autocompleteState?.reset(),this.repaint()}exitPickerMode(){this.pickerController&&(this.pickerController=null,this.inputMode=this.pickerSavedMode,this.repaint())}repaintPicker(){this.pickerController&&this.repaint()}setInputMode(t){let n=this.inputMode;if(this.inputMode=t,n==="idle"&&t==="streaming"){this.canceled=!1,this.backgrounded=!1,this.softStopped=!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=j.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.anchorRow=this.declaredAnchorRow,this.logUpdate||(this.logUpdate=new pl(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(),eN(this.stdin),this.handleKeypress=(t,n)=>this.dispatchKey(t,n),this.stdin.on("keypress",this.handleKeypress),this.armed=!0,this.canceled=!1,this.resizeUnsub=ze.subscribe(()=>{this.armed&&this.repaint()}),this.resizeImmediateUnsub=ze.subscribeImmediate(()=>{this.armed&&this.logUpdate?.resetGeometry?.()}),this.repaint()}}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.resizeImmediateUnsub&&(this.resizeImmediateUnsub(),this.resizeImmediateUnsub=null),this.logUpdate)try{this.logUpdate.clear(this.scrollRegion?.getExtraRows()??0),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.debugLog("setOverlay",{framesLen:t.length,anchorRow:this.anchorRow??null}),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:dp(),nextVerbRotateAt:r+n,startedAt:r,tipPool:mk(),currentTip:null},this.spinnerInterval=setInterval(()=>this.tickSpinner(n),80),this.repaint()}tickSpinner(t){if(!this.spinner)return;this.spinner.frameIndex=(this.spinner.frameIndex+1)%yl.length;let n=Date.now();n>=this.spinner.nextVerbRotateAt&&(this.spinner.verb=dp(),this.spinner.nextVerbRotateAt=n+t),this.spinner.currentTip=fk(this.spinner.tipPool,{startedAt:this.spinner.startedAt,now:n}),this.repaint()}commitAbove(t){this.debugLog("commitAbove:enter",{textLen:t.length,anchorRow:this.anchorRow??null,committing:this.committing,topRow:this.logUpdate?.topRow??null});let n=g=>{this.scrollRegion?this.scrollRegion.withFullScrollRegion(g):g()};if(!this.armed||!this.logUpdate){n(()=>{this.stdout.write(t+`
|
|
2069
2069
|
`)});return}let r=Math.max(1,this.stdout.rows??24),o=t.endsWith(`
|
|
2070
2070
|
`)?t.slice(0,-1):t,s=o.match(/\n/g)?.length??0,i=Math.max(1,s+1),a=o.split(`
|
|
2071
|
-
`)
|
|
2072
|
-
`);
|
|
2073
|
-
|
|
2074
|
-
`):
|
|
2075
|
-
`),
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
`),
|
|
2071
|
+
`),l=this.scrollRegion?.getExtraRows()??0,c=this.logUpdate.topRow??0,u=c>1?c:Math.max(1,r-1-l),d=Math.max(this.anchorRow??1,1),p=c>1&&i<=u-d;this.committing=!0;try{this.logUpdate.clear(l),n(()=>{if(this.debugLog("commitAbove:phase1",{lineCount:i,fitsAboveFrame:p}),p)this.stdout.write(`\x1B[${r};1H${`
|
|
2072
|
+
`.repeat(i)}`);else{let g=a.map(h=>`\x1B[2K${h??""}`).join(`
|
|
2073
|
+
`);this.stdout.write(`\x1B[${d};1H${g}\x1B[${r};1H${`
|
|
2074
|
+
`.repeat(i)}`)}})}finally{this.committing=!1,this.debugLog("commitAbove:finally")}this.hasCommitted=!0,this.debugLog("commitAbove:phase2:repaint"),this.repaint(),this.debugLog("commitAbove:phase2:done",{newTopRow:this.logUpdate.topRow??null});let f=this.logUpdate.topRow??0;if(f>1){let g=Math.max(d,f-i),h="";for(let b=0;b<a.length;b++){let y=g+b;if(y>=f)break;h+=`\x1B[${y};1H\x1B[2K${a[b]??""}`}h.length>0&&n(()=>{this.stdout.write(h)})}this.debugLog("commitAbove:phase3:done")}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=Zo(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=Ls(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=gl(t.trigger.query).slice(0,12):t.trigger.kind==="file"?t.candidates=hl(t.trigger.query).slice(0,12):t.candidates=Fs(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=ml(l,a===t.selectedIndex,r,t.trigger?.kind),u=Ce(c).length,d=Math.max(0,Math.ceil(u/n)-1);s.push(c);for(let p=0;p<d;p++)s.push("")}return s.reverse()}renderHintRow(){let t=this.autocompleteState;if(!t?.dropdownOpen)return null;let n=this.stdout.columns||80;if(n<=40)return null;let r=t.candidates[t.selectedIndex];if(!r)return null;let o=Math.min(n-4,80);return fl(r.hint,o)??""}repaint(){if(!this.armed||!this.logUpdate||this.committing||this.suspended)return;if(this.inputMode==="picker"&&this.pickerController){this.repaintPickerFrame();return}let t=this.renderInputLine(),n=this.overlay?this.overlay.split(`
|
|
2075
|
+
`):[],r=this.spinner?m.meta(`${yl[this.spinner.frameIndex]} ${this.spinner.verb}...`)+fp(this.spinner.startedAt):null,o=this.spinner?.currentTip?gp(this.spinner.currentTip.text,this.stdout.columns??80):null,s=null;this.attachments.length>0?s=Ns(this.attachments):this.clipboardFailureMsg!==null&&(s=m.dim(this.clipboardFailureMsg),this.clipboardFailureMsg=null);let i=this.renderDropdownRows(),a=this.renderHintRow(),l=!!r||!!o||!!s,c=l||n.length>0,u=this.scrollRegion?.getExtraRows()??0,d=Math.max(1,(this.stdout.rows??24)-1-u),p=c?1:0,f=(r?1:0)+(o?1:0)+(s?1:0)+p+i.length+(a!==null?1:0)+1,g=Math.max(0,d-f),h=n.length>g?n.slice(-g):n,b=l||h.length>0,y=[];y.push(...h),r&&y.push(r),o&&y.push(o),s&&y.push(s),b&&y.push(""),y.push(...i),a!==null&&y.push(a),y.push(t);let w=Math.max(1,(this.stdout.rows??24)-1-u),k=y.length,E=Math.max(1,w-k+1);this.preserveRowsBeforeFrameRender(E),this.logUpdate.render(y.join(`
|
|
2076
|
+
`),w)}preserveRowsBeforeFrameRender(t){let n=this.logUpdate?.topRow??0,r=this.hasCommitted&&n>1?Math.max(0,n-t):0,o=this.anchorRow!==void 0&&this.anchorRow>1&&t<this.anchorRow?this.anchorRow-t:0,s=Math.max(r,o);s>0&&(this.evictRowsToScrollback(s),this.anchorRow!==void 0&&this.anchorRow>1&&(this.anchorRow=Math.max(1,this.anchorRow-s)))}evictRowsToScrollback(t){if(t<=0)return;this.debugLog("evict:enter",{rows:t,anchorRow:this.anchorRow??null});let r=`\x1B[${Math.max(1,this.stdout.rows??24)};1H${`
|
|
2077
|
+
`.repeat(t)}`,o=()=>{try{this.stdout.write(r)}catch(s){this.debugLog("evict:error",{msg:s?.message??String(s)})}};this.scrollRegion!==void 0?this.scrollRegion.withFullScrollRegion(o):o()}repaintPickerFrame(){if(!this.logUpdate||!this.pickerController)return;let t=[...this.pickerController.renderRows()],n=this.overlay?this.overlay.split(`
|
|
2078
|
+
`):[],r=this.spinner?m.meta(`${yl[this.spinner.frameIndex]} ${this.spinner.verb}...`)+fp(this.spinner.startedAt):null,o=this.spinner?.currentTip?gp(this.spinner.currentTip.text,this.stdout.columns??80):null,s=null;this.attachments.length>0?s=Ns(this.attachments):this.clipboardFailureMsg!==null&&(s=m.dim(this.clipboardFailureMsg),this.clipboardFailureMsg=null);let i=!!r||!!o||!!s,a=i||n.length>0,l=this.scrollRegion?.getExtraRows()??0,c=Math.max(1,(this.stdout.rows??24)-1-l),u=a?1:0,d=(r?1:0)+(o?1:0)+(s?1:0)+u+t.length,p=Math.max(0,c-d),f=n.length>p?n.slice(-p):n,g=i||f.length>0,h=[];if(h.push(...f),r&&h.push(r),o&&h.push(o),s&&h.push(s),g&&h.push(""),h.push(...t),h.length===0)return;let b=Math.max(1,(this.stdout.rows??24)-1-l),y=h.length,w=Math.max(1,b-y+1);this.preserveRowsBeforeFrameRender(w),this.logUpdate.render(h.join(`
|
|
2079
|
+
`),b)}resetState(){this.overlay="",this.input=j.seed(""),this.queued=!1,this.canceled=!1,this.backgrounded=!1,this.softStopped=!1,this.anchorRow=void 0,this.hasCommitted=!1,this.pickerController=null,this.inputMode="streaming",this.attachments=[],this.pasting=!1,this.pasteStartBufferLen=0,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.updateAutocomplete(),this.pasting||this.repaint(),!0)}applyDropdownSelection(){let t=this.autocompleteState;if(!t?.dropdownOpen||t.candidates.length===0)return!1;let n=t.candidates[t.selectedIndex];if(!n)return!1;let r=this.input.buffer.slice(0,this.input.cursor),o=this.input.buffer.slice(this.input.cursor),s,i;if(t.trigger?.kind==="slash"){let l=/\/[A-Za-z_-]*$/.exec(r);s=l?r.length-l[0].length:this.input.cursor,i=n.value+(o.startsWith(" ")?"":" ")}else if(t.trigger?.kind==="flag"){let l=/--[a-z0-9-]*$/.exec(r);s=l?r.length-l[0].length:this.input.cursor,i=n.value+(o.startsWith(" ")?"":" ")}else{let l=r.search(/[^\s]*$/);s=l>=0?l:this.input.cursor,i=n.value}let a=j.replaceRange(this.input,{start:s,end:this.input.cursor},i);return a===this.input?!1:(this.input=a,t.dropdownOpen=!1,t.candidates=[],t.viewportStart=0,t.selectedIndex=0,this.queued=!1,this.updateAutocomplete(),this.repaint(),!0)}dispatchKey(t,n){if(!this.armed)return;if(this.inputMode==="picker"&&this.pickerController){this.pickerController.onKey(t,n);return}let r=this.autocompleteState,o=n?.sequence??"";if(o==="\x1B[200~"){this.pasting=!0,this.pasteStartBufferLen=this.input.buffer.length;return}if(o==="\x1B[201~"){this.pasting=!1;let a=l=>{this.clipboardInFlight||(this.clipboardInFlight=!0,hr().then(c=>{c?(this.clipboardFailureMsg=null,this.attachments.push(c),this.repaint()):l==="flag-missing"&&(this.clipboardFailureMsg="[clipboard: no image found]",this.repaint())}).catch(()=>{}).finally(()=>{this.clipboardInFlight=!1}))};this.input.buffer.length===this.pasteStartBufferLen?a("flag-missing"):(this.repaint(),a("silent"));return}if(n?.name==="escape"){if(r?.dropdownOpen){r.suppressedSignature=`${this.input.cursor}:${this.input.buffer}`,r.dropdownOpen=!1,r.candidates=[],this.repaint();return}if(this.inputMode==="idle"||this.softStopped)return;this.input.buffer.length>0&&!this.queued&&(this.queued=!0,this.repaint()),this.softStopped=!0,this.onSoftStop&&this.onSoftStop();return}if(n?.ctrl&&n?.name==="c"){if(this.inputMode==="idle"){this.onCancel&&this.onCancel();return}if(this.canceled)return;this.canceled=!0,this.input.buffer.length>0&&!this.queued&&(this.queued=!0,this.repaint()),this.onCancel&&this.onCancel();return}if(n?.ctrl&&n?.name==="v"){this.clipboardInFlight||(this.clipboardInFlight=!0,hr().then(a=>{a?(this.clipboardFailureMsg=null,this.attachments.push(a)):this.clipboardFailureMsg="[clipboard: no image found]",this.repaint()}).catch(()=>{}).finally(()=>{this.clipboardInFlight=!1}));return}if(n?.ctrl&&n?.name==="p"||n?.name==="up"){if(r?.dropdownOpen){r.selectedIndex>0&&(r.selectedIndex--,r.selectedIndex<r.viewportStart&&(r.viewportStart=r.selectedIndex),this.repaint());return}if(this.history){let a=this.history.back(this.input.buffer);a!==null&&this.applyEdit(j.seed(a))}return}if(n?.ctrl&&n?.name==="n"||n?.name==="down"){if(r?.dropdownOpen){r.selectedIndex<r.candidates.length-1&&(r.selectedIndex++,r.selectedIndex>=r.viewportStart+e.MAX_DROPDOWN_ROWS&&(r.viewportStart=r.selectedIndex-e.MAX_DROPDOWN_ROWS+1),this.repaint());return}if(this.history){let a=this.history.forward();a!==null&&this.applyEdit(j.seed(a))}return}if(n?.name==="return"){let a=n?.shift===!0||o==="\x1B[13;2u",l=n?.meta===!0;if(a||l){this.history?.resetRecall(),this.applyEdit(j.insert(this.input,`
|
|
2079
2080
|
`));return}if(this.pasting){this.input=j.insert(this.input,`
|
|
2080
2081
|
`),this.queued=!1;return}let c=this.autocompleteState;if(c?.dropdownOpen){let u=c.trigger?.kind,d=this.applyDropdownSelection();if(u!=="slash"||!d)return}if(this.input.buffer.length===0&&this.attachments.length===0)return;if(this.inputMode==="idle"&&this.onSubmit){let u=this.input.buffer,d=[...this.attachments],p=this.onSubmit;this.queued=!1,this.input=j.seed(""),this.attachments=[],this.autocompleteState?.reset(),this.repaint(),p({text:u,attachments:d});return}this.queued||(this.queued=!0,this.repaint());return}if(n?.name==="backspace"){if(n?.meta){let l=j.deleteWordBackward(this.input);l!==this.input&&(this.history?.resetRecall(),this.applyEdit(l));return}let a=j.backspace(this.input);a!==this.input?(this.history?.resetRecall(),this.applyEdit(a)):this.queued?(this.queued=!1,this.repaint()):this.attachments.length>0&&(this.attachments.pop(),this.repaint());return}if(n?.ctrl&&n?.name==="a"){this.applyEdit(j.moveLineStart(this.input));return}if(n?.ctrl&&n?.name==="e"){this.applyEdit(j.moveLineEnd(this.input));return}if((n?.meta||n?.ctrl)&&n?.name==="left"){this.applyEdit(j.moveWordBackward(this.input));return}if((n?.meta||n?.ctrl)&&n?.name==="right"){this.applyEdit(j.moveWordForward(this.input));return}if(n?.meta&&n?.name==="b"){this.applyEdit(j.moveWordBackward(this.input));return}if(n?.meta&&n?.name==="f"){this.applyEdit(j.moveWordForward(this.input));return}if(n?.ctrl&&n?.name==="w"){let a=j.deleteWordBackward(this.input);a!==this.input&&(this.history?.resetRecall(),this.applyEdit(a));return}if(n?.ctrl&&n?.name==="u"){let a=j.deleteToLineStart(this.input);a!==this.input&&(this.history?.resetRecall(),this.applyEdit(a));return}if(n?.ctrl&&n?.name==="k"){let a=j.deleteToLineEnd(this.input);a!==this.input&&(this.history?.resetRecall(),this.applyEdit(a));return}if(n?.name==="left"){this.applyEdit(j.moveLeft(this.input));return}if(n?.name==="right"){this.applyEdit(j.moveRight(this.input));return}if(n?.name==="home"){this.applyEdit(j.moveHome(this.input));return}if(n?.name==="end"){this.applyEdit(j.moveEnd(this.input));return}if(n?.name==="delete"){if(n?.meta){let a=j.deleteWordForward(this.input);a!==this.input&&(this.history?.resetRecall(),this.applyEdit(a));return}this.history?.resetRecall(),this.applyEdit(j.deleteForward(this.input));return}if(n?.ctrl&&n?.name==="b"){if(this.inputMode==="idle"||this.backgrounded)return;this.backgrounded=!0,this.onBackground&&this.onBackground();return}if(n?.name==="tab"&&n?.shift){this.onShiftTab&&this.onShiftTab();return}if(n?.name==="tab"){this.applyDropdownSelection();return}let s=["tab","pageup","pagedown"];if(n?.name&&s.includes(n.name)||n?.ctrl||n?.meta)return;let i=typeof t=="string"&&t.length===1&&t>=" "?t:typeof n?.sequence=="string"&&n.sequence.length===1&&n.sequence>=" "?n.sequence:null;i!==null&&(this.history?.resetRecall(),this.applyEdit(j.insert(this.input,i)))}};import tN from"chalk";var nN=/(?<=\s|^)(\/[A-Za-z][\w:-]*)(?=\s|$)/g,rN=/(?<=\s|^)(@[\w./-]*)(?=\s|$)/g,Ek={mint:m.mint};function oN(e){let t=Ek[e];if(t)return t;let n=e.lastIndexOf(":");if(n>=0){let r=e.slice(n+1),o=Ek[r];if(o)return o}return null}function Un(e,t){return tN.level===0?e:e.replace(nN,r=>{let o=r.slice(1);return t.has(o)?(oN(o)??m.brand)(r):m.meta(r)}).replace(rN,r=>m.fileRef(r))}K();var xk=/[\x00-\x1F\x7F-\x9F]/g;function We(e){return Ce(e).replace(xk," ").replace(/ {2,}/g," ").trim()}function hp(e){return Ce(e).replace(xk," ")}function Us(e){return e.replace(/\/(?:[^/\s,)]+\/){2,}([^/\s,)]+)/g,"$1")}function sN(e){let t=/^(\s*[("]?\s*)cd\s+\S+\s+&&\s+(?!cd\s)(.+)$/.exec(e);return t?(t[1]??"")+(t[2]??""):e}var Rk=60;function yp(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>Rk?ce(a,Rk,"\u2026"):a})`}}return e}function Ak(e,t){if(e==="bash"||e==="Bash")return sN(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"?yp(t,["id_prefix","prompt"]):e==="Task"?yp(t,["description","prompt"]):e==="skill"||e==="Skill"?yp(t,["name","arguments"]):e==="ask_question"?iN(t):t}function iN(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 aN(e){return e.replace(/[\r\n]+/g," ")}var lN={"(":")","{":"}","[":"]"};function _k(e,t,n="\u2026"){let r=e.charAt(0),o=lN[r];return!(o&&e.endsWith(o)&&e.length>=2)||q(e)<=t?ce(e,t,n):t<3?t>=2?r+o:ce(e,t,n):ce(e,t-1,n)+o}function cn(e,t){let n=/^([A-Za-z_][A-Za-z0-9_]*)(.*)$/s.exec(e);if(n){let r=n[1],o=Us(Ak(r,n[2]??"")),s=_n(r),{color:i,glyph:a}=go(r),l=nd(s),c=l?` [${l}]`:"";if(t!==void 0){let d=(a+" ").length+r.length+c.length,p=Math.max(1,t-d);o=_k(o,p)}o=aN(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)}K();var Ck=8,bl=30;function cN(){let e=v.AFK_DIFF_LINES;if(e===void 0)return bl;let t=e.trim();if(!/^\d+$/.test(t))return bl;let n=Number.parseInt(t,10);return Number.isFinite(n)?n:bl}function uN(){let e=v.AFK_SHOW_DIFFS;if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="0"||t==="false"||t==="no"||t==="off"}function dN(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 pN=/[\x00-\x08\x0B-\x1F\x7F-\x9F]/g;function mN(e){let t=Ce(e.text).replace(pN,"");return e.kind==="+"?m.diffAdd("+ "+t):e.kind==="-"?m.diffRemove("- "+t):m.dim(" "+t)}var wp=new WeakMap;function un(e,t,n){if(uN())return[];if(e.hunks.length===0)return[];let r=t==="overlay"?Ck:cN(),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+dN(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:mN(h)})}if(r===0){for(let f of a)i.push(n+f.text);return bp(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 bp(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}`)),bp(e,o,i),i}function bp(e,t,n){let r=wp.get(e);r===void 0&&(r=new Map,wp.set(e,r)),r.set(t,n)}var fN=m.success("\u2713"),gN=m.error("\u2717");function yr(e){return e?gN:fN}var js=3,Ik=2,Pk=3;function Mk(e){switch(_n(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 hN(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 jn(e,t,n=60,r){let o=e.isError?m.error:m.dim,s=t??v.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} ${hN(r,e.lineCount)}`);let i=e.content.length>n?e.content.slice(0,n-3)+"\u2026":e.content;return o(We(i))}K();function Bs(e,t){if(e.length<=t)return e;let n=e.slice(0,t),r=e.slice(t),o=$k(r);return[...n,{kind:"overflow",count:r.length,text:o}]}function yN(e,t){return t<=1||e.endsWith("s")||/(sh|ch|x|z)$/i.test(e)?e:e+"s"}var bN=5,Ok=60;function $k(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=>Je.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>Ok?d.slice(0,Ok-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,bN),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} ${yN(s,i)}`);return`\u2026 +${n} (${o.join(", ")})`}function wl(e,t=At()){return e.map((n,r)=>({sibling:n,connector:r===e.length-1?t.lastConnector:t.midConnector}))}function Sp(e,t){return t?[...e,{kind:"resultSummary",summary:t}]:e}function kp(e){if(e.length===0)return[];let t=new Map;for(let o of e){let s=Dk(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=Dk(o),i=t.get(s);i.length>=wN(o.toolName)?r.has(s)||(n.push({kind:"group",toolName:o.toolName,label:Je.has(o.toolName)?o.toolInput:"",entries:i}),r.add(s)):n.push(o)}return n}function vp(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 cn(e.toolName+e.label)+m.dim(` \xD7${t} \u2014 ${s}`)}function Dk(e){return Je.has(e.toolName)?e.toolName+"::"+e.toolInput:e.toolName}function wN(e){return Je.has(e)?Ik:Pk}function Lk(e,t,n,r){return e>0||t?Ws([...n,!0],r):Ws(n,r)}function Sl(e,t,n,r=Y(),o=[],s=At()){let i=Ws(o,s),a=kl(i,s),l=e.filter(g=>g.kind==="text"),c=e.filter(g=>g.kind==="tool"),u=kp(c),d=Bs(u,js),p=wl(d,s);for(let{sibling:g,connector:h}of p){let b=m.dim(h),y=h===s.lastConnector;if(g.kind==="overflow")n.push(Pe(a+b+m.dim(g.text),r));else if(g.kind==="group")n.push(Pe(a+b+vp(g),r));else if(g.kind==="resultSummary")n.push(Pe(a+b+m.dim(g.summary),r));else{let w=g,k=t.get(w.toolUseId);if(Je.has(w.toolName)&&k&&k.length>0)w.headerEmitted?n.push(Pe(a+b,r)):n.push(Pe(a+b+w.prefix,r)),Sl(k,t,n,r,[...o,y],s),w.thinkingTail&&n.push(Pe(a+m.thinking("\u2307 "+We(w.thinkingTail)),r));else if(w.result){if(n.push(Pe(a+b+w.prefix+m.dim(" \u2014 ")+yr(w.result.isError)+" "+jn(w.result,void 0,60,w.toolName),r)),w.diff&&!w.result.isError){let E=a+(y?s.spineClosed:m.dim(s.spine))+" ";for(let T of un(w.diff,"overlay",E))n.push(T)}}else{n.push(Pe(a+b+w.prefix,r));let E=a+(y?s.spineClosed:m.dim(s.spine))+" ";w.thinkingTail?n.push(Pe(E+m.thinking("\u2307 "+We(w.thinkingTail)),r)):n.push(Pe(E+m.dim(Mk(w.toolName)),r))}}}let f=Lk(c.length,!1,o,s);for(let g of l)for(let h of Tp(g.text,f,s))n.push(Pe(h,r))}function Hs(e,t,n,r,o=Y(),s=[],i=At()){let a=Ws(s,i),l=kl(a,i),c=[],u=e.filter(y=>y.kind==="text"),d=e.filter(y=>y.kind==="tool"),p=kp(d),f=Bs(p,js),g=Sp(f,r),h=wl(g,i);for(let{sibling:y,connector:w}of h){let k=m.dim(w),E=w===i.lastConnector;if(y.kind==="overflow")c.push(Pe(l+k+m.dim(y.text),o));else if(y.kind==="resultSummary")c.push(Pe(l+k+m.dim(y.summary),o));else if(y.kind==="group")c.push(Pe(l+k+vp(y),o));else{let T=y,I=t.get(T.toolUseId);if(Je.has(T.toolName)&&I&&I.length>0){if(T.headerEmitted){let $=T.toolInput?`${T.toolName} ${We(T.toolInput)}`:T.toolName;c.push(Pe(l+k+m.dim("\u21B3 "+$),o))}else c.push(Pe(l+k+T.prefix,o));c.push(...Hs(I,t,n,void 0,o,[...s,E],i))}else if(T.result){if(c.push(Pe(l+k+T.prefix+m.dim(" \u2014 ")+yr(T.result.isError)+" "+jn(T.result,n,60,T.toolName),o)),T.diff&&!T.result.isError){let $=l+(E?i.spineClosed:m.dim(i.spine))+" ";for(let x of un(T.diff,"flush",$))c.push(x)}}else c.push(Pe(l+k+T.prefix,o))}}let b=Lk(d.length,r!=null,s,i);for(let y of u)for(let w of Tp(y.text,b,i))c.push(Pe(w,o));return c}function Ks(e,t,n,r,o=0){let s=At(),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>js&&(c.push(`${i.length} tools`),l>0&&c.push(`${l} lines`));let u=m.dim(s.spine.repeat(o)),d=Array.from({length:o},()=>!1),p=m.dim(s.turnRoot),f=c.length>0?u+p+e.prefix+m.dim(" \u2014 "+c.join(" \xB7 ")):u+p+e.prefix,g=Hs(t,n,r,e.agentResultSummary,Y(),d,s);return[f,...g].join(`
|
|
2081
2082
|
`)}function Ep(e,t=0){let n=At(),r=m.dim(n.spine.repeat(t)),o=m.dim(n.turnRoot);return r+o+e.prefix}function Gs(e,t,n,r,o=0){let s=At(),i=Array.from({length:o},()=>!1);return Hs(t,n,r,e.agentResultSummary,Y(),i,s)}function Ro(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 ")+yr(i.result.isError)+" "+jn(i.result,n,60,i.toolName)),i.diff&&!i.result.isError)for(let a of un(i.diff,"flush"," "))r.push(a)}else r.push(" "+i.prefix)}else{r.push(Fk(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(Us(l.toolInput).trim()||l.toolInput.trim());r.push(" "+m.dim(`\u2500\u2500 ${c} \u2500\u2500`))}for(let c of un(l.diff,"flush"," "))r.push(c)}}}return r}function Fk(e,t,n){let{color:r,glyph:o}=go(e),s=t.map(u=>We(Us(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=>jn(d.result,n,60,d.toolName));return" "+i+m.dim(" \u2014 ")+u.join(m.dim(", "))}return" "+i}function Pe(e,t){return ce(e,t)}var xp=Object.freeze({spine:"\u2502 ",spineClosed:" ",lead:" ",turnRoot:"\u25C9 ",midConnector:"\u251C\u2500 ",lastConnector:"\u2570\u2500 ",textPrefix:"\u2502 "}),SN=Object.freeze({spine:"| ",spineClosed:" ",lead:" ",turnRoot:"o ",midConnector:"+- ",lastConnector:"\\- ",textPrefix:"| "}),Xoe=xp.midConnector,Zoe=xp.lastConnector;function At(){let e=v.AGENT_AFK_ASCII;return e&&/^(1|true|yes)$/i.test(e)?SN:xp}function Ws(e,t){let n="";for(let r of e)n+=r?t.spineClosed:t.spine;return n+=t.spine,n}function kl(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 Tp(e,t,n){if(!e||!e.trim())return[];let r=m.dim(n.textPrefix),o=Math.max(1,Y()-t.length-2-2),s=kl(t,n),i=[];for(let a of e.split(`
|
|
@@ -2204,7 +2205,7 @@ _ended: ${new Date().toISOString()}_
|
|
|
2204
2205
|
`)}function dB(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 KT(e,t,n){let r=[];return n&&n.trim().length>0&&r.push({type:"text",text:n}),e&&r.push({type:"text",text:e}),Dl(r,t),r}async function GT(e,t,n,r,o="summary",s,i,a){let l=wk(e.text,e.attachments);r.setInFlight(!0);let c="",u=!1,d=!1,p=!1,f=!1,g,h=!1,b=!1,y=0,w=15e3,k=[],E=new Map,T=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,I=r.getCompositor?r.getCompositor():null,$=()=>new Po({out:Mo(s),thinkingMode:o,...T?{activeSkillName:T}:{},onCancel:()=>{t.interrupt().catch(C=>{Ue()&&console.error(" "+m.error("session.interrupt() failed:"),C)})},...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}:{},...I?{compositor:I}:{}}),x=$(),A=async()=>{if(!p){p=!0;try{await x.dispose()}catch{}}},P=async()=>{await x.arm();let C=x.getCompositor();if(s&&C){let R=C;s.fn=M=>R.commitAbove(M)}r.setActiveCompositor?.(C),r.setInterruptNotifier?.(R=>x.setInterrupting(R)),r.rearmStatus?.()};try{I?I.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{b=!0}),await P(),i&&r.setBackgroundHandler&&r.setBackgroundHandler(()=>{h=!0});let C=e.attachments.length===0?e.text:KT(e.text,e.attachments),R=t.sendMessageStream(C);if(await Wr((_,F)=>{x.process(_,F)},async()=>{for await(let _ of R){if(b){t.interrupt().catch(F=>{Ue()&&console.error(" "+m.error("soft-stop session.interrupt() failed:"),F)});break}if(h&&i){let F=T??e.text.slice(0,40),U=i.register(F),G=nl(U,i);rl(R,c,l,U,i,G,n,r.onTurnComplete,t.abortSignal),await A(),(s??{fn:console.log}).fn(m.dim(` \u2192 backgrounded as ${U.id}: ${U.label}`)),r.setInFlight(!1),r.rearmStatus?.();return}if(_.type==="chunk"&&_.chunk.type==="content"?(c+=_.chunk.content,u=!0):_.type==="message"&&!u&&(c=_.message.content),_.type==="chunk"&&_.chunk.type==="tool_use_detail"){let F=_.chunk,U={toolName:F.toolName,toolUseId:F.toolUseId,input:F.toolInput};E.set(F.toolUseId,U),k.push(U)}else if(_.type==="chunk"&&_.chunk.type==="tool_result"){let F=_.chunk,U=E.get(F.toolUseId);if(U&&(U.result=F.content,U.isError=F.isError,E.delete(F.toolUseId)),r.onContextProgress){let G=Date.now();if(G-y>=w){y=G;try{let D=r.onContextProgress();D instanceof Promise&&await D}catch(D){Ue()&&console.error(" "+m.error("onContextProgress (status refresh) failed:"),D)}}}}if(_.type==="paused"){await A(),(s??{fn:console.log}).fn(Jf({reason:_.reason,..._.resetsAt!==void 0?{resetsAt:_.resetsAt}:{},..._.accountId!==void 0?{accountId:_.accountId}:{},..._.autoResume!==void 0?{autoResume:_.autoResume}:{}}));continue}if(_.type==="resumed"){let F=_.hotSwapped&&_.accountId?`\u25B6 Resumed on ${_.accountId}`:"\u25B6 Resumed";c="",u=!1,k.length=0,E.clear(),f=!1,g=void 0,d=!1,h=!1,x=$(),p=!1,await P(),(s??{fn:console.log}).fn(m.success(F));continue}if(_.type==="error"){await A(),Ur(Fr(_.error)),d=!0;continue}x.process(_),_.type==="done"&&(f=!0,g=_.metadata)}}),await A(),b){let _=s?s.fn:console.log;_(m.warning("\u23F8 Stopped \u2014 work so far kept.")+m.dim(" Use /resume or --resume to continue.")),_("")}if(f&&!b){ar(n,l,c,g,k),r.onTurnComplete&&await r.onTurnComplete(l,c).catch(()=>{}),Wa(process.stdout);let _=U=>{s?s.fn(U):console.log(U)},F=WT(c);if(F&&(_(HT(F)),_(""),r.onTerminalState))try{r.onTerminalState(F)}catch{}if(pB(g,n,_),r.onAfterTurn){let U=r.onAfterTurn();U instanceof Promise&&await U.catch(()=>{})}}}catch(C){await A(),d||Ur(Fr(C))}finally{await A(),s&&(s.fn=s.idleFn),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setInFlight(!1),r.rearmStatus?.()}}function pB(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(se(e.durationMs)),e.totalCostUsd!==void 0&&r.push(Fe(e.totalCostUsd));let o=Number(e.usage?.input_tokens??0),s=Number(e.usage?.output_tokens??0);o+s>0&&r.push(te(o+s)+" tok"),r.length>0&&n(m.dim(" \u25E6 "+r.join(" \xB7 ")));let i=qd(t),a=it(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 ~${te(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 ${te(a)}`))}n("")}function zT(e={}){let t=e.load??Qa,n=e.onResize??(i=>ze.subscribe(i)),r="",o,s=n(()=>{r=""});return{renderIfChanged(i){let a=i??"unbound",l=t(a),c=$S(l);return a===o&&c===r?[]:(o=a,r=c,c===""?[]:el(l))},invalidate(){r=""},dispose(){try{s()}catch{}}}}var fm={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 qT(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(u=>{let d=fm[u];return d.color(`${d.glyph} ${d.label}`)}),i=m.dim(` (${n.length} turn${n.length===1?"":"s"})`),a=r+s.join(o)+i,l=Math.max(20,Y()-2);if(q(a)<=l)return a;let c=r+n.map(u=>fm[u].color(fm[u].glyph)).join(m.dim(" "))+i;return ce(c,l)}}}var gm=["\u25D0","\u25D1","\u25D2","\u25D3"],pc=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=ze.subscribe(()=>this.repaint()),this.spinnerInterval=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%gm.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(gm[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(`${te(t.stats.tokens)} tok`);let l=Date.now()-t.startedAt;return a.push(se(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(gm[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(se(a))),ce(" "+i.join(" "),n)}};function mc(e,t){let n=m.brand("afk")+m.dim(` (${e})`),r=t?m.warning(" \u25CF plan"):"";return n+r+m.dim(" \u203A ")}async function JT(e,t,n,r){let o=null,s=[];e.session.current.waitForInitialization().then(async p=>{Ue()&&(o=Va(p)),await jl(e.session.current),Ue()&&(s=zv())}).catch(()=>{});let i=await DT(),a=new dc({rl:e.rl,history:i,statusLine:e.statusLine}),l,c,u,d;try{await a.armCompositor({promptFn:()=>mc(e.stats.model,e.stats.planMode),onCancel:r,onShiftTab:()=>{let y=e.slashCtx;y.stats.planMode&&y.stats.pendingPlanExit?(y.stats.pendingPlanExit=!1,Rt(y,!1,{closureSummarySkipped:!0}).catch(()=>{})):Rt(y).catch(()=>{}),e.statusLine.rearm()},scrollRegion:e.statusLine,...e.preArmAnchorRow!==void 0?{anchorRow:e.preArmAnchorRow}:{}});let p=a.getCompositor();Ft.install(Ka({readLine:y=>a.readLine({promptFn:()=>y}).then(w=>w.text),writer:{line:(y="")=>{let w=a.getCompositor();w?w.commitAbove(y):process.stdout.write(y+`
|
|
2205
2206
|
`)}},pendingCount:()=>Ft.pendingCount(),...p?{pickFromList:y=>jT(p,y),readTextOverlay:y=>BT(p,y)}:{}})),e.replRenderer.setCompositor(a.getCompositor()),e.slashCtx.getCompositor=()=>a.getCompositor();let f=a.getCompositor();if(f){let y=w=>f.commitAbove(w);e.completionWriter.fn=y,e.completionWriter.idleFn=y}e.slashCtx.setSoftStopHandler=y=>a.setSoftStopHandler(y),e.inputSurfaceRef&&(e.inputSurfaceRef.current=a),c=zT();let g=qT();e.clearVerdictLedger=()=>g.reset(),u=new tl,GS(u),XS(u),ek(u),ZS(e.backgroundRegistry),d=new pc(u,e.backgroundRegistry),d.setRowCountChangeHandler(y=>{e.statusLine.setExtraRows(y)}),d.start();let h=50,b=[];for(u.on("complete",y=>{b.length>=h&&b.shift(),b.push(y)});;){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(;b.length>0;){let x=b.shift(),A=x.status==="succeeded"?"\u2713":"\u2717",P=[];if(x.resultText){let R=x.resultText.trim().split(`
|
|
2206
2207
|
`)[0]?.slice(0,80)??"";R&&P.push(R)}x.error&&P.push(x.error.message);let C=[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 ");C&&P.push(C),e.replRenderer.writeLine(kn({kind:x.status==="succeeded"?"checkpoint":"diagnosis",title:`${A} ${x.id} ${x.label}`,body:P})),e.replRenderer.writeLine("")}let y=c.renderIfChanged(e.stats.sessionId);if(y.length>0){for(let x of y)e.replRenderer.writeLine(x);e.replRenderer.writeLine("")}let w=g.render();w&&e.replRenderer.writeLine(w);let k,E;if(l!==void 0){let x=l;l=void 0;let A=mc(e.stats.model,e.stats.planMode),P=pr({buffer:x.text,promptText:A,isTTY:!!process.stdout.isTTY,attachmentSummary:Eo([...x.attachments])});e.replRenderer.writeLine(P),k=x.text.trim(),E=x.attachments}else{let x=await a.readLine({promptFn:()=>mc(e.stats.model,e.stats.planMode),onSigint:r,onShiftTab:()=>{let A=e.slashCtx;A.stats.planMode&&A.stats.pendingPlanExit?(A.stats.pendingPlanExit=!1,Rt(A,!1,{closureSummarySkipped:!0}).catch(()=>{})):Rt(A).catch(()=>{}),e.statusLine.rearm()}});k=x.text.trim(),E=x.attachments}if(!k&&E.length===0)continue;let T=!1;if(k.startsWith("/")){let x=await dS(k,e.slashCtx,E);if(x.handled){if(x.result==="exit"){e.rl.close();return}if((k==="/clear"||k.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:E??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}T=!0}i.push(k);let I=k;if(T){let x=zd(k);if(x){let A=x.name.replace(/^\//,"").split(":").pop()??"";if(A&&Kp(A)){let P={skillName:A,rawArgs:x.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},C=e.session.current.sessionId,R=kr(C),M=Date.now();J(`[afk trace] preflight.start commandName=${A}`);let _=!1,F=await Sr(P,{cwd:e.stats.cwd??process.cwd(),artifactDir:R},U=>{Ue()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${A}) failed: `)+(U instanceof Error?U.message:String(U)))});_=F!==null,J(`[afk trace] preflight.end commandName=${A} durationMs=${Date.now()-M} success=${_}`),I=qp(F?.manifestBlock,k)}}}let $;if(e.firstTurnHook&&e.stats.totalTurns===0){let x=e.firstTurnHook;e.firstTurnHook=void 0,$=Promise.resolve().then(()=>x(k)).catch(A=>{e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(A instanceof Error?A.message:String(A)))})}await GT({text:I,attachments:E},e.session.current,e.stats,{setInFlight(x){n.turnInFlight=x},async onTurnComplete(x,A){await t.appendTurn(x,A)},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await xS(e.slashCtx),e.statusLine.rearm()},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(dr(e.stats,e.contextSampler))}},e.options.thinkingUi,e.completionWriter,u,a.toRunTurnRefs(mc(e.stats.model,e.stats.planMode))),$!==void 0&&await $}}finally{if(u!==void 0)for(let f of u.running())u.cancel(f.id);d?.stop(),c?.dispose();let p=f=>console.log(f);e.completionWriter.fn=p,e.completionWriter.idleFn=p,await a.dispose(),e.inputSurfaceRef&&(e.inputSurfaceRef.current=null)}}import{execFile as mB}from"node:child_process";import{dirname as fB,isAbsolute as gB,resolve as hB}from"node:path";import{promisify as yB}from"node:util";var VT=yB(mB),bB=3e3,wB=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function SB(){let t=(await VT("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=gB(t)?t:hB(process.cwd(),t);return fB(n)}async function YT(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await SB()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),bB)});try{let o=Gt({execFile:VT,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=>wB.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}import{promises as kB}from"node:fs";import{dirname as vB,join as TB}from"node:path";import{randomBytes as EB}from"node:crypto";var xB=["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(`
|
|
2207
|
-
`),XT=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,hm=30,RB=1024,AB=8e3,_B="haiku";async function CB(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=OB(n,RB),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??AB),i=t.signal?$B([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await tc({token:t.token,model:t.model??_B,system:xB,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=IB(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=vB(t.worktreePath);return await PB(l,c)}function IB(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(XT.test(t)&&t.length<=hm)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>hm)break;o=i}return XT.test(o)?o:null}async function PB(e,t){if(!await MB(TB(t,e)))return e;let n=EB(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,hm-5)}-${n}`}async function MB(e){try{return await kB.access(e),!0}catch{return!1}}function OB(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 $B(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 QT(e){let t,n,r=await CB(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??bb)(e.handle,r,e.branchPrefix!==void 0?{branchPrefix:e.branchPrefix}:void 0);return s.ok?(e.session&&e.session.setCwd(s.newPath),ZT(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),ZT(e.handle.path)),{status:"failed",reason:s.reason,...s.partial!==void 0?{partial:s.partial}:{}})}function ZT(e){try{process.chdir(e)}catch{}}B();import{spawn as eE}from"child_process";import{existsSync as UB,mkdirSync as jB,readFileSync as tE,unlinkSync as BB,writeFileSync as WB}from"fs";import{get as HB}from"https";import{join as nE}from"path";import{readFileSync as DB}from"fs";import{dirname as LB,join as FB}from"path";import{fileURLToPath as NB}from"url";function mn(){try{return"3.55.
|
|
2208
|
+
`),XT=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,hm=30,RB=1024,AB=8e3,_B="haiku";async function CB(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=OB(n,RB),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??AB),i=t.signal?$B([t.signal,o.signal]):o.signal,a;try{t.slugGenerator?a=await t.slugGenerator(r,i):a=await tc({token:t.token,model:t.model??_B,system:xB,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=IB(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=vB(t.worktreePath);return await PB(l,c)}function IB(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(XT.test(t)&&t.length<=hm)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>hm)break;o=i}return XT.test(o)?o:null}async function PB(e,t){if(!await MB(TB(t,e)))return e;let n=EB(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,hm-5)}-${n}`}async function MB(e){try{return await kB.access(e),!0}catch{return!1}}function OB(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 $B(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 QT(e){let t,n,r=await CB(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??bb)(e.handle,r,e.branchPrefix!==void 0?{branchPrefix:e.branchPrefix}:void 0);return s.ok?(e.session&&e.session.setCwd(s.newPath),ZT(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),ZT(e.handle.path)),{status:"failed",reason:s.reason,...s.partial!==void 0?{partial:s.partial}:{}})}function ZT(e){try{process.chdir(e)}catch{}}B();import{spawn as eE}from"child_process";import{existsSync as UB,mkdirSync as jB,readFileSync as tE,unlinkSync as BB,writeFileSync as WB}from"fs";import{get as HB}from"https";import{join as nE}from"path";import{readFileSync as DB}from"fs";import{dirname as LB,join as FB}from"path";import{fileURLToPath as NB}from"url";function mn(){try{return"3.55.1"}catch{}try{let e=LB(NB(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(DB(FB(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}K();var KB=64*1024,GB=1440*60*1e3,zB="update-check.json",qB="pending-update.json";function rE(){return nE(vi(),zB)}function ym(){return nE(vi(),qB)}function oE(){let e=vi();UB(e)||jB(e,{recursive:!0})}function JB(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 VB(){try{let e=tE(rE(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function YB(){try{oE();let e=`
|
|
2208
2209
|
const https = require('https');
|
|
2209
2210
|
const fs = require('fs');
|
|
2210
2211
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|