agent-afk 2.22.1 → 2.23.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +2 -2
- package/dist/index.mjs +88 -88
- package/dist/postinstall.mjs +34 -0
- package/dist/telegram.mjs +108 -108
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1702,7 +1702,7 @@ ${JSON.stringify(e.buildResults,null,2)}
|
|
|
1702
1702
|
Verification results:
|
|
1703
1703
|
${JSON.stringify(e.verifyResults,null,2)}
|
|
1704
1704
|
|
|
1705
|
-
Create a ship-ready summary with next steps.`,l=await a.runToResult(i);if(l.status!=="succeeded"||!l.message)throw new Error(`ship phase failed: ${de(l)}`);let c=e.buildResults?.filesChanged.length??0,u=e.healIterations;return _n({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${c}`,`Heal iterations: ${u}`,`Idea: ${e.idea}`]}),l.message.content}import{existsSync as Ud,mkdirSync as $k,readFileSync as Ok,unlinkSync as Dk,writeFileSync as Fk}from"fs";import{dirname as Lk,join as Nk}from"path";function Ri(e){return Nk(kt(),e,"mint-state.json")}function jd(e,t){let n=Ri(e);$k(Lk(n),{recursive:!0}),Fk(n,JSON.stringify(t,null,2),"utf-8")}function Uk(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.currentPhase=="string"&&typeof t.idea=="string"&&typeof t.spec=="string"&&typeof t.healIterations=="number"&&Array.isArray(t.history)}function Bd(e){let t=Ri(e);if(!Ud(t))return null;try{let n=JSON.parse(Ok(t,"utf-8"));return Uk(n)?n:null}catch{return null}}function Ii(e){let t=Ri(e);if(Ud(t))try{Dk(t)}catch{}}var jk=2,Wd=/^\s*(?:--continue(?:\s+(?:approved|yes|y))?|approved?|yes|y|lgtm)\s*$/i,Bk='To approve and run the rest of the pipeline, say "approve", "yes", or "lgtm" \u2014 or invoke /mint --continue approved. The handler will reload the spec state from disk.';function et(e,t,n){e.history.push({phase:t,output:n,timestamp:Date.now()})}function zd(e){if("completed"in e&&"paused"in e)throw new Error("mint: invariant violation \u2014 MintResult carries both completed and paused keys simultaneously")}var Hd=240;function Wk(e){return e.length<=Hd?e:e.slice(0,Hd)+"\u2026"}function qd(e){if(typeof e=="string"){if(Wd.test(e))return{userApproved:!0};if(e.length>1&&e.trimStart().startsWith("{"))try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null)return qd(t)}catch{}return{idea:e}}if(typeof e=="object"&&e!==null){let t=e,n=typeof t.idea=="string"?t.idea:void 0;if(n!==void 0&&Wd.test(n))return{userApproved:!0};if("idea"in t||"resumeFrom"in t||t.userApproved===!0)return t}throw new Error("mint handler requires input.idea (string), input as string, or {userApproved: true} to resume")}async function Kd(e,t){if(!t.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let n=t.sessionId,r=t.cwd;try{e.currentPhase="research",e.research=await $d(e.spec,n,r),et(e,"research",e.research),e.currentPhase="plan",e.plan=await Od(e.spec,e.research,n,r),et(e,"plan",e.plan),e.currentPhase="parallelize";let o=await Dd(e.plan,t);if(o.kind==="plan")e.waveOrchestrationPlan=o.plan,et(e,"parallelize",JSON.stringify(o.plan));else if(o.kind==="skipped")e.waveOrchestrationPlan=void 0,et(e,"parallelize",`skipped: ${o.reason}`);else if(o.kind==="failed"){e.waveOrchestrationPlan=void 0;let i=Wk(o.error);et(e,"parallelize",`failed: ${i}`),Ne({event:"fallback.inline",parent_session_id:n,reason:"parallelize-dispatch-failed",error_message:i}),console.warn(`[mint] parallelize dispatch failed (single-lane fallback): ${i}`)}else{let i=o}e.currentPhase="build",e.buildResults=await Fd(e.plan,e.waveOrchestrationPlan,n,r),et(e,"build",JSON.stringify(e.buildResults)),e.currentPhase="verify",e.verifyResults=await So(e.plan,e.buildResults,n,r),et(e,"verify",JSON.stringify(e.verifyResults)),e.currentPhase="heal";let s=e.verifyResults.testsPassed&&e.verifyResults.lintPassed&&e.verifyResults.designReviewPassed;for(;!s&&e.healIterations<jk;){let i=await Ld(e.plan,e.buildResults,e.verifyResults,e.healIterations,t);e.healIterations=i.newHealIterations,e.verifyResults=i.newVerifyResults,s=i.healed,et(e,"heal",`Iterations: ${e.healIterations}, Success: ${s}`)}if(!s)return{paused:!0,phase:"heal-failed",reason:`Heal capped at ${e.healIterations} iterations; still have failures`,state:e,nextStep:"Heal loop exhausted. Inspect verifyResults, fix manually, then re-invoke /mint with a fresh idea \u2014 resume is not supported from heal-failed."};e.currentPhase="ship";let a=await Nd(e,n,r);return et(e,"ship",a),{completed:!0,artifact:a,state:e}}catch(o){throw new Error(`mint failed at ${e.currentPhase}: ${o}`)}}function Gd(e,t){return zd(t),("completed"in t||t.phase==="heal-failed")&&Ii(e),t}async function Hk(e,t){let n=qd(e);if(!t?.sessionId)throw new Error("mint handler requires a parent session to fork subagents");let r=t.sessionId;if(n.userApproved){let a=n.resumeFrom??Bd(r);if(!a)throw new Error("mint: no paused spec found for this session to continue. Run /mint <idea> first, then /mint --continue approved.");let i=await Kd(a,t);return Gd(r,i)}if(!n.idea)throw new Error("mint: no idea provided. Run /mint <idea> to start, or /mint --continue approved to resume a paused spec.");Ii(r);let o={currentPhase:"spec",idea:n.idea,healIterations:0,history:[]};try{o.spec=await Md(n.idea,r,t.cwd),et(o,"spec",o.spec)}catch(a){throw new Error(`mint failed at spec: ${a}`)}if(!n.autoApprove){jd(r,o);let a={paused:!0,phase:"spec",spec:o.spec,state:o,nextStep:Bk};return zd(a),a}let s=await Kd(o,t);return Gd(r,s)}var Kk={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:Hk,argumentHint:"<idea> | --continue [approved]",whenToUse:'When the user wants a feature or refactor delivered end-to-end (spec \u2192 research \u2192 build \u2192 verify) in one ship-ready pass. After the spec phase pauses for approval, resume by invoking mint again with the literal string `"approved"` (or `"yes"`, `"lgtm"`, `"--continue approved"`) as the arguments. Equivalent JSON forms `{"userApproved": true}` and `{"idea": "approved"}` are also accepted. The handler reloads the spec state from disk and runs phases 2\u20138.',flags:["--continue"]};Le(Kk);async function Gk(){throw new Error("telegram-setup is a fork skill; its handler should never be called directly. Invoke via the `skill` tool or `/telegram-setup` slash command.")}var zk={name:"telegram-setup",description:"Guide the user through first-time Telegram bot onboarding without leaking the bearer token. Walks the user to run `afk telegram setup` in a terminal for token entry, then uses the sanctioned `afk telegram check-token`/`discover-chat`/`set-allowed-chat` subcommands to validate and finish allowlist setup \u2014 the token never enters the model context. Works in REPL or Telegram. Use when the user wants to set up Telegram push notifications for the first time, or to debug a partially-configured install.",handler:Gk,context:"fork",whenToUse:`When the user wants to set up Telegram bot notifications for the first time, or when they say something like "set up telegram", "connect telegram", "enable push", or you detect that TELEGRAM_BOT_TOKEN is unset and they're asking for notifications.`};Le(zk);import{readdirSync as Yk,readFileSync as Vk}from"fs";import{join as Jk}from"path";var qk=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9-]*)(?![a-zA-Z0-9_-])/g;function Yd(e){return e.startsWith("--")?e:`--${e}`}function Mi(e){let t=new Set;for(let n of e.matchAll(qk))n[1]&&t.add(`--${n[1]}`);return Array.from(t).sort()}function dr(e){if(!e.startsWith(`---
|
|
1705
|
+
Create a ship-ready summary with next steps.`,l=await a.runToResult(i);if(l.status!=="succeeded"||!l.message)throw new Error(`ship phase failed: ${de(l)}`);let c=e.buildResults?.filesChanged.length??0,u=e.healIterations;return _n({kind:"checkpoint",title:"ship \u2014 done",body:[`Files changed: ${c}`,`Heal iterations: ${u}`,`Idea: ${e.idea}`]}),l.message.content}import{existsSync as Ud,mkdirSync as $k,readFileSync as Ok,unlinkSync as Dk,writeFileSync as Fk}from"fs";import{dirname as Lk,join as Nk}from"path";function Ri(e){return Nk(kt(),e,"mint-state.json")}function jd(e,t){let n=Ri(e);$k(Lk(n),{recursive:!0}),Fk(n,JSON.stringify(t,null,2),"utf-8")}function Uk(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.currentPhase=="string"&&typeof t.idea=="string"&&typeof t.spec=="string"&&typeof t.healIterations=="number"&&Array.isArray(t.history)}function Bd(e){let t=Ri(e);if(!Ud(t))return null;try{let n=JSON.parse(Ok(t,"utf-8"));return Uk(n)?n:null}catch{return null}}function Ii(e){let t=Ri(e);if(Ud(t))try{Dk(t)}catch{}}var jk=2,Wd=/^\s*(?:--continue(?:\s+(?:approved|yes|y))?|approved?|yes|y|lgtm|sure)\s*$/i,Bk='To approve and run the rest of the pipeline, say "approve", "yes", "sure", or "lgtm" \u2014 or invoke /mint --continue approved. The handler will reload the spec state from disk.';function et(e,t,n){e.history.push({phase:t,output:n,timestamp:Date.now()})}function zd(e){if("completed"in e&&"paused"in e)throw new Error("mint: invariant violation \u2014 MintResult carries both completed and paused keys simultaneously")}var Hd=240;function Wk(e){return e.length<=Hd?e:e.slice(0,Hd)+"\u2026"}function qd(e){if(typeof e=="string"){if(Wd.test(e))return{userApproved:!0};if(e.length>1&&e.trimStart().startsWith("{"))try{let t=JSON.parse(e);if(typeof t=="object"&&t!==null)return qd(t)}catch{}return{idea:e}}if(typeof e=="object"&&e!==null){let t=e,n=typeof t.idea=="string"?t.idea:void 0;if(n!==void 0&&Wd.test(n))return{userApproved:!0};if("idea"in t||"resumeFrom"in t||t.userApproved===!0)return t}throw new Error("mint handler requires input.idea (string), input as string, or {userApproved: true} to resume")}async function Kd(e,t){if(!t.sessionId)throw new Error("runPhasesAfterSpec requires parentSession.sessionId");let n=t.sessionId,r=t.cwd;try{e.currentPhase="research",e.research=await $d(e.spec,n,r),et(e,"research",e.research),e.currentPhase="plan",e.plan=await Od(e.spec,e.research,n,r),et(e,"plan",e.plan),e.currentPhase="parallelize";let o=await Dd(e.plan,t);if(o.kind==="plan")e.waveOrchestrationPlan=o.plan,et(e,"parallelize",JSON.stringify(o.plan));else if(o.kind==="skipped")e.waveOrchestrationPlan=void 0,et(e,"parallelize",`skipped: ${o.reason}`);else if(o.kind==="failed"){e.waveOrchestrationPlan=void 0;let i=Wk(o.error);et(e,"parallelize",`failed: ${i}`),Ne({event:"fallback.inline",parent_session_id:n,reason:"parallelize-dispatch-failed",error_message:i}),console.warn(`[mint] parallelize dispatch failed (single-lane fallback): ${i}`)}else{let i=o}e.currentPhase="build",e.buildResults=await Fd(e.plan,e.waveOrchestrationPlan,n,r),et(e,"build",JSON.stringify(e.buildResults)),e.currentPhase="verify",e.verifyResults=await So(e.plan,e.buildResults,n,r),et(e,"verify",JSON.stringify(e.verifyResults)),e.currentPhase="heal";let s=e.verifyResults.testsPassed&&e.verifyResults.lintPassed&&e.verifyResults.designReviewPassed;for(;!s&&e.healIterations<jk;){let i=await Ld(e.plan,e.buildResults,e.verifyResults,e.healIterations,t);e.healIterations=i.newHealIterations,e.verifyResults=i.newVerifyResults,s=i.healed,et(e,"heal",`Iterations: ${e.healIterations}, Success: ${s}`)}if(!s)return{paused:!0,phase:"heal-failed",reason:`Heal capped at ${e.healIterations} iterations; still have failures`,state:e,nextStep:"Heal loop exhausted. Inspect verifyResults, fix manually, then re-invoke /mint with a fresh idea \u2014 resume is not supported from heal-failed."};e.currentPhase="ship";let a=await Nd(e,n,r);return et(e,"ship",a),{completed:!0,artifact:a,state:e}}catch(o){throw new Error(`mint failed at ${e.currentPhase}: ${o}`)}}function Gd(e,t){return zd(t),("completed"in t||t.phase==="heal-failed")&&Ii(e),t}async function Hk(e,t){let n=qd(e);if(!t?.sessionId)throw new Error("mint handler requires a parent session to fork subagents");let r=t.sessionId;if(n.userApproved){let a=n.resumeFrom??Bd(r);if(!a)throw new Error("mint: no paused spec found for this session to continue. Run /mint <idea> first, then /mint --continue approved.");let i=await Kd(a,t);return Gd(r,i)}if(!n.idea)throw new Error("mint: no idea provided. Run /mint <idea> to start, or /mint --continue approved to resume a paused spec.");Ii(r);let o={currentPhase:"spec",idea:n.idea,healIterations:0,history:[]};try{o.spec=await Md(n.idea,r,t.cwd),et(o,"spec",o.spec)}catch(a){throw new Error(`mint failed at spec: ${a}`)}if(!n.autoApprove){jd(r,o);let a={paused:!0,phase:"spec",spec:o.spec,state:o,nextStep:Bk};return zd(a),a}let s=await Kd(o,t);return Gd(r,s)}var Kk={name:"mint",description:"Takes a feature idea or refactor scope and delivers a ship-ready, verified implementation end-to-end",handler:Hk,argumentHint:"<idea> | --continue [approved]",whenToUse:'When the user wants a feature or refactor delivered end-to-end (spec \u2192 research \u2192 build \u2192 verify) in one ship-ready pass. After the spec phase pauses for approval, resume by invoking mint again with the literal string `"approved"` (or `"yes"`, `"lgtm"`, `"--continue approved"`) as the arguments. Equivalent JSON forms `{"userApproved": true}` and `{"idea": "approved"}` are also accepted. The handler reloads the spec state from disk and runs phases 2\u20138.',flags:["--continue"]};Le(Kk);async function Gk(){throw new Error("telegram-setup is a fork skill; its handler should never be called directly. Invoke via the `skill` tool or `/telegram-setup` slash command.")}var zk={name:"telegram-setup",description:"Guide the user through first-time Telegram bot onboarding without leaking the bearer token. Walks the user to run `afk telegram setup` in a terminal for token entry, then uses the sanctioned `afk telegram check-token`/`discover-chat`/`set-allowed-chat` subcommands to validate and finish allowlist setup \u2014 the token never enters the model context. Works in REPL or Telegram. Use when the user wants to set up Telegram push notifications for the first time, or to debug a partially-configured install.",handler:Gk,context:"fork",whenToUse:`When the user wants to set up Telegram bot notifications for the first time, or when they say something like "set up telegram", "connect telegram", "enable push", or you detect that TELEGRAM_BOT_TOKEN is unset and they're asking for notifications.`};Le(zk);import{readdirSync as Yk,readFileSync as Vk}from"fs";import{join as Jk}from"path";var qk=/(?<![a-zA-Z0-9_/-])--([a-z][a-z0-9-]*)(?![a-zA-Z0-9_-])/g;function Yd(e){return e.startsWith("--")?e:`--${e}`}function Mi(e){let t=new Set;for(let n of e.matchAll(qk))n[1]&&t.add(`--${n[1]}`);return Array.from(t).sort()}function dr(e){if(!e.startsWith(`---
|
|
1706
1706
|
`))return{frontmatter:null,frontmatterFlags:null,body:e};let t=e.indexOf(`
|
|
1707
1707
|
---
|
|
1708
1708
|
`,4);if(t===-1)return{frontmatter:null,frontmatterFlags:null,body:e};let n=e.slice(4,t),r=e.slice(t+5),o={},s=null,a=n.split(`
|
|
@@ -1956,7 +1956,7 @@ _ended: ${new Date().toISOString()}_
|
|
|
1956
1956
|
`)}function wC(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 SC(e,t){let n=[];e&&n.push({type:"text",text:e});for(let r of t)n.push({type:"image",source:{type:"base64",media_type:r.mediaType,data:r.bytes.toString("base64")}});return n}async function Zf(e,t,n,r,o="summary",s,a){let i=Of(e.text,e.attachments);r.setInFlight(!0);let l="",c=!1,u,d=!1,m=!1,f=!1,g,y=!1,S=[],h=new Map,b=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,w=new Bt({out:jn(),thinkingMode:o,...b?{activeSkillName:b}:{},onCancel:()=>{t.interrupt().catch(T=>{Pe()&&console.error(" "+p.error("session.interrupt() failed:"),T)})},...a?{onBackground:()=>{y=!0}}:{}}),C=async()=>{if(!m){m=!0;try{await w.dispose()}catch{}}};try{console.log(),await w.arm();let T=w.getCompositor();if(s&&T){let v=T;s.fn=E=>v.commitAbove(E)}r.setActiveCompositor?.(T),r.rearmStatus?.();let A=e.attachments.length===0?e.text:SC(e.text,e.attachments),x=t.sendMessageStream(A);if(await vn(w.sink,async()=>{for await(let v of x){if(y&&a){let E=b??e.text.slice(0,40),R=a.register(E),I=ss(R,a);is(x,l,i,R,a,I,n,r.onTurnComplete,t.abortSignal),await C(),console.log(p.dim(` \u2192 backgrounded as ${R.id}: ${R.label}`)),r.setInFlight(!1),r.rearmStatus?.();return}if(v.type==="chunk"&&v.chunk.type==="content"?(l+=v.chunk.content,c=!0):v.type==="message"&&!c&&(l=v.message.content),v.type==="chunk"&&v.chunk.type==="tool_use_detail"){let E=v.chunk,R={toolName:E.toolName,toolUseId:E.toolUseId,input:E.toolInput};h.set(E.toolUseId,R),S.push(R)}else if(v.type==="chunk"&&v.chunk.type==="tool_result"){let E=v.chunk,R=h.get(E.toolUseId);R&&(R.result=E.content,R.isError=E.isError,h.delete(E.toolUseId))}if(v.type==="paused"){await C(),console.log(Xl({reason:v.reason,...v.resetsAt!==void 0?{resetsAt:v.resetsAt}:{},...v.accountId!==void 0?{accountId:v.accountId}:{}}));continue}if(v.type==="resumed"){let E=v.hotSwapped&&v.accountId?`\u25B6 Resumed on ${v.accountId}`:"\u25B6 Resumed";console.log(p.success(E));continue}if(v.type==="error"){await C(),wn(kn(v.error)),d=!0;continue}w.process(v),v.type==="done"&&(f=!0,g=v.metadata)}}),!m){let v=w.getCompositor();if(v)try{let{text:E,queued:R}=v.getBuffer();R&&E.length>0&&(u=E)}catch{}}if(await C(),f){Qo(n,i,l,g,S),r.onTurnComplete&&await r.onTurnComplete(i,l).catch(()=>{}),c&&console.log(`
|
|
1957
1957
|
`);let v=Jf(l);if(v&&(console.log(Xf(v)),console.log(),r.onTerminalState))try{r.onTerminalState(v)}catch{}if(vC(g,n),r.onAfterTurn){let E=r.onAfterTurn();E instanceof Promise&&await E.catch(()=>{})}}}catch(T){await C(),d||wn(kn(T))}finally{await C(),s&&(s.fn=T=>console.log(T)),r.setActiveCompositor?.(null),r.setInFlight(!1),r.rearmStatus?.()}return u}function vC(e,t){if(!e)return;let n=[];e.durationMs&&n.push(me(e.durationMs)),e.totalCostUsd!==void 0&&n.push(Ie(e.totalCostUsd));let r=Number(e.usage?.input_tokens??0),o=Number(e.usage?.output_tokens??0);r+o>0&&n.push(H(r+o)+" tok"),n.length>0&&console.log(p.dim(" \u25E6 "+n.join(" \xB7 ")));let s=ca(t);if(s>.5){let a=s>.8?p.error:p.warning;console.log(a(` context ${Math.round(s*100)}% used of ${H(tt(t.model))}`))}console.log()}function Qf(e={}){let t=e.load??ns,n=e.onResize??(a=>xt.subscribe(a)),r="",o,s=n(()=>{r=""});return{renderIfChanged(a){let i=a??"unbound",l=t(i),c=Hp(l);return i===o&&c===r?[]:(o=i,r=c,c===""?[]:rs(l))},invalidate(){r=""},dispose(){try{s()}catch{}}}}var Ha={done:{glyph:"\u2713",color:p.success,label:"done"},blocked:{glyph:"\u2298",color:p.error,label:"blocked"},asking:{glyph:"?",color:p.warning,label:"asking"},interrupted:{glyph:"\u23F8",color:p.info,label:"interrupted"}};function eg(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=p.dim(" ledger "),o=p.dim(" \xB7 "),s=n.map(u=>{let d=Ha[u];return d.color(`${d.glyph} ${d.label}`)}),a=p.dim(` (${n.length} turn${n.length===1?"":"s"})`),i=r+s.join(o)+a,l=Math.max(20,ee()-2);if(j(i)<=l)return i;let c=r+n.map(u=>Ha[u].color(Ha[u].glyph)).join(p.dim(" "))+a;return se(c,l)}}}var tg=["\u25D0","\u25D1","\u25D2","\u25D3"],Ds=class{stream;manager;throttleMs;started=!1;lastRepaint=0;spinnerIndex=0;spinnerInterval=null;resizeUnsub=null;updateHandler=null;rowCount=0;onRowCountChange;constructor(t,n={}){this.manager=t,this.stream=n.stream??process.stdout,this.throttleMs=n.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.resizeUnsub=xt.subscribe(()=>this.repaint()),this.spinnerInterval=setInterval(()=>{this.spinnerIndex=(this.spinnerIndex+1)%tg.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.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(),n=t.length;if(n!==this.rowCount&&(this.rowCount>0&&this.clearRows(),this.rowCount=n,this.onRowCountChange?.(n)),n===0)return;let o=(this.stream.rows??24)-n;this.stream.write("\x1B[s");for(let s=0;s<t.length;s++){let a=t[s],i=o+s;this.stream.write(`\x1B[${i};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatTaskLine(a))}this.stream.write("\x1B[u")}clearRows(){if(!this.stream.isTTY)return;let n=(this.stream.rows??24)-this.rowCount;this.stream.write("\x1B[s");for(let r=0;r<this.rowCount;r++)this.stream.write(`\x1B[${n+r};1H`),this.stream.write("\x1B[2K");this.stream.write("\x1B[u")}formatTaskLine(t){let n=Math.max(4,(this.stream.columns??80)-2),r=p.brand(tg[this.spinnerIndex]),o=p.dim(t.id),s=p.bold(t.label),a=[r,o,s];t.progressDescription&&a.push(p.dim(t.progressDescription));let i=[];t.stats.toolUses>0&&i.push(`${t.stats.toolUses} tool${t.stats.toolUses===1?"":"s"}`),t.stats.tokens>0&&i.push(`${H(t.stats.tokens)} tok`);let l=Date.now()-t.startedAt;return i.push(me(l)),i.length>0&&a.push(p.dim(i.join(" \xB7 "))),se(" "+a.join(" "),n)}};function ng(e,t){let n=p.brand("afk")+p.dim(` (${e})`),r=t?p.warning(" \u25CF plan"):"";return n+r+p.dim(" \u203A ")}async function rg(e,t,n,r){let o=null,s=[];e.session.waitForInitialization().then(async g=>{Pe()&&(o=ts(g)),await Qm(e.session),Pe()&&(s=Zm())}).catch(()=>{});let a=await Vf(),i,l=Qf(),c=eg(),u=new os;em(u),rm(u),sm(u);let d=new Ds(u);d.setRowCountChangeHandler(g=>{e.statusLine.setExtraRows(g)}),d.start();let m=50,f=[];u.on("complete",g=>{f.length>=m&&f.shift(),f.push(g)});try{for(;;){if(o&&(e.replRenderer.writeLine(o),e.replRenderer.writeLine(""),o=null),s.length>0){for(let w of s)e.replRenderer.writeLine(w);e.replRenderer.writeLine(""),s=[]}for(;f.length>0;){let w=f.shift(),C=w.status==="succeeded"?"\u2713":"\u2717",T=[];if(w.resultText){let x=w.resultText.trim().split(`
|
|
1958
1958
|
`)[0]?.slice(0,80)??"";x&&T.push(x)}w.error&&T.push(w.error.message);let A=[w.stats.toolUses>0?`${w.stats.toolUses} tools`:"",w.stats.tokens>0?`${Math.round(w.stats.tokens/1e3)}k tok`:"",w.stats.durationMs>0?`${Math.round(w.stats.durationMs/1e3)}s`:""].filter(Boolean).join(" \xB7 ");A&&T.push(A),e.replRenderer.writeLine(Et({kind:w.status==="succeeded"?"checkpoint":"diagnosis",title:`${C} ${w.id} ${w.label}`,body:T})),e.replRenderer.writeLine("")}let g=l.renderIfChanged(e.stats.sessionId);if(g.length>0){for(let w of g)e.replRenderer.writeLine(w);e.replRenderer.writeLine("")}let y=c.render();y&&e.replRenderer.writeLine(y);let S,h;if(i!==void 0){let w=i;i=void 0;let C=ng(e.stats.model,e.stats.planMode),T=Cr({buffer:w,promptText:C,isTTY:!!process.stdout.isTTY});e.replRenderer.writeLine(T),S=w.trim(),h=[]}else{let w=await Gf({rl:e.rl,promptFn:()=>ng(e.stats.model,e.stats.planMode),onSigint:r,statusLine:e.statusLine,compositor:n.activeCompositor??void 0,history:a,onShiftTab:()=>{let C=e.slashCtx;C.stats.planMode&&C.stats.pendingPlanExit?(C.stats.pendingPlanExit=!1,ht(C,!1,{closureSummarySkipped:!0}).catch(()=>{})):ht(C).catch(()=>{}),e.statusLine.rearm()}});S=w.text.trim(),h=w.attachments}if(!S&&h.length===0)continue;if(S.startsWith("/")){let w=await Ap(S,e.slashCtx);if(w.handled){if(w.result==="exit"){e.rl.close();return}if((S==="/clear"||S.startsWith("/clear "))&&(await t.rotateOnClear(),e.replRenderer.writeLine(p.dim(` transcript: ${t.path()}`)),c.reset()),w.result!==null&&typeof w.result=="object"&&"kind"in w.result&&w.result.kind==="submit"){i=w.result.message,e.statusLine.rearm();continue}e.statusLine.rearm();continue}}a.push(S);let b;if(e.firstTurnHook&&e.stats.totalTurns===0){let w=e.firstTurnHook;e.firstTurnHook=void 0,b=Promise.resolve().then(()=>w(S)).catch(C=>{console.warn(p.warning("\u26A0 ")+"first-turn hook failed: "+(C instanceof Error?C.message:String(C)))})}i=await Zf({text:S,attachments:h},e.session,e.stats,{setInFlight(w){n.turnInFlight=w},async onTurnComplete(w,C){await t.appendTurn(w,C)},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await Op(e.slashCtx),e.statusLine.rearm()},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:w=>c.push(w),setActiveCompositor:w=>{n.activeCompositor=w,e.replRenderer.setCompositor(w)}},e.options.thinkingUi,e.completionWriter,u),b!==void 0&&await b}}finally{d.stop(),l.dispose()}}import{promises as xC}from"node:fs";import{dirname as EC,join as CC}from"node:path";import{randomBytes as PC}from"node:crypto";import TC from"@anthropic-ai/sdk";import{randomUUID as og}from"node:crypto";async function sg(e){let{token:t,model:n,system:r,user:o,maxTokens:s=64,signal:a,clientFactory:i}=e;if(!t)throw new Error("oneShotCompletion: token required");let l=Zr(t),c=Qn(t,l),u=i?i(c):new TC(c),d=og(),m=og(),f=Zt(l,d,m),g={};Object.keys(f).length>0&&(g.headers=f),a&&(g.signal=a);let y=await u.messages.create({model:n,max_tokens:s,system:r,messages:[{role:"user",content:o}]},Object.keys(g).length>0?g:void 0),S=[];for(let b of y.content)b.type==="text"&&S.push(b.text);let h=S.join("").trim();return h.length===0&&console.warn("oneShotCompletion: response contained no text blocks \u2014 returning empty string"),h}var AC=["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(`
|
|
1959
|
-
`),ig=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Ka=30,_C=1024,RC=8e3,IC="haiku";async function MC(e,t){let n=e.trim();if(n.length===0||n.startsWith("/"))return null;let r=FC(n,_C),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??RC),a=t.signal?LC([t.signal,o.signal]):o.signal,i;try{t.slugGenerator?i=await t.slugGenerator(r,a):i=await sg({token:t.token,model:t.model??IC,system:AC,user:r,maxTokens:32,signal:a})}catch{return null}finally{clearTimeout(s)}let l=$C(i);if(l===null)return null;let c=EC(t.worktreePath);return await OC(l,c)}function $C(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(ig.test(t)&&t.length<=Ka)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 a=`${o}-${r[s]}`;if(a.length>Ka)break;o=a}return ig.test(o)?o:null}async function OC(e,t){if(!await DC(CC(t,e)))return e;let n=PC(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Ka-5)}-${n}`}async function DC(e){try{return await xC.access(e),!0}catch{return!1}}function FC(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 LC(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 ag(e){let t=await MC(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}:{}});if(t===null)return{status:"skipped",reason:"slug generation returned null"};let r=await(e.renameFn??pp)(e.handle,t,e.branchPrefix!==void 0?{branchPrefix:e.branchPrefix}:void 0);return r.ok?(e.session&&e.session.setCwd(r.newPath),{status:"renamed",oldPath:r.oldPath,newPath:r.newPath,oldBranch:r.oldBranch,newBranch:r.newBranch}):(r.partial==="branch"&&e.session&&e.session.setCwd(e.handle.path),{status:"failed",reason:r.reason,...r.partial!==void 0?{partial:r.partial}:{}})}import{spawn as lg}from"child_process";import{existsSync as WC,mkdirSync as HC,readFileSync as cg,unlinkSync as KC,writeFileSync as GC}from"fs";import{get as zC}from"https";import{join as dg}from"path";import{readFileSync as NC}from"fs";import{dirname as UC,join as jC}from"path";import{fileURLToPath as BC}from"url";function fn(){try{return"2.
|
|
1959
|
+
`),ig=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,Ka=30,_C=1024,RC=8e3,IC="haiku";async function MC(e,t){let n=e.trim();if(n.length===0||n.startsWith("/"))return null;let r=FC(n,_C),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??RC),a=t.signal?LC([t.signal,o.signal]):o.signal,i;try{t.slugGenerator?i=await t.slugGenerator(r,a):i=await sg({token:t.token,model:t.model??IC,system:AC,user:r,maxTokens:32,signal:a})}catch{return null}finally{clearTimeout(s)}let l=$C(i);if(l===null)return null;let c=EC(t.worktreePath);return await OC(l,c)}function $C(e){let t=e.trim().toLowerCase();if(t.length===0)return null;if(ig.test(t)&&t.length<=Ka)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 a=`${o}-${r[s]}`;if(a.length>Ka)break;o=a}return ig.test(o)?o:null}async function OC(e,t){if(!await DC(CC(t,e)))return e;let n=PC(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,Ka-5)}-${n}`}async function DC(e){try{return await xC.access(e),!0}catch{return!1}}function FC(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 LC(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 ag(e){let t=await MC(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}:{}});if(t===null)return{status:"skipped",reason:"slug generation returned null"};let r=await(e.renameFn??pp)(e.handle,t,e.branchPrefix!==void 0?{branchPrefix:e.branchPrefix}:void 0);return r.ok?(e.session&&e.session.setCwd(r.newPath),{status:"renamed",oldPath:r.oldPath,newPath:r.newPath,oldBranch:r.oldBranch,newBranch:r.newBranch}):(r.partial==="branch"&&e.session&&e.session.setCwd(e.handle.path),{status:"failed",reason:r.reason,...r.partial!==void 0?{partial:r.partial}:{}})}import{spawn as lg}from"child_process";import{existsSync as WC,mkdirSync as HC,readFileSync as cg,unlinkSync as KC,writeFileSync as GC}from"fs";import{get as zC}from"https";import{join as dg}from"path";import{readFileSync as NC}from"fs";import{dirname as UC,join as jC}from"path";import{fileURLToPath as BC}from"url";function fn(){try{return"2.23.0"}catch{}try{let e=UC(BC(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(NC(jC(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}var qC=64*1024,YC=1440*60*1e3,VC="update-check.json",JC="pending-update.json";function ug(){return dg(Wr(),VC)}function Ga(){return dg(Wr(),JC)}function pg(){let e=Wr();WC(e)||HC(e,{recursive:!0})}function XC(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 a=n[s]??0,i=r[s]??0;if(i>a)return!0;if(i<a)return!1}return!1}function ZC(){try{let e=cg(ug(),"utf-8"),t=JSON.parse(e);if(typeof t.latestVersion=="string"&&typeof t.checkedAt=="number")return t}catch{}return null}function QC(){try{pg();let e=`
|
|
1960
1960
|
const https = require('https');
|
|
1961
1961
|
const fs = require('fs');
|
|
1962
1962
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|