agent-afk 3.53.2 → 3.53.3
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 +3 -3
- package/dist/telegram.mjs +68 -68
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1725,7 +1725,7 @@ When diagnosing and fixing code:
|
|
|
1725
1725
|
These skills fire automatically at specific points in the task lifecycle. Check each condition before the relevant phase begins.
|
|
1726
1726
|
|
|
1727
1727
|
- **intent-lock** \u2014 before any multi-step work, scan the request for: ambiguous referents ("the text", "her Y"), unverified characterizations ("the meeting is substantive"), or identity assumptions (which contact = the user). Emit a one-sentence interpretation lock per finding and proceed; escalate to Asking only when interpretation gates an irreversible action AND multiple plausible reads exist.
|
|
1728
|
-
- **ground-state** \u2014 before any non-trivial implementation (multi-file edits, new features, config changes, anything that writes), run a parallel reconnaissance wave
|
|
1728
|
+
- **ground-state** \u2014 before any non-trivial implementation (multi-file edits, new features, config changes, anything that writes), invoke the \`/ground-state\` skill to run a parallel reconnaissance wave for git state, infrastructure, and memory context. Do not settle for inline \`git status\` / \`get_runtime_state\` \u2014 those are serial and miss the memory/infra dimensions the skill triangulates.
|
|
1729
1729
|
- **thesis-lock** \u2014 before drafting first-person analysis or recommendations, lock the thesis to a single sentence for async correction before building on it.
|
|
1730
1730
|
- **premise-gate** \u2014 during research and analysis, check named-entity and status-claim pairs before acting on them.
|
|
1731
1731
|
|
|
@@ -1958,7 +1958,7 @@ ${M}`:I.prompt},model:I.model??this.ctx.defaultSubagentModel??this.ctx.defaultMo
|
|
|
1958
1958
|
${k.map(I=>`> - ${I}`).join(`
|
|
1959
1959
|
`)}
|
|
1960
1960
|
|
|
1961
|
-
`:"")+b,_=g.failed.length>0;return{content:v,isError:_}}catch(d){let p=d instanceof Error?d.message:String(d);return Ie({event:"compose.failed",parent_session_id:this.ctx.parentSession.sessionId,error_message:p.slice(0,240),duration_ms:Date.now()-u}).catch(()=>{}),{content:`Compose execution error: ${p}`,isError:!0}}finally{await l.teardownAll()}}};function lo(e,t,n,r){let o=vw();o.register("SubagentStop",Tw);let s=n??new qe;return r!==void 0&&o.register("PreToolUse",Ew(r)),o.register("SessionEnd",qu(s,t)),o.register("SessionEnd",i=>i.event!=="SessionEnd"?{}:(i.sessionId&&Mw(i.sessionId),{})),e&&o.register("SubagentStop",i=>i.event!=="SubagentStop"?{}:i.status==="idle"||i.status==="running"?{}:(e({subagentId:i.subagentId,status:i.status,durationMs:i.durationMs,agentType:i.agentType}),{})),{registry:o,memoryStore:s}}function se(e){let t=Math.round(e/1e3);if(t<=0)return"0s";let n=Math.floor(t/86400),r=Math.floor(t%86400/3600),o=Math.floor(t%3600/60),s=t%60;return n>0?`${n}d ${r}h`:r>0?`${r}h ${o}m`:o>0?`${o}m ${s}s`:`${s}s`}function Le(e){return e===0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function te(e){if(e<1e3)return String(e);if(e<1e6){let n=e/1e3;return n%1===0?`${n}k`:`${n.toFixed(1).replace(/\.0$/,"")}k`}let t=e/1e6;return t%1===0?`${t}m`:`${t.toFixed(1).replace(/\.0$/,"")}m`}var ID="[skill-routing: active]\n\nRoute recurring work through registered skills instead of rolling ad-hoc solutions:\n\n- Bugs, failing tests, or regressions \u2192 `/diagnose`\n- High-stakes sub-agent output that will drive edits or commits \u2192 `/shadow-verify` before acting\n- Refactor needing parallel waves \u2192 `/parallelize`\n- Parallel or dependent multi-task work \u2192 `compose` tool (DAG of subagent nodes)\n- Greenfield feature where a written spec would genuinely help (novel scope, multi-day work, or external stakeholders involved) \u2192 `/mint`\n\nDo NOT reach for `/mint` for: bug fixes (use `/diagnose`), refactors with known shape, single-feature edits, work already spec'd in chat, or anything where the spec/approve pause would feel like ceremony. Implement directly in those cases.\n\nCommon composed sequences \u2014 reach for these when the task shape matches:\n\n- Bug with failing test and non-trivial fix \u2192 `/diagnose` \u2192 `/shadow-verify` on the proposed fix\n- Refactor needing parallel waves \u2192 plan \u2192 `/parallelize` \u2192 build waves\n- Diagnose + fix in parallel \u2192 `compose` with two independent nodes\n- Research \u2192 implement \u2192 verify pipeline \u2192 `compose` with edges: research\u2192implement\u2192verify\n- Multiple independent investigations \u2192 `compose` with N nodes, no edges\n\nReach for context-isolated investigators when the task is exploratory:\n\n- Map an unfamiliar module before editing \u2192 `/gather` or `/research`\n- Re-derive a load-bearing claim independently \u2192 `/shadow-verify`\n- Audit a diff before merge \u2192 `/review`\n-
|
|
1961
|
+
`:"")+b,_=g.failed.length>0;return{content:v,isError:_}}catch(d){let p=d instanceof Error?d.message:String(d);return Ie({event:"compose.failed",parent_session_id:this.ctx.parentSession.sessionId,error_message:p.slice(0,240),duration_ms:Date.now()-u}).catch(()=>{}),{content:`Compose execution error: ${p}`,isError:!0}}finally{await l.teardownAll()}}};function lo(e,t,n,r){let o=vw();o.register("SubagentStop",Tw);let s=n??new qe;return r!==void 0&&o.register("PreToolUse",Ew(r)),o.register("SessionEnd",qu(s,t)),o.register("SessionEnd",i=>i.event!=="SessionEnd"?{}:(i.sessionId&&Mw(i.sessionId),{})),e&&o.register("SubagentStop",i=>i.event!=="SubagentStop"?{}:i.status==="idle"||i.status==="running"?{}:(e({subagentId:i.subagentId,status:i.status,durationMs:i.durationMs,agentType:i.agentType}),{})),{registry:o,memoryStore:s}}function se(e){let t=Math.round(e/1e3);if(t<=0)return"0s";let n=Math.floor(t/86400),r=Math.floor(t%86400/3600),o=Math.floor(t%3600/60),s=t%60;return n>0?`${n}d ${r}h`:r>0?`${r}h ${o}m`:o>0?`${o}m ${s}s`:`${s}s`}function Le(e){return e===0?"$0.00":e<.01?`$${e.toFixed(4)}`:`$${e.toFixed(2)}`}function te(e){if(e<1e3)return String(e);if(e<1e6){let n=e/1e3;return n%1===0?`${n}k`:`${n.toFixed(1).replace(/\.0$/,"")}k`}let t=e/1e6;return t%1===0?`${t}m`:`${t.toFixed(1).replace(/\.0$/,"")}m`}var ID="[skill-routing: active]\n\nRoute recurring work through registered skills instead of rolling ad-hoc solutions:\n\n- Before non-trivial implementation (multi-file edits, new features, config/build changes \u2014 anything that writes) \u2192 `/ground-state` first. Do NOT substitute inline `git status`/`get_runtime_state` \u2014 the skill triangulates git + infra + prior-session memory in parallel, which the inline checks miss. If `/ground-state` dispatch fails (depth limit, unavailable), fall back to inline checks AND note the coverage gap.\n- Bugs, failing tests, or regressions \u2192 `/diagnose`\n- High-stakes sub-agent output that will drive edits or commits \u2192 `/shadow-verify` before acting\n- Refactor needing parallel waves \u2192 `/parallelize`\n- Parallel or dependent multi-task work \u2192 `compose` tool (DAG of subagent nodes)\n- Greenfield feature where a written spec would genuinely help (novel scope, multi-day work, or external stakeholders involved) \u2192 `/mint`\n\nDo NOT reach for `/mint` for: bug fixes (use `/diagnose`), refactors with known shape, single-feature edits, work already spec'd in chat, or anything where the spec/approve pause would feel like ceremony. Implement directly in those cases.\n\nCommon composed sequences \u2014 reach for these when the task shape matches:\n\n- Bug with failing test and non-trivial fix \u2192 `/diagnose` \u2192 `/shadow-verify` on the proposed fix\n- Refactor needing parallel waves \u2192 plan \u2192 `/parallelize` \u2192 build waves\n- Diagnose + fix in parallel \u2192 `compose` with two independent nodes\n- Research \u2192 implement \u2192 verify pipeline \u2192 `compose` with edges: research\u2192implement\u2192verify\n- Multiple independent investigations \u2192 `compose` with N nodes, no edges\n\nReach for context-isolated investigators when the task is exploratory:\n\n- Map an unfamiliar module before editing \u2192 `/gather` or `/research`\n- Re-derive a load-bearing claim independently \u2192 `/shadow-verify`\n- Audit a diff before merge \u2192 `/review`\n- Generate alternatives before committing to a plan \u2192 `/devils-advocate`\n\nOr dispatch a raw `agent` call when no skill matches but the work is parallelizable, verification-heavy, or would otherwise consume substantial inline context.\n\nSkip orchestration for: single-line edits, trivial Q&A, and direct tool calls the user explicitly requested. The goal is leverage, not ceremony. If a skill would add overhead without adding value, don't invoke it.\n\nWhen you need information only the operator can provide, use `ask_question` to request it directly:\n\n- Question types: `text` (open-ended), `confirm` (yes/no), `choice` (single pick from list), `multi_choice` (multi-pick), `number` (numeric with optional bounds).\n- Ask one focused question at a time. Do NOT ask multiple questions in a single call.\n- Do NOT use for questions you can answer yourself via tools (read files, check git, search docs, etc.).\n- Do NOT use when the user has already provided sufficient context \u2014 infer and proceed instead.\n- The result `action` will be `accept` (answered), `cancel` (user interrupted), `decline` (no handler), or `skip` (optional question skipped).\n- After a `cancel` or `decline`, stop and tell the user what information you need \u2014 do not loop and re-ask.",PD=`[end-of-turn protocol]
|
|
1962
1962
|
|
|
1963
1963
|
Every turn must end in one externally identifiable terminal state. AFK users need inspectable artifacts, not ceremony.
|
|
1964
1964
|
|
|
@@ -2201,7 +2201,7 @@ _ended: ${new Date().toISOString()}_
|
|
|
2201
2201
|
`)}function aB(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=[],w=new Map,k=e.text.startsWith("/")?e.text.split(/[\s:]/)[0]?.slice(1):void 0,E=r.getCompositor?r.getCompositor():null,v=()=>new xo({out:Ro(s),thinkingMode:o,...k?{activeSkillName:k}:{},onCancel:()=>{t.interrupt().catch(C=>{je()&&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}:{},...E?{compositor:E}:{}}),_=v(),I=async()=>{if(!p){p=!0;try{await _.dispose()}catch{}}},R=async()=>{await _.arm();let C=_.getCompositor();if(s&&C){let M=C;s.fn=$=>M.commitAbove($)}r.setActiveCompositor?.(C),r.setInterruptNotifier?.(M=>_.setInterrupting(M)),r.rearmStatus?.()};try{E?E.commitAbove(""):console.log(),r.setSoftStopHandler&&r.setSoftStopHandler(()=>{b=!0}),await R(),i&&r.setBackgroundHandler&&r.setBackgroundHandler(()=>{h=!0});let C=e.attachments.length===0?e.text:KT(e.text,e.attachments),M=t.sendMessageStream(C);if(await jr((x,A)=>{_.process(x,A)},async()=>{for await(let x of M){if(b){t.interrupt().catch(A=>{je()&&console.error(" "+m.error("soft-stop session.interrupt() failed:"),A)});break}if(h&&i){let A=k??e.text.slice(0,40),P=i.register(A),N=nl(P,i);rl(M,c,l,P,i,N,n,r.onTurnComplete,t.abortSignal),await I(),(s??{fn:console.log}).fn(m.dim(` \u2192 backgrounded as ${P.id}: ${P.label}`)),r.setInFlight(!1),r.rearmStatus?.();return}if(x.type==="chunk"&&x.chunk.type==="content"?(c+=x.chunk.content,u=!0):x.type==="message"&&!u&&(c=x.message.content),x.type==="chunk"&&x.chunk.type==="tool_use_detail"){let A=x.chunk,P={toolName:A.toolName,toolUseId:A.toolUseId,input:A.toolInput};w.set(A.toolUseId,P),y.push(P)}else if(x.type==="chunk"&&x.chunk.type==="tool_result"){let A=x.chunk,P=w.get(A.toolUseId);P&&(P.result=A.content,P.isError=A.isError,w.delete(A.toolUseId))}if(x.type==="paused"){await I(),(s??{fn:console.log}).fn(Jf({reason:x.reason,...x.resetsAt!==void 0?{resetsAt:x.resetsAt}:{},...x.accountId!==void 0?{accountId:x.accountId}:{},...x.autoResume!==void 0?{autoResume:x.autoResume}:{}}));continue}if(x.type==="resumed"){let A=x.hotSwapped&&x.accountId?`\u25B6 Resumed on ${x.accountId}`:"\u25B6 Resumed";c="",u=!1,y.length=0,w.clear(),f=!1,g=void 0,d=!1,h=!1,_=v(),p=!1,await R(),(s??{fn:console.log}).fn(m.success(A));continue}if(x.type==="error"){await I(),Lr($r(x.error)),d=!0;continue}_.process(x),x.type==="done"&&(f=!0,g=x.metadata)}}),await I(),b){let x=s?s.fn:console.log;x(m.warning("\u23F8 Stopped \u2014 work so far kept.")+m.dim(" Use /resume or --resume to continue.")),x("")}if(f&&!b){sr(n,l,c,g,y),r.onTurnComplete&&await r.onTurnComplete(l,c).catch(()=>{}),Wa(process.stdout);let x=P=>{s?s.fn(P):console.log(P)},A=WT(c);if(A&&(x(HT(A)),x(""),r.onTerminalState))try{r.onTerminalState(A)}catch{}if(lB(g,n,x),r.onAfterTurn){let P=r.onAfterTurn();P instanceof Promise&&await P.catch(()=>{})}}}catch(C){await I(),d||Lr($r(C))}finally{await I(),s&&(s.fn=s.idleFn),r.setActiveCompositor?.(null),r.setInterruptNotifier?.(null),r.setBackgroundHandler?.(null),r.setSoftStopHandler?.(null),r.setInFlight(!1),r.rearmStatus?.()}}function lB(e,t,n=console.log){if(!e)return;let r=[];e.durationMs&&r.push(se(e.durationMs)),e.totalCostUsd!==void 0&&r.push(Le(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=ot(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=>Ge.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,V()-2);if(z(a)<=l)return a;let c=r+n.map(u=>fm[u].color(fm[u].glyph)).join(m.dim(" "))+i;return ue(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=Ge.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 "))),ue(" "+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))),ue(" "+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=>{je()&&(o=Va(p)),await Ul(e.session.current),je()&&(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,xt(y,!1,{closureSummarySkipped:!0}).catch(()=>{})):xt(y).catch(()=>{}),e.statusLine.rearm()},scrollRegion:e.statusLine,...e.preArmAnchorRow!==void 0?{anchorRow:e.preArmAnchorRow}:{}});let p=a.getCompositor();Dt.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+`
|
|
2202
2202
|
`)}},pendingCount:()=>Dt.pendingCount(),...p?{pickFromList:y=>UT(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 R of s)e.replRenderer.writeLine(R);e.replRenderer.writeLine(""),s=[]}for(;b.length>0;){let R=b.shift(),C=R.status==="succeeded"?"\u2713":"\u2717",M=[];if(R.resultText){let x=R.resultText.trim().split(`
|
|
2203
2203
|
`)[0]?.slice(0,80)??"";x&&M.push(x)}R.error&&M.push(R.error.message);let $=[R.stats.toolUses>0?`${R.stats.toolUses} tools`:"",R.stats.tokens>0?`${Math.round(R.stats.tokens/1e3)}k tok`:"",R.stats.durationMs>0?`${Math.round(R.stats.durationMs/1e3)}s`:""].filter(Boolean).join(" \xB7 ");$&&M.push($),e.replRenderer.writeLine(gn({kind:R.status==="succeeded"?"checkpoint":"diagnosis",title:`${C} ${R.id} ${R.label}`,body:M})),e.replRenderer.writeLine("")}let y=c.renderIfChanged(e.stats.sessionId);if(y.length>0){for(let R of y)e.replRenderer.writeLine(R);e.replRenderer.writeLine("")}let w=g.render();w&&e.replRenderer.writeLine(w);let k,E;if(l!==void 0){let R=l;l=void 0;let C=mc(e.stats.model,e.stats.planMode),M=cr({buffer:R.text,promptText:C,isTTY:!!process.stdout.isTTY,attachmentSummary:bo([...R.attachments])});e.replRenderer.writeLine(M),k=R.text.trim(),E=R.attachments}else{let R=await a.readLine({promptFn:()=>mc(e.stats.model,e.stats.planMode),onSigint:r,onShiftTab:()=>{let C=e.slashCtx;C.stats.planMode&&C.stats.pendingPlanExit?(C.stats.pendingPlanExit=!1,xt(C,!1,{closureSummarySkipped:!0}).catch(()=>{})):xt(C).catch(()=>{}),e.statusLine.rearm()}});k=R.text.trim(),E=R.attachments}if(!k&&E.length===0)continue;let v=!1;if(k.startsWith("/")){let R=await dS(k,e.slashCtx,E);if(R.handled){if(R.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()),R.result!==null&&typeof R.result=="object"&&"kind"in R.result&&R.result.kind==="submit"){l={text:R.result.message,attachments:E??[]},e.statusLine.rearm();continue}e.statusLine.rearm();continue}v=!0}i.push(k);let _=k;if(v){let R=zd(k);if(R){let C=R.name.replace(/^\//,"").split(":").pop()??"";if(C&&Kp(C)){let M={skillName:C,rawArgs:R.args,source:"plugin",capabilities:{compose:!0,subagents:!0}},$=e.session.current.sessionId,x=br($),A=Date.now();J(`[afk trace] preflight.start commandName=${C}`);let P=!1,N=await yr(M,{cwd:e.stats.cwd??process.cwd(),artifactDir:x},K=>{je()&&e.replRenderer.writeLine(m.warning(`\u26A0 preflight(${C}) failed: `)+(K instanceof Error?K.message:String(K)))});P=N!==null,J(`[afk trace] preflight.end commandName=${C} durationMs=${Date.now()-A} success=${P}`),_=qp(N?.manifestBlock,k)}}}let I;if(e.firstTurnHook&&e.stats.totalTurns===0){let R=e.firstTurnHook;e.firstTurnHook=void 0,I=Promise.resolve().then(()=>R(k)).catch(C=>{e.completionWriter.fn(m.warning("\u26A0 ")+"first-turn hook failed: "+(C instanceof Error?C.message:String(C)))})}await GT({text:_,attachments:E},e.session.current,e.stats,{setInFlight(R){n.turnInFlight=R},async onTurnComplete(R,C){await t.appendTurn(R,C)},async onAfterTurn(){await e.contextSampler.onTurn(e.stats.totalTurns),await xS(e.slashCtx),e.statusLine.rearm()},rearmStatus:()=>e.statusLine.rearm(),onTerminalState:R=>g.push(R),setActiveCompositor:R=>{n.activeCompositor=R},setInterruptNotifier:R=>{n.notifyInterrupting=R},scrollRegion:e.statusLine,getCompositor:()=>a.getCompositor(),setBackgroundHandler:R=>a.setBackgroundHandler(R),setSoftStopHandler:R=>a.setSoftStopHandler(R)},e.options.thinkingUi,e.completionWriter,u,a.toRunTurnRefs(mc(e.stats.model,e.stats.planMode))),I!==void 0&&await I}}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 cB}from"node:child_process";import{dirname as uB,isAbsolute as dB,resolve as pB}from"node:path";import{promisify as mB}from"node:util";var VT=mB(cB),fB=3e3,gB=new Set(["empty","orphaned-dir","orphaned-registration","dead-owner"]);async function hB(){let t=(await VT("git",["rev-parse","--git-common-dir"])).stdout.trim();if(!t)throw new Error("Not in a git repository.");let n=dB(t)?t:pB(process.cwd(),t);return uB(n)}async function YT(e){if(e?.disabled)return{ran:!1,removedCount:0,skippedReason:"disabled"};let t;try{t=await hB()}catch{return{ran:!1,removedCount:0,skippedReason:"not-in-repo"}}let n,r=new Promise(o=>{n=setTimeout(()=>o("timeout"),fB)});try{let o=Bt({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=>gB.has(c.verdict)&&i.removed.includes(c.path)).length}}catch{return{ran:!1,removedCount:0,skippedReason:"error"}}finally{n&&clearTimeout(n)}}import{promises as yB}from"node:fs";import{dirname as bB,join as wB}from"node:path";import{randomBytes as SB}from"node:crypto";var kB=["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(`
|
|
2204
|
-
`),XT=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,hm=30,vB=1024,TB=8e3,EB="haiku";async function xB(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=CB(n,vB),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??TB),i=t.signal?IB([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??EB,system:kB,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=RB(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=bB(t.worktreePath);return await AB(l,c)}function RB(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 AB(e,t){if(!await _B(wB(t,e)))return e;let n=SB(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,hm-5)}-${n}`}async function _B(e){try{return await yB.access(e),!0}catch{return!1}}function CB(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 IB(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 xB(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{}}U();import{spawn as eE}from"child_process";import{existsSync as DB,mkdirSync as LB,readFileSync as tE,unlinkSync as FB,writeFileSync as NB}from"fs";import{get as jB}from"https";import{join as nE}from"path";import{readFileSync as PB}from"fs";import{dirname as MB,join as OB}from"path";import{fileURLToPath as $B}from"url";function an(){try{return"3.53.
|
|
2204
|
+
`),XT=/^[a-z0-9]+(-[a-z0-9]+){1,3}$/,hm=30,vB=1024,TB=8e3,EB="haiku";async function xB(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=CB(n,vB),o=new AbortController,s=setTimeout(()=>o.abort(),t.timeoutMs??TB),i=t.signal?IB([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??EB,system:kB,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=RB(a);if(l===null)return t.onSkip?.("invalid-slug-output",a.slice(0,60)),null;let c=bB(t.worktreePath);return await AB(l,c)}function RB(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 AB(e,t){if(!await _B(wB(t,e)))return e;let n=SB(2).toString("hex");return`${e.split("-").slice(0,3).join("-").slice(0,hm-5)}-${n}`}async function _B(e){try{return await yB.access(e),!0}catch{return!1}}function CB(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 IB(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 xB(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{}}U();import{spawn as eE}from"child_process";import{existsSync as DB,mkdirSync as LB,readFileSync as tE,unlinkSync as FB,writeFileSync as NB}from"fs";import{get as jB}from"https";import{join as nE}from"path";import{readFileSync as PB}from"fs";import{dirname as MB,join as OB}from"path";import{fileURLToPath as $B}from"url";function an(){try{return"3.53.3"}catch{}try{let e=MB($B(import.meta.url));for(let t of["../../package.json","../package.json"])try{let n=JSON.parse(PB(OB(e,t),"utf-8"));if(typeof n.version=="string")return n.version}catch{}}catch{}return"0.0.0-unknown"}H();var UB=64*1024,BB=1440*60*1e3,WB="update-check.json",HB="pending-update.json";function rE(){return nE(bi(),WB)}function ym(){return nE(bi(),HB)}function oE(){let e=bi();DB(e)||LB(e,{recursive:!0})}function KB(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 GB(){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 zB(){try{oE();let e=`
|
|
2205
2205
|
const https = require('https');
|
|
2206
2206
|
const fs = require('fs');
|
|
2207
2207
|
const url = 'https://registry.npmjs.org/agent-afk/latest';
|