agent-afk 3.53.0 → 3.53.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 +19 -19
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -1315,7 +1315,7 @@ ${JSON.stringify(I.git,null,2)}
|
|
|
1315
1315
|
|
|
1316
1316
|
Original failure: ${o.failure}`,M;try{M=await R.runToResult(C)}finally{await R.teardown().catch(()=>{})}if(M.status!=="succeeded"||!M.output){if(M.schemaError){let G=M.message?.content||"(no response)";throw new Error(`hypothesis synthesis schema mismatch: ${M.schemaError.message}
|
|
1317
1317
|
Raw response (first 500 chars): ${G.slice(0,500)}
|
|
1318
|
-
Hint: model response must include a fenced JSON block with a hypotheses array.`)}throw new Error(`hypothesis synthesis failed: ${xe(M)}`)}let $=M.output.hypotheses.slice(0,o.maxHypotheses);if($.length===0)return{reproducer:p,triage:f,hypotheses:[],verification_results:[],outcome:"no_hypotheses"};let{premise_verifications:x,hypotheses_to_test:A}=await hM($,async G=>{if(!n?.dispatchSkill)throw new Error("shadow-verify dispatch unavailable (no dispatchSkill in ctx)");let L=JSON.stringify({claims:G,context:`Original failure: ${o.failure}`}),
|
|
1318
|
+
Hint: model response must include a fenced JSON block with a hypotheses array.`)}throw new Error(`hypothesis synthesis failed: ${xe(M)}`)}let $=M.output.hypotheses.slice(0,o.maxHypotheses);if($.length===0)return{reproducer:p,triage:f,hypotheses:[],verification_results:[],outcome:"no_hypotheses"};let{premise_verifications:x,hypotheses_to_test:A}=await hM($,async G=>{if(!n?.dispatchSkill)throw new Error("shadow-verify dispatch unavailable (no dispatchSkill in ctx)");let L=JSON.stringify({claims:G,context:`Original failure: ${o.failure}`}),ee=await n.dispatchSkill("shadow-verify",L);return JSON.parse(ee).verifications});if(A.length===0)return{reproducer:p,triage:f,hypotheses:$,premise_verifications:x,verification_results:[],outcome:"no_hypotheses"};let P=p||o.failure,N=A.map(G=>TM(G,P,o.repoPath,s,u,d,w)),K=await Promise.all(N),D=K.filter(G=>G.reproducer_passed&&G.regressions.length===0).slice().sort((G,L)=>L.confidence-G.confidence)[0]??K.find(G=>G.reproducer_passed),F=SM($,K),W=D?$.find(G=>G.id===D.hypothesis_id):void 0,ne=F==="clear_winner"&&W&&wM(W)?"spec":void 0;return{reproducer:p,triage:f,hypotheses:$,premise_verifications:x.length>0?x:void 0,winner:D?{hypothesis_id:D.hypothesis_id,verification_log:D.verification_log,proposed_fix:W?.proposed_fix||""}:void 0,verification_results:K,outcome:F,recommended_next_skill:ne}}function bM(e,t){let n=`${e}
|
|
1319
1319
|
${t}`,r="unknown",o=n.toLowerCase();/flaky|non-?deterministic|intermittent|sometimes fails|race/.test(o)?r="flaky":/regression|used to work|worked before|broke in|ci.*green.*red|was passing/.test(o)?r="regression":/\b(uncaught|unhandled)\b|panic|segfault|exit(ed)? (with )?(code )?[1-9]|sigsegv|stack overflow|fatal|traceback|core dumped|abort(ed)?|\b(type|reference|range|syntax|internal|eval|uri)error\b/.test(o)?r="crash":/platform|node version|python version|dependency|version mismatch|works on .* not |env(ironment)?|config drift/.test(o)?r="environment":/expected .* but|got .* expected|wrong|incorrect|unexpected/.test(o)&&(r="logic-error");let s=/^(why|what|how|when|where|who|is|are|does|did|can|could|should|would)\b/i,i=/\b(error|exception|panic|throws?|traceback|fail(ed|ure|s)?|undefined|null|nan|segfault|sigsegv|stack ?overflow|abort(ed)?)\w*|:\s*\d+|\bat\s+\S|\bcore dumped\b/i,a=e.split(`
|
|
1320
1320
|
`).map(d=>d.trim()).find(d=>d.length>0),l;a?s.test(a)&&!i.test(e)?l="prose-question":a.length>200?l=`${a.slice(0,197)}...`:l=a:l="unknown";let u=n.match(/(?:^|[\s'"`(])((?:\.{1,2}\/)?[\w@./-]+\.(?:ts|tsx|js|jsx|mjs|cjs|py|rb|go|rs|java|kt|cpp|c|h|hpp|md|json|yaml|yml)(?::\d+(?::\d+)?)?)/)?.[1]??"unknown";return{failure_type:r,error_signature:l,affected_area:u}}function wM(e){let n=`${e.proposed_fix??""}
|
|
1321
1321
|
${e.location??""}`.match(/(?:^|[\s'"`(])((?:\.{1,2}\/)?[\w@./-]+\.(?:ts|tsx|js|jsx|mjs|cjs|py|rb|go|rs|java|kt|cpp|c|h|hpp))/g);return n?new Set(n.map(o=>o.trim().replace(/^[\s'"`(]+/,"").split(":")[0])).size>2:!1}function SM(e,t){if(e.length===0)return"no_hypotheses";let n=t.filter(o=>o.reproducer_passed&&o.regressions.length===0);return n.length===1?"clear_winner":n.length>=2?"multiple_plausible":e.filter(o=>o.confidence>=.7).length>=2?"dissent":"all_inconclusive"}function kM(e){if(!e)return;let t=[/test:\s*(.+)/i,/command:\s*(.+)/i,/reproducer:\s*(.+)/i,/failing test:\s*(.+)/i];for(let n of t){let r=e.match(n);if(r)return r[1]}}function qy(){return async e=>it.allowedTools.includes(e)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${e} not allowed. Allowed tools: ${it.allowedTools.join(", ")}`}}var Jy=[...it.allowedTools,"Agent"];function vM(){return async e=>Jy.includes(e)?{behavior:"allow"}:{behavior:"deny",message:`Tool ${e} not allowed for git orchestrator. Allowed tools: ${Jy.join(", ")}`}}async function TM(e,t,n,r,o,s,i){let a=zy(dM(),`diagnose-hyp-${e.id}-${Date.now()}`),l;try{await pa("git",["worktree","add","--detach",a,"HEAD"],{cwd:n});try{let{writeFile:d}=await import("node:fs/promises"),p="",f="";try{p=(await pa("git",["rev-parse","HEAD"],{cwd:n})).stdout.trim()}catch{}try{f=(await pa("git",["symbolic-ref","--short","HEAD"],{cwd:n})).stdout.trim()}catch{}await d(zy(a,".afk-worktree-meta.json"),JSON.stringify({owner:"diagnose",createdAt:new Date().toISOString(),baseSha:p,baseBranch:f},null,2),"utf-8")}catch{}l=await s.forkSubagent({parent:{sessionId:r},config:{model:"sonnet",systemPrompt:`${o}
|
|
@@ -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
|
|
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- Survey git + infra + memory before non-trivial work \u2192 `/ground-state`\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
|
|
|
@@ -1985,7 +1985,7 @@ Every turn must end in one externally identifiable terminal state. AFK users nee
|
|
|
1985
1985
|
|
|
1986
1986
|
Never end a turn mid-loop without one of these. The terminal-state heading must be the last block of the response, with no trailing prose after it.`,MD=new Set(["repl","telegram"]);function Ma(e,t,n="one-shot"){if(!e)return e;let r=[e];return t&&r.push(ID),MD.has(n)&&r.push(PD),r.join(`
|
|
1987
1987
|
|
|
1988
|
-
`)}import tn from"chalk";var OD={read:tn.hex("#C9B584"),write:tn.hex("#E8A33D"),shell:tn.hex("#A8E060"),subagent:m.plan,skill:tn.hex("#F08AC4"),dag:tn.hex("#4EC9B0"),mcp:tn.hex("#5FE0C0"),web:tn.hex("#A0C4C0"),browser:tn.hex("#FF8A65"),planning:m.meta,schedule:tn.hex("#D4A84B"),other:m.meta},$D={read:"\u25CF",write:"\u270E",shell:"$",subagent:"\u2192",skill:"\u25C6",dag:"\u2B21",mcp:"\u22A1",web:"\u2316",browser:"\u25C9",planning:"\u25B1",schedule:"\u23F2",other:"\u25CF"};function jd(e){return{color:OD[e],glyph:$D[e]}}function co(e){return jd(Tn(e))}function Oa(e){let{description:t,summary:n,lastToolName:r,totalTokens:o,toolUses:s,durationMs:i}=e,a=[];if(r){let{color:c,glyph:u}=co(r);a.push(`via ${c(`${u} ${r}`)}`)}s&&a.push(`${s} tool${s===1?"":"s"}`),o&&a.push(`${
|
|
1988
|
+
`)}import tn from"chalk";var OD={read:tn.hex("#C9B584"),write:tn.hex("#E8A33D"),shell:tn.hex("#A8E060"),subagent:m.plan,skill:tn.hex("#F08AC4"),dag:tn.hex("#4EC9B0"),mcp:tn.hex("#5FE0C0"),web:tn.hex("#A0C4C0"),browser:tn.hex("#FF8A65"),planning:m.meta,schedule:tn.hex("#D4A84B"),other:m.meta},$D={read:"\u25CF",write:"\u270E",shell:"$",subagent:"\u2192",skill:"\u25C6",dag:"\u2B21",mcp:"\u22A1",web:"\u2316",browser:"\u25C9",planning:"\u25B1",schedule:"\u23F2",other:"\u25CF"};function jd(e){return{color:OD[e],glyph:$D[e]}}function co(e){return jd(Tn(e))}function Oa(e){let{description:t,summary:n,lastToolName:r,totalTokens:o,toolUses:s,durationMs:i}=e,a=[];if(r){let{color:c,glyph:u}=co(r);a.push(`via ${c(`${u} ${r}`)}`)}s&&a.push(`${s} tool${s===1?"":"s"}`),o&&a.push(`${te(o)} tok`),i&&a.push(se(i)),a.push("esc to interrupt \xB7 ctrl+b background");let l=a.length>0?` (${a.join(" \xB7 ")})`:"";return n?[m.dim(` \u25E6 ${t}`),m.dim(` ${n}${l}`)]:[m.dim(` \u25E6 ${t}${l}`)]}function $a(e){let t=e.status==="succeeded"?"\u2713":e.status==="failed"?"\u2717":"\u2298",n=e.agentType??e.subagentId,r=[t,n];return e.durationMs!==void 0&&r.push(`\xB7 ${se(e.durationMs)}`),m.dim(` ${r.join(" ")}`)}H();U();import{randomUUID as iL}from"node:crypto";import{createHash as nL}from"crypto";import{mkdir as rL,open as oL,writeFile as sL}from"fs/promises";import{join as Gw}from"path";import{z as S}from"zod";var DD=S.object({phase:S.literal("started"),toolUseId:S.string(),name:S.string(),inputBytes:S.number().int().nonnegative(),subagentId:S.string().optional()}),LD=S.object({phase:S.literal("completed"),toolUseId:S.string(),name:S.string(),resultBytes:S.number().int().nonnegative(),isError:S.boolean(),truncated:S.boolean(),durationMs:S.number().nonnegative(),subagentId:S.string().optional()}),Ow=S.discriminatedUnion("phase",[DD,LD]),FD=S.enum(["PreToolUse","PostToolUse","SessionStart","SessionEnd","SubagentStart","SubagentStop"]),$w=S.object({hookEvent:FD,decision:S.union([S.literal("block"),S.literal("approve"),S.undefined()]),reason:S.string().optional(),blockedTool:S.string().optional(),injectedContextBytes:S.number().int().nonnegative().optional()}),ND=S.object({transition:S.literal("started"),subagentId:S.string(),parentId:S.string(),model:S.string(),allowedTools:S.array(S.string()).readonly().optional(),systemPromptHash:S.string().optional()}),jD=S.object({transition:S.literal("succeeded"),subagentId:S.string(),durationMs:S.number().nonnegative(),turnCount:S.number().int().nonnegative(),totalCostUsd:S.number().nonnegative().optional(),outputBytes:S.number().int().nonnegative()}),UD=S.object({transition:S.literal("failed"),subagentId:S.string(),errorClass:S.string(),errorMessage:S.string(),partialOutputBytes:S.number().int().nonnegative()}),BD=S.object({transition:S.literal("cancelled"),subagentId:S.string(),source:S.enum(["cascade","explicit"])}),Dw=S.discriminatedUnion("transition",[ND,jD,UD,BD]),WD=S.object({transition:S.literal("started"),jobId:S.string(),subagentId:S.string(),label:S.string(),model:S.string()}),HD=S.object({transition:S.literal("completed"),jobId:S.string(),subagentId:S.string(),durationMs:S.number().nonnegative(),outputBytes:S.number().int().nonnegative()}),KD=S.object({transition:S.literal("failed"),jobId:S.string(),subagentId:S.string(),durationMs:S.number().nonnegative(),errorClass:S.string(),errorMessage:S.string()}),GD=S.object({transition:S.literal("cancelled"),jobId:S.string(),subagentId:S.string(),source:S.enum(["explicit","cascade"])}),zD=S.object({transition:S.literal("joined"),jobId:S.string(),subagentId:S.string(),jobStatus:S.enum(["completed","failed","cancelled"])}),Lw=S.discriminatedUnion("transition",[WD,HD,KD,GD,zD]),Fw=S.object({kind:S.literal("monetary"),runningCostUsd:S.number().nonnegative(),maxBudgetUsd:S.number().nonnegative(),lastTurnCostUsd:S.number().nonnegative()}),qD=S.enum(["user_signal","cascade","timeout","budget","hook_block"]),Nw=S.object({origin:qD,cascadedTo:S.array(S.string()).readonly(),reason:S.string().optional()}),jw=S.enum(["manual","token_threshold","turn_count"]),JD=S.object({path:S.string(),sizeBytes:S.number().int().nonnegative(),sha256:S.string().regex(/^[0-9a-f]{64}$/)}),VD=S.object({trigger:jw,preCompactionMessages:S.array(S.unknown()),summary:S.string(),keptTailCount:S.number().int().nonnegative(),keepLastNConfig:S.number().int().nonnegative(),messagesBefore:S.number().int().nonnegative(),messagesAfter:S.number().int().nonnegative(),tokensSavedEstimate:S.number().nonnegative().optional(),summarizationTokens:S.object({input:S.number().int().nonnegative(),output:S.number().int().nonnegative()}).optional()}),YD=S.object({trigger:jw,preCompactionMessagesRef:JD,summary:S.string(),keptTailCount:S.number().int().nonnegative(),keepLastNConfig:S.number().int().nonnegative(),messagesBefore:S.number().int().nonnegative(),messagesAfter:S.number().int().nonnegative(),tokensSavedEstimate:S.number().nonnegative().optional(),summarizationTokens:S.object({input:S.number().int().nonnegative(),output:S.number().int().nonnegative()}).optional()}),XD=S.enum(["model_end_turn","iteration_cap","abort","timeout","budget_exceeded","hook_blocked","max_turns_exceeded"]),Uw=S.object({reason:XD,finalTurnCount:S.number().int().nonnegative(),finalCostUsd:S.number().nonnegative(),finalTokens:S.object({input:S.number().int().nonnegative().optional(),output:S.number().int().nonnegative().optional(),cacheRead:S.number().int().nonnegative().optional(),cacheCreation:S.number().int().nonnegative().optional()}),lastStopReason:S.string().optional()}),Bw=S.object({source:S.string(),assertion:S.string(),evidence:S.array(S.string()).readonly(),confidence:S.number().min(0).max(1),dissent:S.string().optional()}),ZD=S.enum(["browser_open","browser_observe","browser_act","browser_screenshot","browser_extract","browser_close"]),QD=S.enum(["click","fill","press","select","hover","scroll_to","wait_for"]),eL=S.object({kind:S.enum(["semantic","element_id","selector"]),text:S.string().max(80).optional(),role:S.string().optional(),elementId:S.string().optional(),selectorHash:S.string().regex(/^[0-9a-f]{8}$/).optional()}),Ww=S.object({tool:ZD,action:QD.optional(),toolUseId:S.string(),target:eL.optional(),urlBefore:S.string().nullable(),urlAfter:S.string().nullable(),status:S.enum(["ok","error","ambiguous_target","blocked_by_policy"]),screenshotPath:S.string().optional(),observationSummary:S.string().max(500).optional(),error:S.object({reason:S.string(),recoverable:S.boolean()}).optional(),durationMs:S.number().nonnegative()}),tL=S.object({status:S.enum(["succeeded","failed","cancelled"]),finalCostUsd:S.number().nonnegative(),finalTurnCount:S.number().int().nonnegative(),closedAt:S.string().datetime()}),Hw=S.discriminatedUnion("kind",[S.object({kind:S.literal("tool_call"),payload:Ow}),S.object({kind:S.literal("hook_decision"),payload:$w}),S.object({kind:S.literal("subagent_lifecycle"),payload:Dw}),S.object({kind:S.literal("background_agent"),payload:Lw}),S.object({kind:S.literal("budget"),payload:Fw}),S.object({kind:S.literal("abort"),payload:Nw}),S.object({kind:S.literal("compaction"),payload:VD}),S.object({kind:S.literal("closure"),payload:Uw}),S.object({kind:S.literal("claim"),payload:Bw}),S.object({kind:S.literal("browser_event"),payload:Ww})]),Kw=S.discriminatedUnion("kind",[S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("tool_call"),payload:Ow}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("hook_decision"),payload:$w}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("subagent_lifecycle"),payload:Dw}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("background_agent"),payload:Lw}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("budget"),payload:Fw}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("abort"),payload:Nw}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("compaction"),payload:YD}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("closure"),payload:Uw}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("claim"),payload:Bw}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("browser_event"),payload:Ww}),S.object({ts:S.string().datetime(),seq:S.number().int().nonnegative(),kind:S.literal("session_sealed"),payload:tL})]);var Da=class{traceDir;tracePath;seq=0;sealed=!1;fh=null;writeQueue=Promise.resolve();constructor(t){this.traceDir=t.traceDir,this.tracePath=Gw(this.traceDir,"trace.jsonl")}getTracePath(){return this.tracePath}async write(t){if(this.sealed)throw new Error("NdjsonTraceWriter: trace is sealed; write() rejected");return Hw.parse(t),this.enqueue(async()=>{await this.ensureOpen();let n=await this.materializePersistedEvent(t);await this.appendLine(n)})}async seal(t){this.sealed||(this.sealed=!0,await this.enqueue(async()=>{await this.ensureOpen();let n={ts:new Date().toISOString(),seq:this.seq++,kind:"session_sealed",payload:t};await this.appendLine(n),this.fh&&await this.fh.sync()}),await this.closeHandle())}async close(){await this.enqueue(async()=>{}),await this.closeHandle()}enqueue(t){let n=this.writeQueue.then(t,t);return this.writeQueue=n.then(()=>{},()=>{}),n}async ensureOpen(){this.fh||(await rL(this.traceDir,{recursive:!0}),this.fh=await oL(this.tracePath,"a"))}async closeHandle(){if(!this.fh)return;let t=this.fh;this.fh=null,await t.close()}async appendLine(t){if(!this.fh)throw new Error("NdjsonTraceWriter: file handle missing");await this.fh.appendFile(`${JSON.stringify(t)}
|
|
1989
1989
|
`)}async materializePersistedEvent(t){let n=new Date().toISOString(),r=this.seq++;if(t.kind==="compaction"){let o=await this.persistCompactionSidecar(t.payload,r,n);return{ts:n,seq:r,kind:"compaction",payload:o}}return{ts:n,seq:r,kind:t.kind,payload:t.payload}}async persistCompactionSidecar(t,n,r){let o=r.replace(/[:.]/g,"-"),s=Gw(this.traceDir,`${String(n).padStart(6,"0")}-${o}-pre-compaction.json`),i=JSON.stringify(t.preCompactionMessages),a=Buffer.byteLength(i,"utf8"),l=nL("sha256").update(i).digest("hex");await sL(s,i,{encoding:"utf8",flag:"w"});let c={path:s,sizeBytes:a,sha256:l};return{trigger:t.trigger,preCompactionMessagesRef:c,summary:t.summary,keptTailCount:t.keptTailCount,keepLastNConfig:t.keepLastNConfig,messagesBefore:t.messagesBefore,messagesAfter:t.messagesAfter,...t.tokensSavedEstimate!==void 0?{tokensSavedEstimate:t.tokensSavedEstimate}:{},...t.summarizationTokens!==void 0?{summarizationTokens:t.summarizationTokens}:{}}}};function La(e={}){if(T.AFK_TRACE_DISABLED==="1")return null;let t=e.sessionLabel??iL(),n=Si(t),r=new Da({traceDir:n});return{writer:r,tracePath:r.getTracePath(),sessionLabel:t}}U();import{readFileSync as aL,writeFileSync as lL,existsSync as Fa,mkdirSync as cL,readdirSync as uL,statSync as dL,realpathSync as zw}from"fs";import{join as Jw,basename as Vw,resolve as qw,sep as pL}from"path";function Es(){return _f(),dn()}function mL(e){return Jw(Es(),`${e}.json`)}function Ud(e,{write:t=!1}={}){let n=e.includes("/")?e:mL(e),r,o;if(!t&&Fa(n)?(r=zw(n),o=zw(Es())):(r=qw(n),o=qw(Es())),!r.startsWith(o+pL)&&r!==o)throw new Error(`Session path escapes sessions directory: ${e}`);return r}function uo(e,t){let n=Es();Fa(n)||cL(n,{recursive:!0});let r=t??e.sessionId??`session-${Date.now()}`,o={sessionId:e.sessionId,model:e.model,startedAt:e.sessionStartTime,savedAt:Date.now(),totalTurns:e.totalTurns,totalCostUsd:e.totalCostUsd,totalTokens:e.totalTokens,totalDurationMs:e.totalDurationMs,turns:e.turns},s=Ud(r,{write:!0});return lL(s,JSON.stringify(o,null,2)),s}function xs(e){let t;try{t=Ud(e)}catch{return}if(Fa(t))try{let n=aL(t,"utf-8");return JSON.parse(n)}catch{return}}function po(e){let t;try{t=Ud(e)}catch{return}let n=xs(t);if(n)return{path:t,id:Vw(t,".json"),data:n};for(let r of Rs()){if(r.id!==e&&r.sessionId!==e)continue;let o=xs(r.path);if(o)return{path:r.path,id:r.id,data:o}}}function Rs(){let e=Es();if(!Fa(e))return[];let t=[];for(let n of uL(e)){if(!n.endsWith(".json"))continue;let r=Jw(e,n);try{if(!dL(r).isFile())continue;let s=xs(r);if(!s||typeof s.savedAt!="number"||typeof s.model!="string")continue;t.push({path:r,id:Vw(n,".json"),sessionId:s.sessionId,model:s.model,startedAt:s.startedAt,savedAt:s.savedAt,totalTurns:s.totalTurns,totalCostUsd:s.totalCostUsd})}catch{}}return t.sort((n,r)=>r.savedAt-n.savedAt),t}function mo(e){if(e.resume&&e.continue)throw new Error("Use either --resume <id> or --continue, not both.");if(e.resume){let t=po(e.resume);return t?{id:t.id,resumeId:t.data.sessionId??t.id,stored:t.data}:{id:e.resume,resumeId:e.resume}}if(e.continue){let t=Rs()[0];if(!t)throw new Error("No saved sessions found for --continue. Run a session first or use /save.");let n=xs(t.path);if(!n)throw new Error(`Could not load latest saved session: ${t.id}`);return{id:t.id,resumeId:n.sessionId??t.id,stored:n}}}function fo(e){return e?{resume:e.resumeId,sessionId:e.resumeId,...e.stored?{resumeHistory:e.stored.turns.map(t=>({user:t.user,assistant:t.assistant}))}:{}}:{}}function Na(e){return{totalTurns:0,totalCostUsd:0,totalTokens:0,totalDurationMs:0,sessionStartTime:Date.now(),turnCosts:[],turnTokens:[],turns:[],model:e,planMode:!1}}function Yw(e){e.totalTurns=0,e.totalCostUsd=0,e.totalTokens=0,e.totalDurationMs=0,e.sessionStartTime=Date.now(),e.turnCosts.length=0,e.turnTokens.length=0,e.turns.length=0,delete e.sessionId,delete e.pendingPlanExit}function sr(e,t,n,r,o){let s=r?.totalCostUsd??0,i=r?.durationMs??0,a=Number(r?.usage?.input_tokens??0),l=Number(r?.usage?.output_tokens??0),c=a,u=l,d=Number(r?.usage?.cache_read_input_tokens??0)+Number(r?.usage?.cache_creation_input_tokens??0),p=r?.usage?.iterations;if(Array.isArray(p)&&p.length>0){let g=p[p.length-1];if(g&&typeof g=="object"){let h=g;c=Number(h.input_tokens??0),u=Number(h.output_tokens??0),d=Number(h.cache_read_input_tokens??0)+Number(h.cache_creation_input_tokens??0)}}e.totalTurns+=1,e.totalCostUsd+=s,e.totalDurationMs+=i,e.totalTokens+=a+l,e.turnCosts.push(s),e.turnTokens.push({input:c,output:u,cache:d}),r?.sessionId&&!e.sessionId&&(e.sessionId=String(r.sessionId));let f={user:t,assistant:n,timestamp:Date.now(),costUsd:s,durationMs:i,inputTokens:a,outputTokens:l,...o&&o.length>0?{toolEvents:o}:{}};return e.turns.push(f),f}function gL(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}var Zw=10*1024*1024;function Qw(){return new Promise((e,t)=>{let n=[],r=0;if(process.stdin.readableEnded){e("");return}let o=s=>{if(r+=s.length,r>Zw){process.stdin.destroy(new Error(`stdin exceeds ${Zw}-byte limit`));return}n.push(s)};process.stdin.on("data",o),process.stdin.once("end",()=>{process.stdin.removeListener("data",o),e(Buffer.concat(n).toString("utf-8").replace(/\n+$/,""))}),process.stdin.once("error",s=>{process.stdin.removeListener("data",o),t(s)}),process.stdin.resume()})}function eS(e,t){return new Promise((n,r)=>{let o=e.write(t,s=>{s?r(s):o&&n()});if(!o){let s=()=>{e.removeListener("error",i),n()},i=a=>{e.removeListener("drain",s),r(a)};e.once("drain",s),e.once("error",i)}})}function rS(e){e.command("chat").description("Send a message to the agent").argument("[message]","Message to send; use `-` or omit to read from stdin").option("-m, --model <model>","Model to use. Short aliases: opus|opus_1m|sonnet|sonnet_1m|haiku. Any other value (e.g. `auto` for cursor-api-proxy, or a full `claude-*` ID) passes through to the SDK/proxy untouched.",Ye()).option("-s, --stream","[no-op] reserved; use --format stream-json for headless streaming",!1).option("-f, --format <format>","Output format (text|json|stream-json)","text").option("--max-turns <number>","Maximum conversation turns","10").option("--thinking <mode>","Thinking mode: 'adaptive' | 'disabled' | 'enabled:<N>'","enabled:max").option("--effort <level>","Effort level: low|medium|high|xhigh|max").option("--max-budget-usd <usd>","Hard session cost ceiling in USD. Env: AFK_MAX_BUDGET_USD").option("--task-budget <tokens>","Soft per-task token budget. Env: AFK_TASK_BUDGET").option("--max-output-tokens <n|max>","Per-response output cap ('max' = model ceiling). Env: AFK_MAX_OUTPUT_TOKENS").option("--provider <name>","Provider to use: anthropic|anthropic-direct|openai|openai-compatible. Default: auto-selected by model").option("--dump-prompt [path]",'Dump resolved SDK prompt+options+provenance to file (default: ~/.afk/logs/prompt-dump-<ISO>.json) or "stderr"').option("-w, --worktree [branch]","Create a git worktree for an isolated one-shot. Optional value sets the branch name; otherwise auto-named. On clean exit (no uncommitted changes) the worktree and branch are auto-removed; on dirty exit the worktree is preserved. Mirrors `afk interactive -w`.").option("--resume <id>","Resume a persisted session by id").option("--continue","Continue the most recent persisted session in cwd").option("--session-id <uuid>","Assign a specific UUID to this session (creates new; errors if already exists)").action(async(t,n)=>{if(n.resume&&n.continue){process.stderr.write(`Error: --resume and --continue are mutually exclusive
|
|
1990
1990
|
`),process.exitCode=1;return}if(n.sessionId!==void 0&&(n.resume||n.continue)){process.stderr.write(`Error: --session-id is mutually exclusive with --resume and --continue
|
|
1991
1991
|
`),process.exitCode=1;return}if(n.sessionId!==void 0&&!gL(n.sessionId)){process.stderr.write(`Error: --session-id must be a UUID (got: ${n.sessionId})
|
|
@@ -1993,11 +1993,11 @@ Never end a turn mid-loop without one of these. The terminal-state heading must
|
|
|
1993
1993
|
`),process.exitCode=1;return}let r,o=!process.stdin.isTTY;if(t==="-"){if(!o){process.stderr.write(`Error: no stdin available \u2014 pass a message or pipe one in
|
|
1994
1994
|
`),process.exitCode=1;return}r=await Qw()}else if(t===void 0&&o)r=await Qw();else if(t!==void 0)r=t;else{process.stderr.write(`Error: missing message \u2014 pass a message argument or pipe via stdin
|
|
1995
1995
|
`),process.exitCode=1;return}if(r.trim()===""){process.stderr.write(`Error: message is empty \u2014 stdin contained only whitespace
|
|
1996
|
-
`),process.exitCode=1;return}let s=fL("Initializing agent...").start(),i=null,a,l,c,u=!1,d,p=Na(n.model),f=!1;try{if(n.worktree!==void 0)try{l=await ya(n.worktree),c=l.path,s.text=`Worktree ready at ${l.path} (branch: ${l.branch})`}catch(
|
|
1996
|
+
`),process.exitCode=1;return}let s=fL("Initializing agent...").start(),i=null,a,l,c,u=!1,d,p=Na(n.model),f=!1;try{if(n.worktree!==void 0)try{l=await ya(n.worktree),c=l.path,s.text=`Worktree ready at ${l.path} (branch: ${l.branch})`}catch(ee){s.fail("Failed to create worktree"),B(ee)}let g,h,b,y,w,k;try{g=Pn(n.thinking)??eo(),h=Mn(n.effort)??to(),b=no(n.maxBudgetUsd)??vd(),y=no(n.taskBudget)??Td(),w=ro(n.maxOutputTokens)??ks(),k=void 0}catch(ee){s.fail("Invalid options"),B(ee)}if(n.dumpPrompt!==void 0){let ee=n.dumpPrompt===!0?nS.join(tS.homedir(),".afk","logs",`prompt-dump-${new Date().toISOString().replace(/[:.]/g,"-")}.json`):String(n.dumpPrompt);process.env.AFK_DUMP_PROMPT=ee,n.provider!==void 0&&n.provider!=="anthropic"&&n.provider!=="anthropic-direct"&&console.error(`[--dump-prompt] WARNING: active provider (${n.provider}) does not support prompt dumping. No file will be written.`)}let E=le(),v=Qr()??Zr(),_=tt(),I=_.systemPromptSource,R=_.autoRouting?.chat??!1,C=Ma(v,R,"one-shot"),M={},$=mo({resume:n.resume,continue:n.continue});if(n.resume&&$&&!$.stored){s.fail("Session not found"),process.stderr.write(`Error: session not found: ${JSON.stringify(n.resume)}
|
|
1997
1997
|
Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
1998
|
-
`),process.exitCode=1;return}$&&(M=fo($),u=!0,d=$.id),n.sessionId!==void 0&&(M={sessionId:n.sessionId},u=!0,d=n.sessionId);let x=$?.stored?.model??n.model;p.model=x,$?.stored&&(p.totalTurns=$.stored.totalTurns,p.totalCostUsd=$.stored.totalCostUsd,p.totalTokens=$.stored.totalTokens,p.totalDurationMs=$.stored.totalDurationMs,p.turns=[...$.stored.turns],p.sessionId=$.stored.sessionId??$.resumeId,p.sessionStartTime=$.stored.startedAt??Date.now()),n.sessionId!==void 0&&(p.sessionId=n.sessionId);let A,P=La(),N=new Y({apiKey:E,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},...c!==void 0?{cwd:c}:{}}),K=ia(_.openaiBaseUrl!==void 0?{openaiBaseUrl:_.openaiBaseUrl}:{}),q={get sessionId(){return A?.sessionId},getInputStreamRef(){return A?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return A?.abortSignal??new AbortController().signal}},D=aa(n.model,E,K,_.baseUrl,P?.writer,void 0,c),F=new xn({subagentManager:N,parentSession:q,defaultConfig:{apiKey:E,systemPrompt:v,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{}},defaultSubagentModel:In(n.model),childProviderFactory:K,childSkillExecutorFactory:D,depth:0,...c!==void 0?{cwd:c}:{}}),W=new Rn({parentSession:q,defaultModel:n.model,defaultSubagentModel:In(n.model),apiKey:E,childProviderFactory:K,childSkillExecutorFactory:D,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},...P?.writer!==void 0?{traceWriter:P.writer}:{},...c!==void 0?{cwd:c}:{}}),ne=new ao({parentSession:q,defaultModel:n.model,defaultSubagentModel:In(n.model),apiKey:E,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},systemPrompt:v??""});if(a=new qe,k=wa(n.provider,{subagentExecutor:F,skillExecutor:W,composeExecutor:ne,memoryStore:a,model:String(n.model),..._.openaiBaseUrl!==void 0?{openaiBaseUrl:_.openaiBaseUrl}:{}})??new Ue({permissions:{allowedTools:[...wn,...Qn,...vt,"agent","skill","compose"]},subagentExecutor:F,skillExecutor:W,composeExecutor:ne,memoryStore:a,surface:"cli"}),i=new st(nr({model:x,apiKey:E,maxTurns:parseInt(n.maxTurns,10),hookRegistry:lo(
|
|
1999
|
-
`),Me.type==="chunk"&&Me.chunk.type==="content"&&(Te+=Me.chunk.content),Me.type==="done"&&(sr(p,r,Te,Me.metadata),Me.metadata?.sessionId&&!p.sessionId&&(p.sessionId=String(Me.metadata.sessionId))),Me.type==="error"){process.exitCode=1;break}return}let G=await i.sendMessage(r,{stream:n.stream});s.succeed("Response received");let L=i.getLastResponseMetadata();if(sr(p,r,G.content,L??void 0),L?.sessionId&&!p.sessionId&&(p.sessionId=String(L.sessionId)),n.format==="json"){let
|
|
2000
|
-
\u{1F916} Claude:`)),console.log(kt(G.content)),L){let
|
|
1998
|
+
`),process.exitCode=1;return}$&&(M=fo($),u=!0,d=$.id),n.sessionId!==void 0&&(M={sessionId:n.sessionId},u=!0,d=n.sessionId);let x=$?.stored?.model??n.model;p.model=x,$?.stored&&(p.totalTurns=$.stored.totalTurns,p.totalCostUsd=$.stored.totalCostUsd,p.totalTokens=$.stored.totalTokens,p.totalDurationMs=$.stored.totalDurationMs,p.turns=[...$.stored.turns],p.sessionId=$.stored.sessionId??$.resumeId,p.sessionStartTime=$.stored.startedAt??Date.now()),n.sessionId!==void 0&&(p.sessionId=n.sessionId);let A,P=La(),N=new Y({apiKey:E,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},...c!==void 0?{cwd:c}:{}}),K=ia(_.openaiBaseUrl!==void 0?{openaiBaseUrl:_.openaiBaseUrl}:{}),q={get sessionId(){return A?.sessionId},getInputStreamRef(){return A?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return A?.abortSignal??new AbortController().signal}},D=aa(n.model,E,K,_.baseUrl,P?.writer,void 0,c),F=new xn({subagentManager:N,parentSession:q,defaultConfig:{apiKey:E,systemPrompt:v,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{}},defaultSubagentModel:In(n.model),childProviderFactory:K,childSkillExecutorFactory:D,depth:0,...c!==void 0?{cwd:c}:{}}),W=new Rn({parentSession:q,defaultModel:n.model,defaultSubagentModel:In(n.model),apiKey:E,childProviderFactory:K,childSkillExecutorFactory:D,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},...P?.writer!==void 0?{traceWriter:P.writer}:{},...c!==void 0?{cwd:c}:{}}),ne=new ao({parentSession:q,defaultModel:n.model,defaultSubagentModel:In(n.model),apiKey:E,..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},systemPrompt:v??""});if(a=new qe,k=wa(n.provider,{subagentExecutor:F,skillExecutor:W,composeExecutor:ne,memoryStore:a,model:String(n.model),..._.openaiBaseUrl!==void 0?{openaiBaseUrl:_.openaiBaseUrl}:{}})??new Ue({permissions:{allowedTools:[...wn,...Qn,...vt,"agent","skill","compose"]},subagentExecutor:F,skillExecutor:W,composeExecutor:ne,memoryStore:a,surface:"cli"}),i=new st(nr({model:x,apiKey:E,maxTurns:parseInt(n.maxTurns,10),hookRegistry:lo(ee=>{console.log($a(ee))},"cli",a).registry,...C!==void 0?{systemPrompt:C}:{},...I!==void 0?{systemPromptSource:I}:{},...g!==void 0?{thinking:g}:{},...h!==void 0?{effort:h}:{},...b!==void 0?{maxBudgetUsd:b}:{},...y!==void 0?{taskBudget:y}:{},...w!==void 0?{maxOutputTokens:w}:{},..._.baseUrl!==void 0?{baseUrl:_.baseUrl}:{},...P?{traceWriter:P.writer}:{},..._.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:_.autoResumeOnUsageLimit}:{},...c!==void 0?{cwd:c}:{},...M,provider:k})),A=i,s.text="Sending message...",n.format==="stream-json"){let ee=(Me,ct)=>ct instanceof Date?ct.toISOString():ct instanceof Error?{message:ct.message,name:ct.name}:ct;s.stop();let Te="",Oe=i.sendMessageStream(r);for await(let Me of Oe)if(await eS(process.stdout,JSON.stringify(Me,ee)+`
|
|
1999
|
+
`),Me.type==="chunk"&&Me.chunk.type==="content"&&(Te+=Me.chunk.content),Me.type==="done"&&(sr(p,r,Te,Me.metadata),Me.metadata?.sessionId&&!p.sessionId&&(p.sessionId=String(Me.metadata.sessionId))),Me.type==="error"){process.exitCode=1;break}return}let G=await i.sendMessage(r,{stream:n.stream});s.succeed("Response received");let L=i.getLastResponseMetadata();if(sr(p,r,G.content,L??void 0),L?.sessionId&&!p.sessionId&&(p.sessionId=String(L.sessionId)),n.format==="json"){let ee=L?Number(L.usage?.input_tokens??0):0,Te=L?Number(L.usage?.output_tokens??0):0;console.log(JSON.stringify({success:!0,model:x,message:G.content,timestamp:G.timestamp,...L?.totalCostUsd!==void 0?{costUsd:L.totalCostUsd}:{},...L?.durationMs!==void 0?{durationMs:L.durationMs}:{},...ee>0?{inputTokens:ee}:{},...Te>0?{outputTokens:Te}:{}},null,2))}else{if(console.log(Xw.cyan(`
|
|
2000
|
+
\u{1F916} Claude:`)),console.log(kt(G.content)),L){let ee=[];L.durationMs&&ee.push(se(L.durationMs)),L.totalCostUsd!==void 0&&ee.push(Le(L.totalCostUsd));let Te=Number(L.usage?.input_tokens??0),Oe=Number(L.usage?.output_tokens??0);Te+Oe>0&&ee.push(te(Te+Oe)+" tokens"),ee.length>0&&console.log(Xw.dim(" \xB7 "+ee.join(" \xB7 ")))}console.log("")}}catch(g){if(f=!0,n.format==="stream-json"){let h=g instanceof Error?g:new Error(String(g));try{await eS(process.stdout,JSON.stringify({type:"error",error:{message:h.message,name:h.name}})+`
|
|
2001
2001
|
`)}catch{}process.exitCode=1}s.fail("Failed to send message"),B(g)}finally{if(u&&p.totalTurns>0&&!f)try{let h=uo(p,d).replace(/\.json$/,"").split("/").pop()??d??p.sessionId??"unknown";process.stderr.write(`Continue with: afk chat <msg> --resume ${h}
|
|
2002
2002
|
`)}catch{}i&&await i.close(),a?.close(),l!==void 0&&await l.cleanup()}})}H();import qB from"ora";import*as aE from"node:os";import*as vr from"node:path";import{execFileSync as JB}from"node:child_process";var ja=new Set;function ir(e){return ja.add(e),()=>{ja.delete(e)}}async function Ua(){await Promise.all([...ja].map(e=>e())),ja.clear()}var hL=/^[A-Za-z0-9_@%+=:,./-]+$/;function oS(e){return hL.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function go(e,t){let n=["afk","interactive"];return typeof t=="string"&&t.length>0&&n.push("--model",oS(t)),n.push("--resume",oS(e)),n.join(" ")}import{homedir as yL}from"node:os";import{sep as jt}from"node:path";function Ba(e,t={}){if(!e)return"";let n=t.homedir??yL(),r=bL(e,n),o=t.maxWidth;if(o===void 0||o<=0||z(r)<=o)return r;let s=r.split(jt).filter(d=>d.length>0);if(s.length<=1)return ue(r,o);let a=r.startsWith("~")?"~":s[0],l=1,c=s[s.length-1],u=[];for(let d=s.length-2;d>=l;d--){let p=s.slice(l,d+1),f=p.length>0?p.join(jt)+jt:"";u.push(`${a}${jt}${f}\u2026${jt}${c}`)}u.push(`${a}${jt}\u2026${jt}${c}`);for(let d of u)if(z(d)<=o)return d;return ue(u[u.length-1],o)}function bL(e,t){if(!t)return e;if(e===t)return"~";let n=t.endsWith(jt)?t:t+jt;return e.startsWith(n)?"~"+jt+e.slice(n.length):e}import*as AT from"node:readline";import*as Gd from"node:readline";var wL=/\x1B\][^\x07\x1B]*(?:\x07|\x1B\\)|\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])|\x9B[0-?]*[ -/]*[@-~]|[\x80-\x9F]/g;function ce(e,t=128){let n=e.replace(wL,"");return n.length>t?n.slice(0,t)+"\u2026":n}function sS(e=process.env){return e.AFK_DEMO_CLEAN==="1"||typeof e.SCRIPT=="string"&&e.SCRIPT.length>0||e.ASCIINEMA_REC==="1"}function SL(e=process.env){return e.AFK_BELL==="1"}function iS(e=process.env){return e.AFK_REDUCED_MOTION==="1"}function Wa(e,t=process.env){SL(t)&&e.isTTY&&e.write("\x07")}var Wd=64,Bd=256,Ha=20,Hd=new Set(["__proto__","constructor","prototype"]);async function kL(e,t){if(!process.stdout.isTTY||!process.stdin.isTTY||e.length===0)return null;let n=10,r=0,o=0;function s(){let u=o,d=Math.min(u+n,e.length);return{start:u,end:d}}function i(){let{start:u,end:d}=s(),p=[];for(let f=u;f<d;f++){let g=ce(e[f],80);f===r?p.push(` ${m.bold("\u25B6 "+g)}`):p.push(` ${m.dim(g)}`)}if(e.length>n){let{end:f}=s();p.push(m.dim(` (${o+1}\u2013${f} of ${e.length} \u2191/\u2193 to scroll)`))}else p.push(m.dim(" \u2191/\u2193 navigate Enter select Esc cancel"));return p}let a=i();process.stdout.write(a.join(`
|
|
2003
2003
|
`)+`
|
|
@@ -2007,8 +2007,8 @@ Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
|
2007
2007
|
`)+`
|
|
2008
2008
|
`);let c=l.length;function u(){let d=a();process.stdout.write(`\x1B[${c}A\x1B[0J`+d.join(`
|
|
2009
2009
|
`)+`
|
|
2010
|
-
`),c=d.length}return new Promise(d=>{process.stdin.setRawMode(!0),Gd.emitKeypressEvents(process.stdin);let p=(g,h)=>{if(h)if(h.name==="up"||h.sequence==="\x1B[A")r>0&&(r--,r<o&&(o=r),u());else if(h.name==="down"||h.sequence==="\x1B[B"){if(r<e.length-1){r++;let{end:b}=i();r>=b&&o++,u()}}else h.name==="space"?(s.has(r)?s.delete(r):s.add(r),u()):h.name==="return"||h.name==="enter"?(f(),d([...s].sort((b,y)=>b-y))):(h.name==="escape"||h.ctrl&&h.name==="c")&&(f(),d(":cancel"))};function f(){process.stdin.removeListener("keypress",p);try{process.stdin.setRawMode(!1)}catch{}}process.stdin.on("keypress",p)})}var ho={action:"decline"},oe={action:"cancel"},TL={action:"accept"};function EL(e){let t=e.properties,n={},r=0,o=!1;if(typeof t=="object"&&t!==null){let a=0;for(let[l,c]of Object.entries(t))if(!Hd.has(l)){if(r+=1,a>=Wd){o=!0;continue}n[l]=c,a+=1}}let s=e.required,i=new Set(Array.isArray(s)?s.slice(0,Wd*2).filter(a=>typeof a=="string").filter(a=>!Hd.has(a)):[]);return{properties:n,required:i,fieldsTruncated:o,originalFieldCount:r}}function xL(e,t){e.line(),e.line(m.warning("\u26A0 MCP form elicitation")),e.line(m.dim(" server: ")+m.bold(ce(t.serverName,64))),e.line(m.dim(" message: ")+ce(t.message,256)),t.elicitationId&&e.line(m.dim(" id: ")+ce(t.elicitationId,64)),e.line(m.dim(" Type :decline or :cancel at any prompt to exit.")),e.line()}async function RL(e,t,n,r,o,s){if(s.aborted)return{tag:"cancel"};let i=ce(t.description??t.title??e),a=ce(t.type??"string",32),l=ce(e,64),c;if(t.enum!==void 0){let d=t.enum.slice(0,Ha).map(f=>ce(String(f),32)).join("|"),p=t.enum.length>Ha?"|\u2026":"";c=` (enum: ${d}${p})`}else a==="boolean"?c=" (boolean: y/n)":a==="number"||a==="integer"?c=` (${a})`:a==="string"?c=" (string)":(c=` (${a} \u2014 treated as string)`,o.line(m.warning(` \u26A0 Unknown field type '${a}' for '${l}' \u2014 collecting as string.`)));let u=n?"":m.dim(" [optional, enter to skip]");for(o.line(m.dim(` [${l}]`)+m.dim(` ${i}`)+m.dim(c)+u),t.enum!==void 0&&t.enum.length>Bd&&o.line(m.warning(` \u26A0 Field '${l}' has ${t.enum.length} enum values; only the first ${Bd} are valid for input.`));;){let d;try{d=await r(m.dim(" > "))}catch{return{tag:"cancel"}}if(s.aborted)return{tag:"cancel"};let p=d.trim();if(p===":cancel")return{tag:"cancel"};if(p===":decline")return{tag:"decline"};if(p===""){if(n){o.line(m.warning(" (required \u2014 cannot be skipped)"));continue}return{tag:"value",value:t.default}}let f;if(a==="boolean"){let g=p.toLowerCase();if(g==="y"||g==="yes"||g==="true"||g==="1")f=!0;else if(g==="n"||g==="no"||g==="false"||g==="0")f=!1;else{o.line(m.warning(" Invalid boolean \u2014 enter y/yes/true/1 or n/no/false/0."));continue}}else if(a==="number"){let g=Number(p);if(!isFinite(g)){o.line(m.warning(" Invalid number \u2014 enter a numeric value."));continue}f=g}else if(a==="integer"){let g=parseInt(p,10);if(!isFinite(g)||String(g)!==p.replace(/\.0+$/,"")){o.line(m.warning(" Invalid integer \u2014 enter a whole number."));continue}f=g}else f=p;if(t.enum!==void 0){let g=t.enum.slice(0,Bd),h=!1;for(let b of g)if(String(b)===String(f)){h=!0;break}if(!h){let b=ce(String(f),64),y=g.slice(0,Ha).map(k=>ce(String(k),32)).join(", "),w=g.length>Ha?", \u2026":"";o.line(m.warning(` '${b}' is not a valid choice. Valid: ${y}${w}`));continue}}return{tag:"value",value:f}}}function AL(e,t){e.line(),e.line(m.warning("\u26A0 MCP elicitation")),e.line(m.dim(" server: ")+m.bold(ce(t.serverName,64))),e.line(m.dim(" message: ")+ce(t.message,256)),t.url&&e.line(m.dim(" url: ")+m.brand(ce(t.url,512))),t.elicitationId&&e.line(m.dim(" id: ")+ce(t.elicitationId,64)),e.line()}var ar={action:"skip"};function Kd(e){let t=[];return t.push(m.warning(" \u{1F4AC} Agent question")),t.push(m.bold(" ? "+ce(e.message,512))),e.context&&t.push(m.dim(" "+ce(e.context,512))),t.push(""),t}async function _L(e,t,n,r){let o=Kd(t),s=t.allowSkip===!0;if(e==="number"){let u=t.min,d=t.max,f=`enter to submit \xB7 esc to cancel${u!==void 0&&d!==void 0?` [${u}\u2013${d}]`:u!==void 0?` [\u2265${u}]`:d!==void 0?` [\u2264${d}]`:""}`,h=await n({header:o,help:f,validate:y=>{let w=y.trim();if(w==="")return s?null:"Please enter a number (or esc to cancel).";let k=Number(w);return Number.isFinite(k)?u!==void 0&&k<u?`Value must be \u2265 ${u}.`:d!==void 0&&k>d?`Value must be \u2264 ${d}.`:null:"Please enter a valid number."},signal:r});if(h===null)return null;let b=h.trim();return b===""&&s?{tag:"skip"}:{tag:"number",value:Number(b)}}let i=t.minLength,a=t.maxLength,c=await n({header:o,validate:u=>u===""?s?null:"Please enter a response (or esc to cancel).":i!==void 0&&u.length<i?`Response must be at least ${i} characters.`:a!==void 0&&u.length>a?`Response must be at most ${a} characters.`:null,signal:r});return c===null?null:c===""&&s?{tag:"skip"}:{tag:"text",value:c}}async function CL(e,t,n){if(n.aborted)return ho;let{readLine:r,writer:o,pendingCount:s,pickFromList:i,readTextOverlay:a}=t,l=e.type??"text",c=s();if(c>1&&o.line(m.dim(` [${c} questions queued]`)),(l==="choice"||l==="multi_choice")&&i&&(e.choices?.length??0)>0){let p=(e.choices??[]).map(h=>ce(h,128)),f;try{f=await i({header:Kd(e),options:p,multi:l==="multi_choice",signal:n})}catch{return oe}if(n.aborted||f===null)return oe;if(f.length===0)return e.allowSkip?ar:oe;let g=f.length===1?ce(f[0]??"",128):f.map(h=>ce(h,128)).join(", ");return o.line(m.dim(" \u2713 ")+m.brand(g)),l==="choice"?{action:"accept",content:{value:f[0]}}:{action:"accept",content:{value:[...f]}}}if(l==="confirm"&&i){let f=e.questionDefault!==!1?["Yes","No"]:["No","Yes"],g;try{g=await i({header:Kd(e),options:f,multi:!1,signal:n})}catch{return oe}if(n.aborted||g===null)return oe;let h=g[0];if(h===void 0)return oe;let b=h==="Yes";return o.line(m.dim(" \u2713 ")+(b?m.success("Yes"):m.error("No"))),{action:"accept",content:{value:b}}}if((l==="text"||l==="number")&&a){let p=await _L(l,e,a,n);if(p===null)return oe;if(p.tag==="skip")return ar;let f=p.tag==="text"?ce(p.value,256):String(p.value);return o.line(m.dim(" \u2713 ")+m.brand(f)),{action:"accept",content:{value:(p.tag==="text",p.value)}}}if(o.line(),o.line(m.warning("\u{1F4AC} Agent question")),e.context&&o.line(m.dim(" context: ")+ce(e.context,512)),o.line(m.bold(" "+ce(e.message,512))),o.line(m.dim(" Type :cancel to skip this question.")),o.line(),l==="confirm"){o.line("\x07");let p=e.questionDefault===!0?"Y/n":"y/N";for(;;){if(n.aborted)return oe;let f;try{f=(await r(m.dim(` Continue? [${p}] `))).trim().toLowerCase()}catch{return oe}if(n.aborted||f===":cancel")return oe;if(f==="")return{action:"accept",content:{value:e.questionDefault===!0}};if(f==="y"||f==="yes")return{action:"accept",content:{value:!0}};if(f==="n"||f==="no")return{action:"accept",content:{value:!1}};o.line(m.warning(" Please enter y or n."))}}if(l==="choice"){o.line("\x07");let p=e.choices??[],f=await kL(p,n);if(f!==null){if(f===":cancel")return oe;let g=p[f];return g!==void 0?(o.line(m.dim(` Selected: ${ce(g,128)}`)),{action:"accept",content:{value:g}}):oe}for(p.forEach((g,h)=>{o.line(` ${h+1}. ${ce(g,128)}`)});;){if(n.aborted)return oe;let g;try{g=(await r(m.dim(" Enter number: "))).trim()}catch{return oe}if(n.aborted||g===":cancel")return oe;if(g===""&&e.allowSkip)return ar;let h=parseInt(g,10);if(!isFinite(h)||String(h)!==g||h<1||h>p.length){o.line(m.warning(` Please enter a number between 1 and ${p.length}.`));continue}return{action:"accept",content:{value:p[h-1]}}}}if(l==="multi_choice"){let p=e.choices??[],f=await vL(p,n);if(f!==null){if(f===":cancel")return oe;if(f.length===0&&e.allowSkip)return ar;if(f.length>0){let g=f.map(h=>p[h]);return o.line(m.dim(` Selected: ${g.map(h=>ce(h,64)).join(", ")}`)),{action:"accept",content:{value:g}}}}for(p.forEach((g,h)=>{o.line(` ${h+1}. ${ce(g,128)}`)});;){if(n.aborted)return oe;let g;try{g=(await r(m.dim(" Enter numbers (comma-separated): "))).trim()}catch{return oe}if(n.aborted||g===":cancel")return oe;if(g===""&&e.allowSkip)return ar;if(g===""){o.line(m.warning(" Please enter at least one selection."));continue}let h=g.split(",").map(w=>w.trim()),b=[],y=!0;for(let w of h){let k=parseInt(w,10);if(!isFinite(k)||String(k)!==w||k<1||k>p.length){o.line(m.warning(` Invalid selection "${ce(w,32)}". Enter numbers between 1 and ${p.length}.`)),y=!1;break}b.push(p[k-1])}if(y)return{action:"accept",content:{value:b}}}}if(l==="number"){let p=e.min,f=e.max,g=p!==void 0&&f!==void 0?` [${p}\u2013${f}]`:p!==void 0?` [\u2265${p}]`:f!==void 0?` [\u2264${f}]`:"";for(;;){if(n.aborted)return oe;let h;try{h=(await r(m.dim(` Enter a number${g}: `))).trim()}catch{return oe}if(n.aborted||h===":cancel")return oe;if(h===""&&e.allowSkip)return ar;if(h===""&&!e.allowSkip){o.line(m.warning(" Please enter a number (or :cancel to skip)."));continue}let b=Number(h);if(!isFinite(b)){o.line(m.warning(" Please enter a valid number."));continue}if(p!==void 0&&b<p){o.line(m.warning(` Value must be \u2265 ${p}.`));continue}if(f!==void 0&&b>f){o.line(m.warning(` Value must be \u2264 ${f}.`));continue}return{action:"accept",content:{value:b}}}}let u=e.minLength,d=e.maxLength;for(;;){if(n.aborted)return oe;let p;try{p=(await r(m.dim(" > "))).trim()}catch{return oe}if(n.aborted||p===":cancel")return oe;if(p===""&&e.allowSkip)return ar;if(p===""){o.line(m.warning(" Please enter a response (or type :cancel to skip)."));continue}if(u!==void 0&&p.length<u){o.line(m.warning(` Response must be at least ${u} characters.`));continue}if(d!==void 0&&p.length>d){o.line(m.warning(` Response must be at most ${d} characters.`));continue}return{action:"accept",content:{value:p}}}}function Ka(e){return async(t,{signal:n})=>{if(n.aborted)return ho;Wa(process.stdout),e.suspendInput?.();try{if(t.origin==="agent")return await CL(t,e,n);if(t.mode==="form"){let o=t.requestedSchema,{properties:s,required:i,fieldsTruncated:a,originalFieldCount:l}=typeof o=="object"&&o!==null?EL(o):{properties:{},required:new Set,fieldsTruncated:!1,originalFieldCount:0};xL(e.writer,t),a&&e.writer.line(m.warning(` \u26A0 Schema has ${l} fields; only the first ${Wd} will be prompted (server may be malformed or compromised).`));let c=Object.create(null);if(Object.keys(s).length===0)return e.writer.line(m.warning(" \u26A0 Form schema has no usable fields \u2014 declining.")),ho;for(let u of i)if(!(u in s))return e.writer.line(m.warning(` \u26A0 Required field '${ce(u,64)}' has no schema entry \u2014 declining.`)),ho;for(let[u,d]of Object.entries(s)){if(n.aborted)return oe;let p=await RL(u,d,i.has(u),e.readLine,e.writer,n);if(p.tag==="cancel")return oe;if(p.tag==="decline")return ho;p.value!==void 0&&!Hd.has(u)&&(c[u]=p.value)}return{action:"accept",content:{...c}}}AL(e.writer,t);let r=(await e.readLine(m.dim("Continue? [y/N] "))).trim().toLowerCase();return r===""?oe:r==="y"||r==="yes"?TL:ho}finally{e.resumeInput?.()}}}function aS(e){let t=Math.max(0,Math.min(1,e.ratio)),n=t>.8?m.error:t>.5?m.warning:m.meta,r=20,o=Math.round(t*r),s=r-o,i="["+"\u2588".repeat(o)+"\u2591".repeat(s)+"]",a=Math.round(t*100)+"%",l="";e.used!==void 0&&e.limit!==void 0&&(l=ee(e.used)+"/"+ee(e.limit));let c=l?`${i} ${a} ${l}`:`${i} ${a}`,u=`${i} ${a}`,d=`ctx ${a}`,p=e.sparkline?m.meta(e.sparkline)+" ":"",f=e.sparkline?z(e.sparkline)+1:0,g=Math.max(0,e.width-f);if(z(c)<=g&&g>90)return p+n(c);if(z(u)<=g&&g>32)return p+n(u);if(z(d)<=g)return p+n(d);if(e.width>0){let h=p+n(d);return ue(h,e.width)}return n(a)}var Ga=class{stream;force;throttleMs;started=!1;lastRepaint=0;lastFields=null;resizeUnsub=null;lastPaintedRow=null;extraRows=0;constructor(t={}){this.stream=t.stream??process.stdout,this.force=t.force??!1,this.throttleMs=t.throttleMs??100}get enabled(){return this.force||!!this.stream.isTTY}start(){if(this.started||!this.enabled)return;this.started=!0,this.lastRepaint=0;let t=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.resizeUnsub===null&&(this.resizeUnsub=Ge.subscribe(()=>{this.onResize()}))}onResize(){if(!this.started||!this.enabled)return;let t=this.currentRows();this.stream.write("\x1B[s"),this.lastPaintedRow!==null&&this.lastPaintedRow!==this.paintRow(t)&&(this.stream.write(`\x1B[${this.lastPaintedRow};1H`),this.stream.write("\x1B[2K")),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.flush()}repaint(t){if(!this.enabled||!this.started){this.lastFields=t;return}let n=Date.now();if(n-this.lastRepaint<this.throttleMs){this.lastFields=t;return}this.lastRepaint=n,this.lastFields=t;let r=this.currentRows();this.stream.write("\x1B[s"),this.stream.write(`\x1B[${this.paintRow(r)};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatLine(t)),this.stream.write("\x1B[u"),this.lastPaintedRow=this.paintRow(r)}flush(){this.lastRepaint=0,this.lastFields&&this.repaint(this.lastFields)}setExtraRows(t){if(this.extraRows=t,this.started&&this.enabled){let n=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(n),this.stream.write("\x1B[u"),this.flush()}}getExtraRows(){return this.extraRows}rearm(){if(!this.started||!this.enabled)return;let t=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.flush()}withFullScrollRegion(t){if(!this.started||!this.enabled)return t();this.stream.write("\x1B[s"),this.stream.write("\x1B[r"),this.stream.write("\x1B[u");try{return t()}finally{let n=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(n),this.stream.write("\x1B[u"),this.flush()}}stop(){if(this.resizeUnsub!==null&&(this.resizeUnsub(),this.resizeUnsub=null),!this.started||!this.enabled){this.started=!1;return}let t=this.currentRows();this.stream.write("\x1B[s"),this.stream.write(`\x1B[${this.lastPaintedRow??this.paintRow(t)};1H`),this.stream.write("\x1B[2K"),this.stream.write("\x1B[r"),this.stream.write("\x1B[u"),this.started=!1,this.lastRepaint=0,this.lastPaintedRow=null}formatLine(t){let n=[],r=Math.max(4,(this.stream.columns??80)-2);if(t.cwd){let a=Math.max(8,Math.floor(r*.4)),l=Ba(t.cwd,{maxWidth:a});l&&n.push({text:m.dim(l)})}if(n.push({text:m.brand(t.model)}),t.planMode&&n.push({text:m.warning("\u25CF plan")}),t.contextPct!==void 0){let a=aS({ratio:t.contextPct,used:t.contextUsedTokens,limit:t.contextLimit,sparkline:t.contextSparkline,width:r});n.push({text:a,droppablePriority:1})}t.cost!==void 0&&n.push({text:m.meta(`$${t.cost.toFixed(2)}`),droppablePriority:2}),t.tokens!==void 0&&n.push({text:m.meta(`${IL(t.tokens)} tok`),droppablePriority:3});let o=m.dim(" \xB7 "),s=n.map(a=>a.text).join(o);if(z(s)<=r)return s;let i=n.filter(a=>a.droppablePriority!==void 0);for(;i.length>0&&z(s)>r;){let a=Math.max(...i.map(l=>l.droppablePriority));n=n.filter(l=>l.droppablePriority===void 0||l.droppablePriority!==a),s=n.map(l=>l.text).join(o),i=n.filter(l=>l.droppablePriority!==void 0)}return ue(s,r)}currentRows(){let t=this.stream.rows;return typeof t=="number"&&t>0?t:24}paintRow(t){return t>1?t:1}writeScrollRegion(t){let n=1+this.extraRows;if(t>n){this.stream.write(`\x1B[1;${t-n}r`);return}this.stream.write("\x1B[r")}};function IL(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}var at=new Map,lr=new Map;function de(e){if(at.has(e.name))throw new Error(`Slash command already registered: ${e.name}`);at.set(e.name,e);for(let t of e.aliases??[]){if(lr.has(t)||at.has(t))throw new Error(`Slash alias collides: ${t}`);lr.set(t,e.name)}}function On(e){if(at.has(e.name)){for(let[t,n]of lr.entries())n===e.name&&lr.delete(t);at.delete(e.name)}de(e)}function lS(e){at.has(e.name)||de(e)}function cS(){at.clear(),lr.clear()}function Xe(){return[...at.values()].sort((e,t)=>e.name.localeCompare(t.name))}function uS(){let e=[];for(let[t,n]of lr.entries()){let r=at.get(n);r&&e.push({alias:t,canonical:n,summary:r.summary})}return e.sort((t,n)=>t.alias.localeCompare(n.alias))}function PL(e){if(at.has(e))return at.get(e);let t=lr.get(e);return t?at.get(t):void 0}function ML(e,t){let n=Array.from({length:e.length+1},()=>new Array(t.length+1).fill(0));for(let r=0;r<=e.length;r++)n[r][0]=r;for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let o=1;o<=t.length;o++){let s=e[r-1]===t[o-1]?0:1;n[r][o]=Math.min(n[r-1][o]+1,n[r][o-1]+1,n[r-1][o-1]+s)}return n[e.length][t.length]}function OL(e,t=3){let n;for(let r of at.keys()){let o=ML(e,r);o<=t&&(n===void 0||o<n.dist)&&(n={name:r,dist:o})}return n?.name}function zd(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.indexOf(" ");return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}async function dS(e,t,n){let r=zd(e);if(r===null)return{handled:!1};let o=PL(r.name);if(!o){let a=OL(r.name);return a?t.out.warn(`Unknown command: ${r.name} (did you mean ${a}?)`):t.out.warn(`Unknown command: ${r.name} (type /help for commands)`),{handled:!0,result:"continue"}}let s=n??[];s.length>0&&o.acceptsAttachments!==!0&&t.out.warn(`\u26A0 Image attachments are ignored by ${r.name} (images only reach the model on skill commands like /forge, /mint).`);let i=await o.handler(t,r.args,o.acceptsAttachments===!0?s:void 0);return i==="forward"?{handled:!1}:{handled:!0,result:i}}import FL from"ora";function pS(e,t=5){if(e.length===0)return"";let n=e.slice(-t),r=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];return n.map(o=>{let s=Math.max(0,Math.min(1,o)),i=Math.min(7,Math.floor(s*8));return r[i]}).join("")}function za(e,t,n){e.totalTurns=t.totalTurns,e.totalCostUsd=t.totalCostUsd,e.totalTokens=t.totalTokens,e.totalDurationMs=t.totalDurationMs,e.turns=[...t.turns],e.sessionId=t.sessionId??n,e.model=t.model,e.sessionStartTime=t.startedAt??Date.now()}function qa(e,t){let n=e.turns;if(n.length===0)return;let r=n[n.length-1];if(!r)return;let o=fS(mS(r.user),80),s=fS(LL(mS(r.assistant)),120);o.length>0&&t.fn(m.dim(` Last: ${o}`)),s.length>0&&t.fn(m.dim(` \u21B3 ${s}`)),t.fn(m.dim(" \u21AA /history for full review"))}function mS(e){return e.replace(DL,"").replace(/\s+/g," ").trim()}var DL=/\u001B\][\s\S]*?(?:\u0007|\u001B\\|\u009C)|\u001B[PX^_][\s\S]*?(?:\u0007|\u001B\\|\u009C)|\u001B[@-OQ-WY-Z\\`6-9=]|[\u001B\u009B][[\]()#;?]*(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]/g;function LL(e){let t=e.match(/^.*?(?<![A-Za-z]\.[A-Za-z])[.!?](?=\s|$)/);return t?t[0]:e}function fS(e,t){let n=[...e];return n.length<=t?e:n.slice(0,t-1).join("")+"\u2026"}var Ja={stream:process.stdout,hideCursor:!1,discardStdin:!1};function qd(e,t){if(t?.getRatio()!==void 0)return t.getRatio();let n=e.turnTokens[e.turnTokens.length-1];return n?(n.input+n.output+n.cache)/ot(e.model):0}function As(e,t){let n=qd(e,t),r=ot(e.model),o,s=t?.getDetail();if(s!==void 0)o=s.used;else{let a=e.turnTokens[e.turnTokens.length-1];a&&(o=a.input+a.output+a.cache)}let i;if(e.turnTokens.length>=2){let a=e.turnTokens.map(c=>(c.input+c.output+c.cache)/r),l=pS(a,5);l.length>0&&(i=l)}return{model:e.model,cost:e.totalCostUsd,tokens:e.totalTokens,contextPct:n,contextLimit:r,contextUsedTokens:o,contextSparkline:i,planMode:e.planMode,...e.cwd!==void 0?{cwd:e.cwd}:{}}}var NL={name:"/exit",aliases:["/quit"],summary:"Exit the session",hint:"When you want to tear down the REPL \u2014 Ctrl+D on an empty prompt does the same.",async handler(){return"exit"}},jL={name:"/clear",summary:"Clear conversation history",hint:"When the current thread has drifted off-topic or you want a clean slate without restarting the session.",async handler(e){try{await e.session.current.reset(),e.ui.clearScreen(),Yw(e.stats),e.ledger?.clear(),e.out.success("Conversation history cleared.")}catch(t){e.out.error(t instanceof Error?t.message:"Unknown error")}return"continue"}},UL={name:"/compact",summary:"Compact history (summarize older messages)",hint:"When context is filling up but you want to keep the thread \u2014 summarizes old turns and keeps the recent ones intact.",async handler(e){let t=FL({text:m.meta("Summarizing earlier turns..."),...Ja}).start();try{let n=await e.session.current.compact();if(t.stop(),n.compacted){let r=n.tokensSavedEstimate?` (~${n.tokensSavedEstimate} input tokens saved)`:"";e.out.success(`Compacted ${n.messagesBefore} \u2192 ${n.messagesAfter} messages${r}.`)}else{let r=n.reason??"unknown";r==="aborted"?e.out.info("Compaction cancelled."):r.startsWith("summarization-failed")?e.out.error(`Compaction failed: ${r}. History unchanged.`):r==="nothing-to-summarize"?e.out.info("Nothing to compact \u2014 all history is within the keep window."):r==="not-supported"?e.out.warn("Compaction is not supported for this model or provider \u2014 use a Claude model to enable /compact."):e.out.info(`Nothing to compact (${r}).`)}}catch(n){t.stop(),e.out.error(n instanceof Error?n.message:"Unknown error")}return"continue"}},BL={name:"/help",summary:"Show this help",hint:"When you want the full command list with usage strings \u2014 broader than this inline dropdown.",async handler(e){let t=Xe(),n=t.reduce((r,o)=>Math.max(r,o.name.length),0)+2;e.out.line(),e.out.line(m.bold(m.brand("Commands"))),e.out.line(ge());for(let r of t){let o=r.usage??r.name,s=" ".repeat(Math.max(0,n-o.length));e.out.line(` ${m.warning(o)}${s} ${m.dim(r.summary)}`)}return e.out.line(),e.out.line(m.dim(" Tip: Ctrl+C interrupts a running turn; a second press exits.")),e.out.line(),"continue"}},gS=[NL,jL,UL,BL];function Jd(e,t=30){return!e||e.length===0?m.dim("(none)"):e.length<=t?e.join(", "):`${e.slice(0,t).join(", ")}, ${m.dim(`+${e.length-t} more`)}`}function yt(e,t){return` ${m.label(e.padEnd(16))} ${t}`}function Va(e){let t=[];t.push(" "+ge("Session Debug")),e.sessionId&&t.push(yt("session",e.sessionId)),e.model&&t.push(yt("model",e.model)),e.permissionMode&&t.push(yt("permission",e.permissionMode)),e.cwd&&t.push(yt("cwd",e.cwd)),e.claudeCodeVersion&&t.push(yt("sdk",`v${e.claudeCodeVersion}`)),e.apiKeySource&&t.push(yt("api key",e.apiKeySource)),e.outputStyle&&t.push(yt("output style",e.outputStyle));let n=e.tools?.length??0;t.push(yt(`tools (${n})`,Jd(e.tools)));let r=e.mcpServers??[],o=r.length?r.map(c=>`${c.name}[${c.status}]`).join(", "):m.dim("(none)");t.push(yt(`mcp (${r.length})`,o));let s=e.skills?.length??0;t.push(yt(`skills (${s})`,Jd(e.skills)));let i=e.plugins?.length??0,a=i?(e.plugins??[]).map(c=>c.name).join(", "):m.dim("(none)");t.push(yt(`plugins (${i})`,a));let l=e.slashCommands?.length??0;return t.push(yt(`slash (${l})`,Jd(e.slashCommands))),t.push(" "+ge()),t.join(`
|
|
2011
|
-
`)}var Xd=["opus","opus_1m","sonnet","sonnet_1m","haiku"],GL={name:"/cost",summary:"Show total and per-turn cost",hint:"When you want a dollar breakdown of this session \u2014 total, average per turn, and the recent turn-by-turn series.",async handler(e){let{stats:t,out:n}=e;if(n.line(),n.line(m.bold("Session cost")),n.line(ge()),n.line(` total ${m.success(Le(t.totalCostUsd))}`),n.line(` turns ${m.meta(String(t.totalTurns))}`),t.totalTurns>0){let r=t.totalCostUsd/t.totalTurns;n.line(` avg/turn ${m.meta(Le(r))}`)}if(t.turnCosts.length>0){let r=t.turnCosts.slice(-5).map(Le).join(m.dim(" \xB7 "));n.line(` last 5 ${r}`)}return n.line(),"continue"}};function zL(e,t){let n=t.apiUsage,r=n?.input_tokens??0,o=n?.output_tokens??0,s=n?.cache_read_input_tokens??0,i=n?.cache_creation_input_tokens??0,a=r+o+s+i;e.line(),e.line(m.bold("Token usage")+m.dim(" (SDK breakdown)")),e.line(ge()),e.line(` total ${m.success(ee(t.totalTokens))} of ${m.meta(ee(t.maxTokens))} (${m.meta(`${Math.round(t.percentage*100)/100}%`)})`),t.autoCompactThreshold&&t.isAutoCompactEnabled&&e.line(` compact at ${m.meta(ee(t.autoCompactThreshold))}`),e.line(),e.line(m.dim(" Last turn (API):")),e.line(` input ${m.meta(ee(r))}`),e.line(` output ${m.meta(ee(o))}`),e.line(` cache read ${m.meta(ee(s))}`),e.line(` cache creat ${m.meta(ee(i))}`),e.line(` total ${m.meta(ee(a))}`);let l=t.categories??[];if(l.length>0){let p=[...l].sort((f,g)=>g.tokens-f.tokens).slice(0,5);e.line(),e.line(m.dim(" Top categories:"));for(let f of p)e.line(` ${m.warning(f.name.padEnd(18))} ${m.meta(ee(f.tokens))}`)}let c=t.systemTools??[],u=t.mcpTools??[];if(c.length>0||u.length>0){e.line();let p=c.reduce((g,h)=>g+h.tokens,0),f=u.reduce((g,h)=>g+h.tokens,0);c.length>0&&e.line(m.dim(` system tools ${c.length} tools, ${ee(p)} tokens`)),u.length>0&&e.line(m.dim(` MCP tools ${u.length} tools, ${ee(f)} tokens`))}let d=t.agents??[];if(d.length>0){let p=d.reduce((f,g)=>f+g.tokens,0);e.line(m.dim(` agents ${d.length} loaded, ${ee(p)} tokens`))}if(t.skills){let p=t.skills;e.line(m.dim(` skills ${p.includedSkills}/${p.totalSkills} included, ${ee(p.tokens)} tokens`))}if(t.slashCommands){let p=t.slashCommands;e.line(m.dim(` slash cmds ${p.includedCommands}/${p.totalCommands} included, ${ee(p.tokens)} tokens`))}e.line()}function qL(e,t){let n=t.turnTokens.reduce((c,u)=>c+u.input,0),r=t.turnTokens.reduce((c,u)=>c+u.output,0),o=t.turnTokens.reduce((c,u)=>c+u.cache,0),s=n+r,i=ot(t.model),a=n+r+o,l=Math.round(a/i*100);e.line(),e.line(m.bold("Token usage")+m.dim(" (local stats \u2014 SDK breakdown unavailable)")),e.line(ge()),e.line(` input ${m.meta(ee(n))}`),e.line(` output ${m.meta(ee(r))}`),e.line(` cache read ${m.meta(ee(o))}`),e.line(` total ${m.success(ee(s))}`),e.line(` context ${m.meta(`${l}% of ${ee(i)} (${t.model})`)}`),e.line()}var JL={name:"/tokens",aliases:["/ctx"],summary:"Show token usage (SDK breakdown with local-stats fallback)",hint:"When you want to know how full the context window is \u2014 input/output/cache breakdown plus % of the model's limit used.",async handler(e){try{let t=await e.session.current.getContextUsage();zL(e.out,t)}catch{qL(e.out,e.stats)}return"continue"}},VL={name:"/history",summary:"Show conversation history",async handler(e){let{stats:t,out:n}=e;return t.turns.length===0?(n.info("No turns yet in this session."),"continue"):(n.line(),n.line(m.bold(`Session history (${t.turns.length} turn${t.turns.length===1?"":"s"})`)),n.line(ge()),t.turns.forEach((r,o)=>{let s=m.meta(`#${o+1}`),i=r.user.length>100?r.user.slice(0,97)+"...":r.user,a=r.assistant.length>100?r.assistant.slice(0,97)+"...":r.assistant;n.line(` ${s} ${m.user("\u25B6")} ${i}`),n.line(` ${m.brand("\u25C6")} ${m.dim(a)}`)}),n.line(),"continue")}},YL={name:"/reset",summary:"Clear screen, history, and session stats",async handler(e){let{stats:t,ui:n,out:r}=e;try{await e.session.current.sendMessage("/clear")}catch{}return t.totalTurns=0,t.totalCostUsd=0,t.totalTokens=0,t.totalDurationMs=0,t.turnCosts.length=0,t.turnTokens.length=0,t.turns.length=0,t.sessionStartTime=Date.now(),n.clearScreen(),r.success("Session reset."),"continue"}},XL={name:"/model",usage:"/model <opus|opus_1m|sonnet|sonnet_1m|haiku|org/model>",summary:"Switch the active model mid-session",hint:"When you want to upgrade to opus for a hard problem or downshift to haiku for cheap iteration \u2014 context carries over. Also accepts full HuggingFace-style IDs (e.g. mlx-community/Qwen3-30B-A3B-4bit).",async handler(e,t){let n=t.trim().toLowerCase();if(!n)return e.out.info(`Current model: ${m.brand(e.stats.model)}`),e.out.line(m.dim(` Aliases: ${Xd.join(", ")} (or any org/model HF id)`)),"continue";let r=Xd.includes(n),o=Ee(n)==="openai-compatible";if(!r&&!o)return e.out.warn(`Unknown model: ${n}. Aliases: ${Xd.join(", ")} (or org/model for local/OpenAI-compatible)`),"continue";try{await e.session.current.setModel(n),e.stats.model=n,e.ui.repaintStatusLine(),e.out.success(`Model switched to ${m.brand(n)}`)}catch(s){e.out.error(`Failed to switch model: ${s instanceof Error?s.message:String(s)}`)}return"continue"}},ZL={name:"/tools",summary:"List tools available to the session",async handler(e){try{let n=(await e.session.current.waitForInitialization()).tools??[];if(n.length===0)return e.out.info("No tools reported by the session."),"continue";e.out.line(),e.out.line(m.bold(`Tools (${n.length})`)),e.out.line(ge());let r=3,o=Math.ceil(n.length/r),s=Math.max(...n.map(i=>i.length))+2;for(let i=0;i<o;i++){let a=[];for(let l=0;l<r;l++){let c=l*o+i;c<n.length&&a.push(n[c].padEnd(s))}e.out.line(" "+a.join(""))}e.out.line()}catch(t){e.out.error(`Could not read session tools: ${t instanceof Error?t.message:String(t)}`)}return"continue"}},QL={name:"/mcp",summary:'List MCP servers connected to the session ("/mcp auth" to surface pending OAuth URLs)',async handler(e,t){let n=(t??"").trim().toLowerCase();if(n==="auth"){try{let{readOauthPending:r}=await Promise.resolve().then(()=>(Za(),TS)),o=r();if(Object.keys(o).length===0)return e.out.info("No MCP servers are waiting for OAuth."),"continue";e.out.line(),e.out.line(m.bold(`MCP OAuth pending (${Object.keys(o).length})`)),e.out.line(ge());for(let[s,i]of Object.entries(o)){let a=Date.now()-i.timestamp,l=Math.round(a/6e4);e.out.line(` ${m.warning("\u25CF")} ${s} ${m.dim(`(${l}m ago)`)}`),e.out.line(` ${m.info(i.authorizationUrl)}`)}e.out.line(),e.out.line(m.dim(" Open each URL in a browser. After authorizing, paste the code with:")),e.out.line(m.dim(" /mcp auth complete <serverName> <code>")),e.out.line()}catch(r){e.out.error(`Could not read OAuth state: ${r instanceof Error?r.message:String(r)}`)}return"continue"}if(n.startsWith("auth complete ")){let r=(t??"").trim(),o=r.slice(r.toLowerCase().indexOf("auth complete ")+14).trim(),s=o.indexOf(" ");if(s===-1||o.slice(0,s).length===0||o.slice(s+1).trim().length===0)return e.out.error("Usage: /mcp auth complete <serverName> <code>"),"continue";let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(!e.mcpManager)return e.out.error("No MCP manager available in this session. Make sure an mcp.json config is present and at least one server is enabled."),"continue";try{e.out.info(`Completing OAuth for "${i}"\u2026`),await e.mcpManager.completeAuth(i,a),e.out.success(`OAuth complete for "${i}" \u2014 server is now connected.`)}catch(l){e.out.error(`OAuth completion failed for "${i}": ${l instanceof Error?l.message:String(l)}`)}return"continue"}if(n!==""&&n!=="auth")return e.out.error(`Unknown /mcp subcommand: "${n}". Try: /mcp, /mcp auth, /mcp auth complete <server> <code>.`),"continue";try{let o=(await e.session.current.waitForInitialization()).mcpServers??[];if(o.length===0)return e.out.info("No MCP servers connected."),"continue";e.out.line(),e.out.line(m.bold(`MCP servers (${o.length})`)),e.out.line(ge());let s=0;for(let i of o){let a=typeof i=="string"?i:i.name??JSON.stringify(i),l=typeof i=="object"&&i!==null&&"status"in i?String(i.status):"",c=l==="connected"?m.success("\u25CF"):m.warning("\u25CF");e.out.line(` ${c} ${a}${l?m.dim(` (${l})`):""}`),l==="oauth_pending"&&s++}e.out.line(),s>0&&(e.out.line(m.dim(` ${s} server(s) need OAuth \u2014 run "/mcp auth" to see authorization URLs.`)),e.out.line())}catch(r){e.out.error(`Could not read MCP servers: ${r instanceof Error?r.message:String(r)}`)}return"continue"}},eF={name:"/limits",summary:"Show known per-model context-window limits",async handler(e){e.out.line(),e.out.line(m.bold("Context-window limits")),e.out.line(ge());for(let[t,n]of Object.entries(as)){let r=t===e.stats.model?m.brand(" \u2190 active"):"";e.out.line(` ${m.warning(t.padEnd(12))} ${m.meta(ee(n))}${r}`)}return e.out.line(),"continue"}},tF={name:"/debug",summary:"Show SDK session metadata (tools, MCP, skills, plugins, etc.)",hint:"When something feels broken and you want to inspect what the session actually loaded \u2014 tools, MCP servers, plugins, system prompt source.",async handler(e){try{let t=await e.session.current.waitForInitialization();e.out.line(),e.out.line(Va(t)),e.out.line()}catch(t){e.out.error(`Could not read session metadata: ${t instanceof Error?t.message:String(t)}`)}return"continue"}},ES=[GL,JL,VL,YL,XL,ZL,QL,eF,tF];var Zd=!1;async function xt(e,t,n={}){let r=e.stats.planMode,o=t!==void 0?t:!r;try{if(await e.session.current.setPermissionMode(o?"plan":"default"),e.stats.planMode=o,e.ui.repaintStatusLine(),o){let s=Zd?"":m.dim(" Shift+Tab or /plan to exit.");Zd||(Zd=!0),e.out.success(m.warning("\u25CF plan mode ON")+m.dim(" \u2014 write_file, edit_file, and write-intent bash are refused.")+s)}else n.closureSummarySkipped?e.out.success(m.success("\u25CB plan mode OFF")+m.dim(" \u2014 force-exit (closure summary skipped). Default permissions restored.")):e.out.success(m.success("\u25CB plan mode OFF")+m.dim(" \u2014 default permissions restored"))}catch(s){e.out.error(`Could not toggle plan mode: ${s instanceof Error?s.message:String(s)}`)}}async function xS(e){e.stats.pendingPlanExit&&(await xt(e,!1),e.stats.planMode||(e.stats.pendingPlanExit=!1))}var nF=["You are about to exit plan mode. Before I flip permissions back to default on the next turn, emit your final plan in three sections:",""," - **Chosen approach** \u2014 the plan you recommend, in one to three sentences."," - **Risks named** \u2014 the concrete failure modes, constraints, or unknowns this plan does not eliminate."," - **Alternatives considered** \u2014 the options you weighed and why you rejected them.","","This is the record. Be specific. Do not propose write actions in this turn \u2014 writes are still refused until the mode flips."].join(`
|
|
2010
|
+
`),c=d.length}return new Promise(d=>{process.stdin.setRawMode(!0),Gd.emitKeypressEvents(process.stdin);let p=(g,h)=>{if(h)if(h.name==="up"||h.sequence==="\x1B[A")r>0&&(r--,r<o&&(o=r),u());else if(h.name==="down"||h.sequence==="\x1B[B"){if(r<e.length-1){r++;let{end:b}=i();r>=b&&o++,u()}}else h.name==="space"?(s.has(r)?s.delete(r):s.add(r),u()):h.name==="return"||h.name==="enter"?(f(),d([...s].sort((b,y)=>b-y))):(h.name==="escape"||h.ctrl&&h.name==="c")&&(f(),d(":cancel"))};function f(){process.stdin.removeListener("keypress",p);try{process.stdin.setRawMode(!1)}catch{}}process.stdin.on("keypress",p)})}var ho={action:"decline"},oe={action:"cancel"},TL={action:"accept"};function EL(e){let t=e.properties,n={},r=0,o=!1;if(typeof t=="object"&&t!==null){let a=0;for(let[l,c]of Object.entries(t))if(!Hd.has(l)){if(r+=1,a>=Wd){o=!0;continue}n[l]=c,a+=1}}let s=e.required,i=new Set(Array.isArray(s)?s.slice(0,Wd*2).filter(a=>typeof a=="string").filter(a=>!Hd.has(a)):[]);return{properties:n,required:i,fieldsTruncated:o,originalFieldCount:r}}function xL(e,t){e.line(),e.line(m.warning("\u26A0 MCP form elicitation")),e.line(m.dim(" server: ")+m.bold(ce(t.serverName,64))),e.line(m.dim(" message: ")+ce(t.message,256)),t.elicitationId&&e.line(m.dim(" id: ")+ce(t.elicitationId,64)),e.line(m.dim(" Type :decline or :cancel at any prompt to exit.")),e.line()}async function RL(e,t,n,r,o,s){if(s.aborted)return{tag:"cancel"};let i=ce(t.description??t.title??e),a=ce(t.type??"string",32),l=ce(e,64),c;if(t.enum!==void 0){let d=t.enum.slice(0,Ha).map(f=>ce(String(f),32)).join("|"),p=t.enum.length>Ha?"|\u2026":"";c=` (enum: ${d}${p})`}else a==="boolean"?c=" (boolean: y/n)":a==="number"||a==="integer"?c=` (${a})`:a==="string"?c=" (string)":(c=` (${a} \u2014 treated as string)`,o.line(m.warning(` \u26A0 Unknown field type '${a}' for '${l}' \u2014 collecting as string.`)));let u=n?"":m.dim(" [optional, enter to skip]");for(o.line(m.dim(` [${l}]`)+m.dim(` ${i}`)+m.dim(c)+u),t.enum!==void 0&&t.enum.length>Bd&&o.line(m.warning(` \u26A0 Field '${l}' has ${t.enum.length} enum values; only the first ${Bd} are valid for input.`));;){let d;try{d=await r(m.dim(" > "))}catch{return{tag:"cancel"}}if(s.aborted)return{tag:"cancel"};let p=d.trim();if(p===":cancel")return{tag:"cancel"};if(p===":decline")return{tag:"decline"};if(p===""){if(n){o.line(m.warning(" (required \u2014 cannot be skipped)"));continue}return{tag:"value",value:t.default}}let f;if(a==="boolean"){let g=p.toLowerCase();if(g==="y"||g==="yes"||g==="true"||g==="1")f=!0;else if(g==="n"||g==="no"||g==="false"||g==="0")f=!1;else{o.line(m.warning(" Invalid boolean \u2014 enter y/yes/true/1 or n/no/false/0."));continue}}else if(a==="number"){let g=Number(p);if(!isFinite(g)){o.line(m.warning(" Invalid number \u2014 enter a numeric value."));continue}f=g}else if(a==="integer"){let g=parseInt(p,10);if(!isFinite(g)||String(g)!==p.replace(/\.0+$/,"")){o.line(m.warning(" Invalid integer \u2014 enter a whole number."));continue}f=g}else f=p;if(t.enum!==void 0){let g=t.enum.slice(0,Bd),h=!1;for(let b of g)if(String(b)===String(f)){h=!0;break}if(!h){let b=ce(String(f),64),y=g.slice(0,Ha).map(k=>ce(String(k),32)).join(", "),w=g.length>Ha?", \u2026":"";o.line(m.warning(` '${b}' is not a valid choice. Valid: ${y}${w}`));continue}}return{tag:"value",value:f}}}function AL(e,t){e.line(),e.line(m.warning("\u26A0 MCP elicitation")),e.line(m.dim(" server: ")+m.bold(ce(t.serverName,64))),e.line(m.dim(" message: ")+ce(t.message,256)),t.url&&e.line(m.dim(" url: ")+m.brand(ce(t.url,512))),t.elicitationId&&e.line(m.dim(" id: ")+ce(t.elicitationId,64)),e.line()}var ar={action:"skip"};function Kd(e){let t=[];return t.push(m.warning(" \u{1F4AC} Agent question")),t.push(m.bold(" ? "+ce(e.message,512))),e.context&&t.push(m.dim(" "+ce(e.context,512))),t.push(""),t}async function _L(e,t,n,r){let o=Kd(t),s=t.allowSkip===!0;if(e==="number"){let u=t.min,d=t.max,f=`enter to submit \xB7 esc to cancel${u!==void 0&&d!==void 0?` [${u}\u2013${d}]`:u!==void 0?` [\u2265${u}]`:d!==void 0?` [\u2264${d}]`:""}`,h=await n({header:o,help:f,validate:y=>{let w=y.trim();if(w==="")return s?null:"Please enter a number (or esc to cancel).";let k=Number(w);return Number.isFinite(k)?u!==void 0&&k<u?`Value must be \u2265 ${u}.`:d!==void 0&&k>d?`Value must be \u2264 ${d}.`:null:"Please enter a valid number."},signal:r});if(h===null)return null;let b=h.trim();return b===""&&s?{tag:"skip"}:{tag:"number",value:Number(b)}}let i=t.minLength,a=t.maxLength,c=await n({header:o,validate:u=>u===""?s?null:"Please enter a response (or esc to cancel).":i!==void 0&&u.length<i?`Response must be at least ${i} characters.`:a!==void 0&&u.length>a?`Response must be at most ${a} characters.`:null,signal:r});return c===null?null:c===""&&s?{tag:"skip"}:{tag:"text",value:c}}async function CL(e,t,n){if(n.aborted)return ho;let{readLine:r,writer:o,pendingCount:s,pickFromList:i,readTextOverlay:a}=t,l=e.type??"text",c=s();if(c>1&&o.line(m.dim(` [${c} questions queued]`)),(l==="choice"||l==="multi_choice")&&i&&(e.choices?.length??0)>0){let p=(e.choices??[]).map(h=>ce(h,128)),f;try{f=await i({header:Kd(e),options:p,multi:l==="multi_choice",signal:n})}catch{return oe}if(n.aborted||f===null)return oe;if(f.length===0)return e.allowSkip?ar:oe;let g=f.length===1?ce(f[0]??"",128):f.map(h=>ce(h,128)).join(", ");return o.line(m.dim(" \u2713 ")+m.brand(g)),l==="choice"?{action:"accept",content:{value:f[0]}}:{action:"accept",content:{value:[...f]}}}if(l==="confirm"&&i){let f=e.questionDefault!==!1?["Yes","No"]:["No","Yes"],g;try{g=await i({header:Kd(e),options:f,multi:!1,signal:n})}catch{return oe}if(n.aborted||g===null)return oe;let h=g[0];if(h===void 0)return oe;let b=h==="Yes";return o.line(m.dim(" \u2713 ")+(b?m.success("Yes"):m.error("No"))),{action:"accept",content:{value:b}}}if((l==="text"||l==="number")&&a){let p=await _L(l,e,a,n);if(p===null)return oe;if(p.tag==="skip")return ar;let f=p.tag==="text"?ce(p.value,256):String(p.value);return o.line(m.dim(" \u2713 ")+m.brand(f)),{action:"accept",content:{value:(p.tag==="text",p.value)}}}if(o.line(),o.line(m.warning("\u{1F4AC} Agent question")),e.context&&o.line(m.dim(" context: ")+ce(e.context,512)),o.line(m.bold(" "+ce(e.message,512))),o.line(m.dim(" Type :cancel to skip this question.")),o.line(),l==="confirm"){o.line("\x07");let p=e.questionDefault===!0?"Y/n":"y/N";for(;;){if(n.aborted)return oe;let f;try{f=(await r(m.dim(` Continue? [${p}] `))).trim().toLowerCase()}catch{return oe}if(n.aborted||f===":cancel")return oe;if(f==="")return{action:"accept",content:{value:e.questionDefault===!0}};if(f==="y"||f==="yes")return{action:"accept",content:{value:!0}};if(f==="n"||f==="no")return{action:"accept",content:{value:!1}};o.line(m.warning(" Please enter y or n."))}}if(l==="choice"){o.line("\x07");let p=e.choices??[],f=await kL(p,n);if(f!==null){if(f===":cancel")return oe;let g=p[f];return g!==void 0?(o.line(m.dim(` Selected: ${ce(g,128)}`)),{action:"accept",content:{value:g}}):oe}for(p.forEach((g,h)=>{o.line(` ${h+1}. ${ce(g,128)}`)});;){if(n.aborted)return oe;let g;try{g=(await r(m.dim(" Enter number: "))).trim()}catch{return oe}if(n.aborted||g===":cancel")return oe;if(g===""&&e.allowSkip)return ar;let h=parseInt(g,10);if(!isFinite(h)||String(h)!==g||h<1||h>p.length){o.line(m.warning(` Please enter a number between 1 and ${p.length}.`));continue}return{action:"accept",content:{value:p[h-1]}}}}if(l==="multi_choice"){let p=e.choices??[],f=await vL(p,n);if(f!==null){if(f===":cancel")return oe;if(f.length===0&&e.allowSkip)return ar;if(f.length>0){let g=f.map(h=>p[h]);return o.line(m.dim(` Selected: ${g.map(h=>ce(h,64)).join(", ")}`)),{action:"accept",content:{value:g}}}}for(p.forEach((g,h)=>{o.line(` ${h+1}. ${ce(g,128)}`)});;){if(n.aborted)return oe;let g;try{g=(await r(m.dim(" Enter numbers (comma-separated): "))).trim()}catch{return oe}if(n.aborted||g===":cancel")return oe;if(g===""&&e.allowSkip)return ar;if(g===""){o.line(m.warning(" Please enter at least one selection."));continue}let h=g.split(",").map(w=>w.trim()),b=[],y=!0;for(let w of h){let k=parseInt(w,10);if(!isFinite(k)||String(k)!==w||k<1||k>p.length){o.line(m.warning(` Invalid selection "${ce(w,32)}". Enter numbers between 1 and ${p.length}.`)),y=!1;break}b.push(p[k-1])}if(y)return{action:"accept",content:{value:b}}}}if(l==="number"){let p=e.min,f=e.max,g=p!==void 0&&f!==void 0?` [${p}\u2013${f}]`:p!==void 0?` [\u2265${p}]`:f!==void 0?` [\u2264${f}]`:"";for(;;){if(n.aborted)return oe;let h;try{h=(await r(m.dim(` Enter a number${g}: `))).trim()}catch{return oe}if(n.aborted||h===":cancel")return oe;if(h===""&&e.allowSkip)return ar;if(h===""&&!e.allowSkip){o.line(m.warning(" Please enter a number (or :cancel to skip)."));continue}let b=Number(h);if(!isFinite(b)){o.line(m.warning(" Please enter a valid number."));continue}if(p!==void 0&&b<p){o.line(m.warning(` Value must be \u2265 ${p}.`));continue}if(f!==void 0&&b>f){o.line(m.warning(` Value must be \u2264 ${f}.`));continue}return{action:"accept",content:{value:b}}}}let u=e.minLength,d=e.maxLength;for(;;){if(n.aborted)return oe;let p;try{p=(await r(m.dim(" > "))).trim()}catch{return oe}if(n.aborted||p===":cancel")return oe;if(p===""&&e.allowSkip)return ar;if(p===""){o.line(m.warning(" Please enter a response (or type :cancel to skip)."));continue}if(u!==void 0&&p.length<u){o.line(m.warning(` Response must be at least ${u} characters.`));continue}if(d!==void 0&&p.length>d){o.line(m.warning(` Response must be at most ${d} characters.`));continue}return{action:"accept",content:{value:p}}}}function Ka(e){return async(t,{signal:n})=>{if(n.aborted)return ho;Wa(process.stdout),e.suspendInput?.();try{if(t.origin==="agent")return await CL(t,e,n);if(t.mode==="form"){let o=t.requestedSchema,{properties:s,required:i,fieldsTruncated:a,originalFieldCount:l}=typeof o=="object"&&o!==null?EL(o):{properties:{},required:new Set,fieldsTruncated:!1,originalFieldCount:0};xL(e.writer,t),a&&e.writer.line(m.warning(` \u26A0 Schema has ${l} fields; only the first ${Wd} will be prompted (server may be malformed or compromised).`));let c=Object.create(null);if(Object.keys(s).length===0)return e.writer.line(m.warning(" \u26A0 Form schema has no usable fields \u2014 declining.")),ho;for(let u of i)if(!(u in s))return e.writer.line(m.warning(` \u26A0 Required field '${ce(u,64)}' has no schema entry \u2014 declining.`)),ho;for(let[u,d]of Object.entries(s)){if(n.aborted)return oe;let p=await RL(u,d,i.has(u),e.readLine,e.writer,n);if(p.tag==="cancel")return oe;if(p.tag==="decline")return ho;p.value!==void 0&&!Hd.has(u)&&(c[u]=p.value)}return{action:"accept",content:{...c}}}AL(e.writer,t);let r=(await e.readLine(m.dim("Continue? [y/N] "))).trim().toLowerCase();return r===""?oe:r==="y"||r==="yes"?TL:ho}finally{e.resumeInput?.()}}}function aS(e){let t=Math.max(0,Math.min(1,e.ratio)),n=t>.8?m.error:t>.5?m.warning:m.meta,r=20,o=Math.round(t*r),s=r-o,i="["+"\u2588".repeat(o)+"\u2591".repeat(s)+"]",a=Math.round(t*100)+"%",l="";e.used!==void 0&&e.limit!==void 0&&(l=te(e.used)+"/"+te(e.limit));let c=l?`${i} ${a} ${l}`:`${i} ${a}`,u=`${i} ${a}`,d=`ctx ${a}`,p=e.sparkline?m.meta(e.sparkline)+" ":"",f=e.sparkline?z(e.sparkline)+1:0,g=Math.max(0,e.width-f);if(z(c)<=g&&g>90)return p+n(c);if(z(u)<=g&&g>32)return p+n(u);if(z(d)<=g)return p+n(d);if(e.width>0){let h=p+n(d);return ue(h,e.width)}return n(a)}var Ga=class{stream;force;throttleMs;started=!1;lastRepaint=0;lastFields=null;resizeUnsub=null;lastPaintedRow=null;extraRows=0;constructor(t={}){this.stream=t.stream??process.stdout,this.force=t.force??!1,this.throttleMs=t.throttleMs??100}get enabled(){return this.force||!!this.stream.isTTY}start(){if(this.started||!this.enabled)return;this.started=!0,this.lastRepaint=0;let t=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.resizeUnsub===null&&(this.resizeUnsub=Ge.subscribe(()=>{this.onResize()}))}onResize(){if(!this.started||!this.enabled)return;let t=this.currentRows();this.stream.write("\x1B[s"),this.lastPaintedRow!==null&&this.lastPaintedRow!==this.paintRow(t)&&(this.stream.write(`\x1B[${this.lastPaintedRow};1H`),this.stream.write("\x1B[2K")),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.flush()}repaint(t){if(!this.enabled||!this.started){this.lastFields=t;return}let n=Date.now();if(n-this.lastRepaint<this.throttleMs){this.lastFields=t;return}this.lastRepaint=n,this.lastFields=t;let r=this.currentRows();this.stream.write("\x1B[s"),this.stream.write(`\x1B[${this.paintRow(r)};1H`),this.stream.write("\x1B[2K"),this.stream.write(this.formatLine(t)),this.stream.write("\x1B[u"),this.lastPaintedRow=this.paintRow(r)}flush(){this.lastRepaint=0,this.lastFields&&this.repaint(this.lastFields)}setExtraRows(t){if(this.extraRows=t,this.started&&this.enabled){let n=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(n),this.stream.write("\x1B[u"),this.flush()}}getExtraRows(){return this.extraRows}rearm(){if(!this.started||!this.enabled)return;let t=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(t),this.stream.write("\x1B[u"),this.flush()}withFullScrollRegion(t){if(!this.started||!this.enabled)return t();this.stream.write("\x1B[s"),this.stream.write("\x1B[r"),this.stream.write("\x1B[u");try{return t()}finally{let n=this.currentRows();this.stream.write("\x1B[s"),this.writeScrollRegion(n),this.stream.write("\x1B[u"),this.flush()}}stop(){if(this.resizeUnsub!==null&&(this.resizeUnsub(),this.resizeUnsub=null),!this.started||!this.enabled){this.started=!1;return}let t=this.currentRows();this.stream.write("\x1B[s"),this.stream.write(`\x1B[${this.lastPaintedRow??this.paintRow(t)};1H`),this.stream.write("\x1B[2K"),this.stream.write("\x1B[r"),this.stream.write("\x1B[u"),this.started=!1,this.lastRepaint=0,this.lastPaintedRow=null}formatLine(t){let n=[],r=Math.max(4,(this.stream.columns??80)-2);if(t.cwd){let a=Math.max(8,Math.floor(r*.4)),l=Ba(t.cwd,{maxWidth:a});l&&n.push({text:m.dim(l)})}if(n.push({text:m.brand(t.model)}),t.planMode&&n.push({text:m.warning("\u25CF plan")}),t.contextPct!==void 0){let a=aS({ratio:t.contextPct,used:t.contextUsedTokens,limit:t.contextLimit,sparkline:t.contextSparkline,width:r});n.push({text:a,droppablePriority:1})}t.cost!==void 0&&n.push({text:m.meta(`$${t.cost.toFixed(2)}`),droppablePriority:2}),t.tokens!==void 0&&n.push({text:m.meta(`${IL(t.tokens)} tok`),droppablePriority:3});let o=m.dim(" \xB7 "),s=n.map(a=>a.text).join(o);if(z(s)<=r)return s;let i=n.filter(a=>a.droppablePriority!==void 0);for(;i.length>0&&z(s)>r;){let a=Math.max(...i.map(l=>l.droppablePriority));n=n.filter(l=>l.droppablePriority===void 0||l.droppablePriority!==a),s=n.map(l=>l.text).join(o),i=n.filter(l=>l.droppablePriority!==void 0)}return ue(s,r)}currentRows(){let t=this.stream.rows;return typeof t=="number"&&t>0?t:24}paintRow(t){return t>1?t:1}writeScrollRegion(t){let n=1+this.extraRows;if(t>n){this.stream.write(`\x1B[1;${t-n}r`);return}this.stream.write("\x1B[r")}};function IL(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`}var at=new Map,lr=new Map;function de(e){if(at.has(e.name))throw new Error(`Slash command already registered: ${e.name}`);at.set(e.name,e);for(let t of e.aliases??[]){if(lr.has(t)||at.has(t))throw new Error(`Slash alias collides: ${t}`);lr.set(t,e.name)}}function On(e){if(at.has(e.name)){for(let[t,n]of lr.entries())n===e.name&&lr.delete(t);at.delete(e.name)}de(e)}function lS(e){at.has(e.name)||de(e)}function cS(){at.clear(),lr.clear()}function Xe(){return[...at.values()].sort((e,t)=>e.name.localeCompare(t.name))}function uS(){let e=[];for(let[t,n]of lr.entries()){let r=at.get(n);r&&e.push({alias:t,canonical:n,summary:r.summary})}return e.sort((t,n)=>t.alias.localeCompare(n.alias))}function PL(e){if(at.has(e))return at.get(e);let t=lr.get(e);return t?at.get(t):void 0}function ML(e,t){let n=Array.from({length:e.length+1},()=>new Array(t.length+1).fill(0));for(let r=0;r<=e.length;r++)n[r][0]=r;for(let r=0;r<=t.length;r++)n[0][r]=r;for(let r=1;r<=e.length;r++)for(let o=1;o<=t.length;o++){let s=e[r-1]===t[o-1]?0:1;n[r][o]=Math.min(n[r-1][o]+1,n[r][o-1]+1,n[r-1][o-1]+s)}return n[e.length][t.length]}function OL(e,t=3){let n;for(let r of at.keys()){let o=ML(e,r);o<=t&&(n===void 0||o<n.dist)&&(n={name:r,dist:o})}return n?.name}function zd(e){let t=e.trim();if(!t.startsWith("/"))return null;let n=t.indexOf(" ");return n===-1?{name:t,args:""}:{name:t.slice(0,n),args:t.slice(n+1).trim()}}async function dS(e,t,n){let r=zd(e);if(r===null)return{handled:!1};let o=PL(r.name);if(!o){let a=OL(r.name);return a?t.out.warn(`Unknown command: ${r.name} (did you mean ${a}?)`):t.out.warn(`Unknown command: ${r.name} (type /help for commands)`),{handled:!0,result:"continue"}}let s=n??[];s.length>0&&o.acceptsAttachments!==!0&&t.out.warn(`\u26A0 Image attachments are ignored by ${r.name} (images only reach the model on skill commands like /forge, /mint).`);let i=await o.handler(t,r.args,o.acceptsAttachments===!0?s:void 0);return i==="forward"?{handled:!1}:{handled:!0,result:i}}import FL from"ora";function pS(e,t=5){if(e.length===0)return"";let n=e.slice(-t),r=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"];return n.map(o=>{let s=Math.max(0,Math.min(1,o)),i=Math.min(7,Math.floor(s*8));return r[i]}).join("")}function za(e,t,n){e.totalTurns=t.totalTurns,e.totalCostUsd=t.totalCostUsd,e.totalTokens=t.totalTokens,e.totalDurationMs=t.totalDurationMs,e.turns=[...t.turns],e.sessionId=t.sessionId??n,e.model=t.model,e.sessionStartTime=t.startedAt??Date.now()}function qa(e,t){let n=e.turns;if(n.length===0)return;let r=n[n.length-1];if(!r)return;let o=fS(mS(r.user),80),s=fS(LL(mS(r.assistant)),120);o.length>0&&t.fn(m.dim(` Last: ${o}`)),s.length>0&&t.fn(m.dim(` \u21B3 ${s}`)),t.fn(m.dim(" \u21AA /history for full review"))}function mS(e){return e.replace(DL,"").replace(/\s+/g," ").trim()}var DL=/\u001B\][\s\S]*?(?:\u0007|\u001B\\|\u009C)|\u001B[PX^_][\s\S]*?(?:\u0007|\u001B\\|\u009C)|\u001B[@-OQ-WY-Z\\`6-9=]|[\u001B\u009B][[\]()#;?]*(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]/g;function LL(e){let t=e.match(/^.*?(?<![A-Za-z]\.[A-Za-z])[.!?](?=\s|$)/);return t?t[0]:e}function fS(e,t){let n=[...e];return n.length<=t?e:n.slice(0,t-1).join("")+"\u2026"}var Ja={stream:process.stdout,hideCursor:!1,discardStdin:!1};function qd(e,t){if(t?.getRatio()!==void 0)return t.getRatio();let n=e.turnTokens[e.turnTokens.length-1];return n?(n.input+n.output+n.cache)/ot(e.model):0}function As(e,t){let n=qd(e,t),r=ot(e.model),o,s=t?.getDetail();if(s!==void 0)o=s.used;else{let a=e.turnTokens[e.turnTokens.length-1];a&&(o=a.input+a.output+a.cache)}let i;if(e.turnTokens.length>=2){let a=e.turnTokens.map(c=>(c.input+c.output+c.cache)/r),l=pS(a,5);l.length>0&&(i=l)}return{model:e.model,cost:e.totalCostUsd,tokens:e.totalTokens,contextPct:n,contextLimit:r,contextUsedTokens:o,contextSparkline:i,planMode:e.planMode,...e.cwd!==void 0?{cwd:e.cwd}:{}}}var NL={name:"/exit",aliases:["/quit"],summary:"Exit the session",hint:"When you want to tear down the REPL \u2014 Ctrl+D on an empty prompt does the same.",async handler(){return"exit"}},jL={name:"/clear",summary:"Clear conversation history",hint:"When the current thread has drifted off-topic or you want a clean slate without restarting the session.",async handler(e){try{await e.session.current.reset(),e.ui.clearScreen(),Yw(e.stats),e.ledger?.clear(),e.out.success("Conversation history cleared.")}catch(t){e.out.error(t instanceof Error?t.message:"Unknown error")}return"continue"}},UL={name:"/compact",summary:"Compact history (summarize older messages)",hint:"When context is filling up but you want to keep the thread \u2014 summarizes old turns and keeps the recent ones intact.",async handler(e){let t=FL({text:m.meta("Summarizing earlier turns..."),...Ja}).start();try{let n=await e.session.current.compact();if(t.stop(),n.compacted){let r=n.tokensSavedEstimate?` (~${n.tokensSavedEstimate} input tokens saved)`:"";e.out.success(`Compacted ${n.messagesBefore} \u2192 ${n.messagesAfter} messages${r}.`)}else{let r=n.reason??"unknown";r==="aborted"?e.out.info("Compaction cancelled."):r.startsWith("summarization-failed")?e.out.error(`Compaction failed: ${r}. History unchanged.`):r==="nothing-to-summarize"?e.out.info("Nothing to compact \u2014 all history is within the keep window."):r==="not-supported"?e.out.warn("Compaction is not supported for this model or provider \u2014 use a Claude model to enable /compact."):e.out.info(`Nothing to compact (${r}).`)}}catch(n){t.stop(),e.out.error(n instanceof Error?n.message:"Unknown error")}return"continue"}},BL={name:"/help",summary:"Show this help",hint:"When you want the full command list with usage strings \u2014 broader than this inline dropdown.",async handler(e){let t=Xe(),n=t.reduce((r,o)=>Math.max(r,o.name.length),0)+2;e.out.line(),e.out.line(m.bold(m.brand("Commands"))),e.out.line(ge());for(let r of t){let o=r.usage??r.name,s=" ".repeat(Math.max(0,n-o.length));e.out.line(` ${m.warning(o)}${s} ${m.dim(r.summary)}`)}return e.out.line(),e.out.line(m.dim(" Tip: Ctrl+C interrupts a running turn; a second press exits.")),e.out.line(),"continue"}},gS=[NL,jL,UL,BL];function Jd(e,t=30){return!e||e.length===0?m.dim("(none)"):e.length<=t?e.join(", "):`${e.slice(0,t).join(", ")}, ${m.dim(`+${e.length-t} more`)}`}function yt(e,t){return` ${m.label(e.padEnd(16))} ${t}`}function Va(e){let t=[];t.push(" "+ge("Session Debug")),e.sessionId&&t.push(yt("session",e.sessionId)),e.model&&t.push(yt("model",e.model)),e.permissionMode&&t.push(yt("permission",e.permissionMode)),e.cwd&&t.push(yt("cwd",e.cwd)),e.claudeCodeVersion&&t.push(yt("sdk",`v${e.claudeCodeVersion}`)),e.apiKeySource&&t.push(yt("api key",e.apiKeySource)),e.outputStyle&&t.push(yt("output style",e.outputStyle));let n=e.tools?.length??0;t.push(yt(`tools (${n})`,Jd(e.tools)));let r=e.mcpServers??[],o=r.length?r.map(c=>`${c.name}[${c.status}]`).join(", "):m.dim("(none)");t.push(yt(`mcp (${r.length})`,o));let s=e.skills?.length??0;t.push(yt(`skills (${s})`,Jd(e.skills)));let i=e.plugins?.length??0,a=i?(e.plugins??[]).map(c=>c.name).join(", "):m.dim("(none)");t.push(yt(`plugins (${i})`,a));let l=e.slashCommands?.length??0;return t.push(yt(`slash (${l})`,Jd(e.slashCommands))),t.push(" "+ge()),t.join(`
|
|
2011
|
+
`)}var Xd=["opus","opus_1m","sonnet","sonnet_1m","haiku"],GL={name:"/cost",summary:"Show total and per-turn cost",hint:"When you want a dollar breakdown of this session \u2014 total, average per turn, and the recent turn-by-turn series.",async handler(e){let{stats:t,out:n}=e;if(n.line(),n.line(m.bold("Session cost")),n.line(ge()),n.line(` total ${m.success(Le(t.totalCostUsd))}`),n.line(` turns ${m.meta(String(t.totalTurns))}`),t.totalTurns>0){let r=t.totalCostUsd/t.totalTurns;n.line(` avg/turn ${m.meta(Le(r))}`)}if(t.turnCosts.length>0){let r=t.turnCosts.slice(-5).map(Le).join(m.dim(" \xB7 "));n.line(` last 5 ${r}`)}return n.line(),"continue"}};function zL(e,t){let n=t.apiUsage,r=n?.input_tokens??0,o=n?.output_tokens??0,s=n?.cache_read_input_tokens??0,i=n?.cache_creation_input_tokens??0,a=r+o+s+i;e.line(),e.line(m.bold("Token usage")+m.dim(" (SDK breakdown)")),e.line(ge()),e.line(` total ${m.success(te(t.totalTokens))} of ${m.meta(te(t.maxTokens))} (${m.meta(`${Math.round(t.percentage*100)/100}%`)})`),t.autoCompactThreshold&&t.isAutoCompactEnabled&&e.line(` compact at ${m.meta(te(t.autoCompactThreshold))}`),e.line(),e.line(m.dim(" Last turn (API):")),e.line(` input ${m.meta(te(r))}`),e.line(` output ${m.meta(te(o))}`),e.line(` cache read ${m.meta(te(s))}`),e.line(` cache creat ${m.meta(te(i))}`),e.line(` total ${m.meta(te(a))}`);let l=t.categories??[];if(l.length>0){let p=[...l].sort((f,g)=>g.tokens-f.tokens).slice(0,5);e.line(),e.line(m.dim(" Top categories:"));for(let f of p)e.line(` ${m.warning(f.name.padEnd(18))} ${m.meta(te(f.tokens))}`)}let c=t.systemTools??[],u=t.mcpTools??[];if(c.length>0||u.length>0){e.line();let p=c.reduce((g,h)=>g+h.tokens,0),f=u.reduce((g,h)=>g+h.tokens,0);c.length>0&&e.line(m.dim(` system tools ${c.length} tools, ${te(p)} tokens`)),u.length>0&&e.line(m.dim(` MCP tools ${u.length} tools, ${te(f)} tokens`))}let d=t.agents??[];if(d.length>0){let p=d.reduce((f,g)=>f+g.tokens,0);e.line(m.dim(` agents ${d.length} loaded, ${te(p)} tokens`))}if(t.skills){let p=t.skills;e.line(m.dim(` skills ${p.includedSkills}/${p.totalSkills} included, ${te(p.tokens)} tokens`))}if(t.slashCommands){let p=t.slashCommands;e.line(m.dim(` slash cmds ${p.includedCommands}/${p.totalCommands} included, ${te(p.tokens)} tokens`))}e.line()}function qL(e,t){let n=t.turnTokens.reduce((c,u)=>c+u.input,0),r=t.turnTokens.reduce((c,u)=>c+u.output,0),o=t.turnTokens.reduce((c,u)=>c+u.cache,0),s=n+r,i=ot(t.model),a=n+r+o,l=Math.round(a/i*100);e.line(),e.line(m.bold("Token usage")+m.dim(" (local stats \u2014 SDK breakdown unavailable)")),e.line(ge()),e.line(` input ${m.meta(te(n))}`),e.line(` output ${m.meta(te(r))}`),e.line(` cache read ${m.meta(te(o))}`),e.line(` total ${m.success(te(s))}`),e.line(` context ${m.meta(`${l}% of ${te(i)} (${t.model})`)}`),e.line()}var JL={name:"/tokens",aliases:["/ctx"],summary:"Show token usage (SDK breakdown with local-stats fallback)",hint:"When you want to know how full the context window is \u2014 input/output/cache breakdown plus % of the model's limit used.",async handler(e){try{let t=await e.session.current.getContextUsage();zL(e.out,t)}catch{qL(e.out,e.stats)}return"continue"}},VL={name:"/history",summary:"Show conversation history",async handler(e){let{stats:t,out:n}=e;return t.turns.length===0?(n.info("No turns yet in this session."),"continue"):(n.line(),n.line(m.bold(`Session history (${t.turns.length} turn${t.turns.length===1?"":"s"})`)),n.line(ge()),t.turns.forEach((r,o)=>{let s=m.meta(`#${o+1}`),i=r.user.length>100?r.user.slice(0,97)+"...":r.user,a=r.assistant.length>100?r.assistant.slice(0,97)+"...":r.assistant;n.line(` ${s} ${m.user("\u25B6")} ${i}`),n.line(` ${m.brand("\u25C6")} ${m.dim(a)}`)}),n.line(),"continue")}},YL={name:"/reset",summary:"Clear screen, history, and session stats",async handler(e){let{stats:t,ui:n,out:r}=e;try{await e.session.current.sendMessage("/clear")}catch{}return t.totalTurns=0,t.totalCostUsd=0,t.totalTokens=0,t.totalDurationMs=0,t.turnCosts.length=0,t.turnTokens.length=0,t.turns.length=0,t.sessionStartTime=Date.now(),n.clearScreen(),r.success("Session reset."),"continue"}},XL={name:"/model",usage:"/model <opus|opus_1m|sonnet|sonnet_1m|haiku|org/model>",summary:"Switch the active model mid-session",hint:"When you want to upgrade to opus for a hard problem or downshift to haiku for cheap iteration \u2014 context carries over. Also accepts full HuggingFace-style IDs (e.g. mlx-community/Qwen3-30B-A3B-4bit).",async handler(e,t){let n=t.trim().toLowerCase();if(!n)return e.out.info(`Current model: ${m.brand(e.stats.model)}`),e.out.line(m.dim(` Aliases: ${Xd.join(", ")} (or any org/model HF id)`)),"continue";let r=Xd.includes(n),o=Ee(n)==="openai-compatible";if(!r&&!o)return e.out.warn(`Unknown model: ${n}. Aliases: ${Xd.join(", ")} (or org/model for local/OpenAI-compatible)`),"continue";try{await e.session.current.setModel(n),e.stats.model=n,e.ui.repaintStatusLine(),e.out.success(`Model switched to ${m.brand(n)}`)}catch(s){e.out.error(`Failed to switch model: ${s instanceof Error?s.message:String(s)}`)}return"continue"}},ZL={name:"/tools",summary:"List tools available to the session",async handler(e){try{let n=(await e.session.current.waitForInitialization()).tools??[];if(n.length===0)return e.out.info("No tools reported by the session."),"continue";e.out.line(),e.out.line(m.bold(`Tools (${n.length})`)),e.out.line(ge());let r=3,o=Math.ceil(n.length/r),s=Math.max(...n.map(i=>i.length))+2;for(let i=0;i<o;i++){let a=[];for(let l=0;l<r;l++){let c=l*o+i;c<n.length&&a.push(n[c].padEnd(s))}e.out.line(" "+a.join(""))}e.out.line()}catch(t){e.out.error(`Could not read session tools: ${t instanceof Error?t.message:String(t)}`)}return"continue"}},QL={name:"/mcp",summary:'List MCP servers connected to the session ("/mcp auth" to surface pending OAuth URLs)',async handler(e,t){let n=(t??"").trim().toLowerCase();if(n==="auth"){try{let{readOauthPending:r}=await Promise.resolve().then(()=>(Za(),TS)),o=r();if(Object.keys(o).length===0)return e.out.info("No MCP servers are waiting for OAuth."),"continue";e.out.line(),e.out.line(m.bold(`MCP OAuth pending (${Object.keys(o).length})`)),e.out.line(ge());for(let[s,i]of Object.entries(o)){let a=Date.now()-i.timestamp,l=Math.round(a/6e4);e.out.line(` ${m.warning("\u25CF")} ${s} ${m.dim(`(${l}m ago)`)}`),e.out.line(` ${m.info(i.authorizationUrl)}`)}e.out.line(),e.out.line(m.dim(" Open each URL in a browser. After authorizing, paste the code with:")),e.out.line(m.dim(" /mcp auth complete <serverName> <code>")),e.out.line()}catch(r){e.out.error(`Could not read OAuth state: ${r instanceof Error?r.message:String(r)}`)}return"continue"}if(n.startsWith("auth complete ")){let r=(t??"").trim(),o=r.slice(r.toLowerCase().indexOf("auth complete ")+14).trim(),s=o.indexOf(" ");if(s===-1||o.slice(0,s).length===0||o.slice(s+1).trim().length===0)return e.out.error("Usage: /mcp auth complete <serverName> <code>"),"continue";let i=o.slice(0,s).trim(),a=o.slice(s+1).trim();if(!e.mcpManager)return e.out.error("No MCP manager available in this session. Make sure an mcp.json config is present and at least one server is enabled."),"continue";try{e.out.info(`Completing OAuth for "${i}"\u2026`),await e.mcpManager.completeAuth(i,a),e.out.success(`OAuth complete for "${i}" \u2014 server is now connected.`)}catch(l){e.out.error(`OAuth completion failed for "${i}": ${l instanceof Error?l.message:String(l)}`)}return"continue"}if(n!==""&&n!=="auth")return e.out.error(`Unknown /mcp subcommand: "${n}". Try: /mcp, /mcp auth, /mcp auth complete <server> <code>.`),"continue";try{let o=(await e.session.current.waitForInitialization()).mcpServers??[];if(o.length===0)return e.out.info("No MCP servers connected."),"continue";e.out.line(),e.out.line(m.bold(`MCP servers (${o.length})`)),e.out.line(ge());let s=0;for(let i of o){let a=typeof i=="string"?i:i.name??JSON.stringify(i),l=typeof i=="object"&&i!==null&&"status"in i?String(i.status):"",c=l==="connected"?m.success("\u25CF"):m.warning("\u25CF");e.out.line(` ${c} ${a}${l?m.dim(` (${l})`):""}`),l==="oauth_pending"&&s++}e.out.line(),s>0&&(e.out.line(m.dim(` ${s} server(s) need OAuth \u2014 run "/mcp auth" to see authorization URLs.`)),e.out.line())}catch(r){e.out.error(`Could not read MCP servers: ${r instanceof Error?r.message:String(r)}`)}return"continue"}},eF={name:"/limits",summary:"Show known per-model context-window limits",async handler(e){e.out.line(),e.out.line(m.bold("Context-window limits")),e.out.line(ge());for(let[t,n]of Object.entries(as)){let r=t===e.stats.model?m.brand(" \u2190 active"):"";e.out.line(` ${m.warning(t.padEnd(12))} ${m.meta(te(n))}${r}`)}return e.out.line(),"continue"}},tF={name:"/debug",summary:"Show SDK session metadata (tools, MCP, skills, plugins, etc.)",hint:"When something feels broken and you want to inspect what the session actually loaded \u2014 tools, MCP servers, plugins, system prompt source.",async handler(e){try{let t=await e.session.current.waitForInitialization();e.out.line(),e.out.line(Va(t)),e.out.line()}catch(t){e.out.error(`Could not read session metadata: ${t instanceof Error?t.message:String(t)}`)}return"continue"}},ES=[GL,JL,VL,YL,XL,ZL,QL,eF,tF];var Zd=!1;async function xt(e,t,n={}){let r=e.stats.planMode,o=t!==void 0?t:!r;try{if(await e.session.current.setPermissionMode(o?"plan":"default"),e.stats.planMode=o,e.ui.repaintStatusLine(),o){let s=Zd?"":m.dim(" Shift+Tab or /plan to exit.");Zd||(Zd=!0),e.out.success(m.warning("\u25CF plan mode ON")+m.dim(" \u2014 write_file, edit_file, and write-intent bash are refused.")+s)}else n.closureSummarySkipped?e.out.success(m.success("\u25CB plan mode OFF")+m.dim(" \u2014 force-exit (closure summary skipped). Default permissions restored.")):e.out.success(m.success("\u25CB plan mode OFF")+m.dim(" \u2014 default permissions restored"))}catch(s){e.out.error(`Could not toggle plan mode: ${s instanceof Error?s.message:String(s)}`)}}async function xS(e){e.stats.pendingPlanExit&&(await xt(e,!1),e.stats.planMode||(e.stats.pendingPlanExit=!1))}var nF=["You are about to exit plan mode. Before I flip permissions back to default on the next turn, emit your final plan in three sections:",""," - **Chosen approach** \u2014 the plan you recommend, in one to three sentences."," - **Risks named** \u2014 the concrete failure modes, constraints, or unknowns this plan does not eliminate."," - **Alternatives considered** \u2014 the options you weighed and why you rejected them.","","This is the record. Be specific. Do not propose write actions in this turn \u2014 writes are still refused until the mode flips."].join(`
|
|
2012
2012
|
`);async function rF(e){return e.stats.pendingPlanExit=!0,e.ui.repaintStatusLine(),e.out.success(m.warning("\u25CF plan exit queued")+m.dim(" \u2014 plan mode still ON; writes still refused. Submitting closure summary (chosen approach, risks, alternatives); mode flips after the model responds. Force-exit now: /plan off again or Shift+Tab.")),{kind:"submit",message:nF}}async function oF(e){return e.stats.pendingPlanExit=!1,await xt(e,!1,{closureSummarySkipped:!0}),"continue"}async function sF(e){return e.stats.pendingPlanExit=!1,e.ui.repaintStatusLine(),e.out.success(m.warning("\u25CF plan mode ON")+m.dim(" \u2014 plan exit cancelled, staying in plan mode.")),"continue"}function iF(e){e.out.info(m.dim("(plan exit cancelled \u2014 submitting your prompt instead.)"))}var RS={name:"/plan",usage:"/plan [on|off|<prompt>]",summary:"Toggle plan mode (write_file, edit_file, and write-intent bash refused)",hint:"When you want the model to think through an approach without touching files \u2014 refuses writes until you flip back. Shift+Tab toggles too.",async handler(e,t){let n=t.trim(),r=n.toLowerCase();if(n!==""&&r!=="on"&&r!=="off"){let s=!!e.stats.pendingPlanExit;return e.stats.planMode||await xt(e,!0),s&&(e.stats.pendingPlanExit=!1,iF(e)),{kind:"submit",message:n}}return(r==="on"?!0:r==="off"?!1:!e.stats.planMode)===!0?e.stats.pendingPlanExit?sF(e):(e.stats.planMode||await xt(e,!0),"continue"):e.stats.planMode?e.stats.pendingPlanExit?oF(e):rF(e):(await xt(e,!1),"continue")}};U();import{readFileSync as aF,writeFileSync as lF,existsSync as AS,mkdirSync as cF}from"fs";import{join as uF}from"path";function _S(){return Cf(),Xc()}function CS(e){return uF(_S(),`${e}.json`)}function Qa(e){let t=CS(e);if(!AS(t))return{sessionId:e,items:[]};try{let n=aF(t,"utf-8"),r=JSON.parse(n);return Array.isArray(r.items)?r:{sessionId:e,items:[]}}catch{return{sessionId:e,items:[]}}}function _s(e){let t=_S();AS(t)||cF(t,{recursive:!0}),lF(CS(e.sessionId),JSON.stringify(e,null,2))}function IS(e,t){let r={id:e.items.reduce((o,s)=>Math.max(o,s.id),0)+1,text:t,done:!1,createdAt:Date.now()};return e.items.push(r),r}function PS(e,t){let n=e.items.find(r=>r.id===t);return n&&(n.done=!0),n}function MS(e,t){let n=e.items.findIndex(r=>r.id===t);return n===-1?!1:(e.items.splice(n,1),!0)}function OS(e){e.items.length=0}function el(e){if(e.items.length===0)return[];let t=[],n=Math.max(20,V());{let r=m.dim("\u250C\u2500 todos "),o=Math.max(0,Math.min(n-10,120));t.push(r+m.dim("\u2500".repeat(o)))}for(let r of e.items){let o=r.done?m.success("[x]"):m.dim("[ ]"),s=r.done?m.dim(r.text):fn(r.text),a=` ${m.meta(`#${r.id}`)} ${o} `,l=Math.max(8,n-z(a)),c=ae(s,l).split(`
|
|
2013
2013
|
`);t.push(a+(c[0]??""));let u=" ".repeat(z(a));for(let d of c.slice(1))t.push(u+d)}{let r=Math.max(0,Math.min(n-1,120));t.push(m.dim("\u2514"+"\u2500".repeat(r)))}return t}function $S(e){return e.items.length===0?"":e.items.map(t=>`${t.id}:${t.done?1:0}:${t.text}`).join(`
|
|
2014
2014
|
`)}function DS(e){let t=e.stats.sessionId??"unbound";return Qa(t)}function dF(e){let t=DS(e),n=el(t);if(n.length===0){e.out.info("No todos yet. Try /todo add buy milk");return}for(let r of n)e.out.line(r)}var LS={name:"/todo",usage:"/todo [add|done|rm|clear|list] ...",summary:"Manage this session's todo list",hint:"When you want a durable checklist the model and you both see \u2014 survives across turns and shows above each prompt.",async handler(e,t){let n=t.trim();if(!n||n==="list")return dF(e),"continue";let[r,...o]=n.split(/\s+/),s=o.join(" "),i=DS(e);switch(r){case"add":{if(!s)return e.out.warn("Usage: /todo add <text>"),"continue";let a=IS(i,s);return _s(i),e.out.success(`Added ${m.meta(`#${a.id}`)} ${a.text}`),"continue"}case"done":{let a=parseInt(s,10);if(!Number.isFinite(a))return e.out.warn("Usage: /todo done <id>"),"continue";let l=PS(i,a);return l?(_s(i),e.out.success(`Marked done ${m.meta(`#${a}`)} ${l.text}`)):e.out.warn(`No todo with id ${a}`),"continue"}case"rm":case"remove":{let a=parseInt(s,10);return Number.isFinite(a)?(MS(i,a)?(_s(i),e.out.success(`Removed ${m.meta(`#${a}`)}`)):e.out.warn(`No todo with id ${a}`),"continue"):(e.out.warn("Usage: /todo rm <id>"),"continue")}case"clear":return OS(i),_s(i),e.out.success("All todos cleared."),"continue";default:return e.out.warn(`Unknown subcommand: ${r}. Try /todo add, done, rm, clear, list.`),"continue"}}};var FS={name:"/save",usage:"/save [name]",hint:"When you want to checkpoint this conversation so /resume can pick it back up in a future session.",summary:"Save this session to disk (for /resume)",async handler(e,t){if(e.stats.totalTurns===0)return e.out.warn("Nothing to save \u2014 no turns in this session yet."),"continue";try{let n=t.trim()||void 0,r=uo(e.stats,n);e.out.success(m.success("Saved")+m.dim(` ${r}`));let o=e.stats.sessionId??n;o&&e.out.line(m.dim(` Resume: ${go(o,e.stats.model)}`))}catch(n){e.out.error(`Could not save: ${n instanceof Error?n.message:String(n)}`)}return"continue"}};function pF(e){if(typeof e!="number"||!Number.isFinite(e))return" \u2014 ";let t=new Date(e);return Number.isNaN(t.getTime())?" \u2014 ":t.toISOString().replace("T"," ").slice(0,16)}function mF(e){return{id:e.id,resumeId:e.data.sessionId??e.id,stored:e.data}}var NS={name:"/resume",usage:"/resume [id]",hint:"When you want to continue a previously /saved session \u2014 runs interactively to pick one if no id is given.",summary:"List saved sessions, or swap the active session for a stored one",async handler(e,t){let n=t.trim();if(n){let o=po(n);if(!o)return e.out.warn(`No saved session: ${n}`),"continue";if(typeof e.requestResume=="function"){let a=e.session.current.sessionId,l=o.data.sessionId;if(a!==void 0&&l!==void 0&&a===l||a!==void 0&&a===o.id)return e.out.warn(`Already on session ${o.id}.`),"continue";e.out.info(`Resuming session ${o.id} \u2026`);let u=await e.requestResume(mF(o));return u.ok?e.out.success(`Resumed ${o.id} (sdk id: ${u.sessionId})`):e.out.warn(u.reason),"continue"}let s=o.data,i=s.sessionId??o.id;return e.out.line(),e.out.line(m.bold(`Session ${o.id}`)),e.out.line(ge()),e.out.line(` model ${m.brand(s.model)}`),e.out.line(` turns ${m.meta(String(s.totalTurns))}`),e.out.line(` cost ${m.meta(Le(s.totalCostUsd))}`),e.out.line(` sdk id ${m.meta(s.sessionId??"\u2014")}`),e.out.line(),e.out.line(m.dim(" Resume with:")),e.out.line(m.brand(` ${go(i,s.model)}`)),e.out.line(),"continue"}let r=Rs();if(r.length===0)return e.out.info("No saved sessions found. Use /save first."),"continue";e.out.line(),e.out.line(m.bold(`Saved sessions (${r.length})`)),e.out.line(ge());for(let o of r.slice(0,20)){let s=pF(o.savedAt),i=m.brand(o.model.padEnd(7)),a=m.meta(`${o.totalTurns} turn${o.totalTurns===1?"":"s"}`.padEnd(9)),l=m.meta(Le(o.totalCostUsd).padStart(8)),c=m.warning(o.id);e.out.line(` ${s} ${i} ${a} ${l} ${c}`)}return e.out.line(),e.out.line(m.dim(" Resume with: /resume <id>")),e.out.line(),"continue"}};import{existsSync as SF,readFileSync as kF}from"node:fs";import{resolve as HS}from"node:path";import{execFileSync as jS}from"node:child_process";import{readFileSync as fF,writeFileSync as gF}from"node:fs";import{resolve as hF}from"node:path";var yF={feat:"Added",fix:"Fixed",refactor:"Changed",perf:"Changed",docs:"Changed",chore:"Changed",ci:"Changed",test:"Changed","test+fix":"Fixed",build:"Changed",style:"Changed"},bF=["Added","Fixed","Changed","Deprecated","Removed","Security"];function US(e){let t;try{t=jS("git",["describe","--tags","--abbrev=0"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()}catch{t=""}let n=t?["log",`${t}..HEAD`,"--format=%h %s"]:["log","-50","--format=%h %s"],r=jS("git",n,{cwd:e,encoding:"utf8"}).trim();return r?r.split(`
|
|
@@ -2079,7 +2079,7 @@ ${u}`}function rp(e,t){let n=VS[t.status];e.out.line(` ${n} ${m.bold(t.jobId)}
|
|
|
2079
2079
|
`)){let l=hp(a),c=ae(l,o);for(let u of c.split(`
|
|
2080
2080
|
`))i.push(s+r+u)}return i}var Nk=6,Ws=class{entries=new Map;order=[];agentIdStack=[];addStart(t,n,r){let o=Ce(r),s=nn(n+o),i=this.agentIdStack.at(-1)??void 0,a={kind:"tool",toolUseId:t,toolName:n,toolInput:o,prefix:s,...i!==void 0?{agentContext:i}:{}};this.entries.set(t,a),this.order.push(t),Gr.has(n)&&this.agentIdStack.push(t)}addStartWithAgentContext(t,n,r,o,s){let i=Ce(r),a=this.entries.get(t);if(a?.kind==="tool"){a.toolInput=i,a.prefix=nn(n+i,s),o!==void 0&&(a.agentContext=o);return}let l=nn(n+i,s),c={kind:"tool",toolUseId:t,toolName:n,toolInput:i,prefix:l,...o!==void 0?{agentContext:o}:{}};this.entries.set(t,c),this.order.push(t)}mergeAgentLabel(t,n,r){let o=this.entries.get(t);if(o?.kind!=="tool"||!Gr.has(o.toolName)||o.toolName==="Agent")return!1;let i=`(${Ce(n)})`;return o.toolName="Agent",o.toolInput=i,o.prefix=nn("Agent"+i,r),!0}setAgentContext(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(n===void 0?delete r.agentContext:r.agentContext=n)}setAgentResultSummary(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.agentResultSummary=n)}setThinkingTail(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(n===void 0?delete r.thinkingTail:r.thinkingTail=n)}addResult(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.result=n),this.agentIdStack.at(-1)===t&&this.agentIdStack.pop()}addDiff(t,n){let r=this.entries.get(t);r?.kind==="tool"&&(r.diff=n)}upsertTextChild(t,n,r){let o=this.entries.get(t);if(o?.kind==="text"){o.text=r,o.agentContext=n;return}let s={kind:"text",toolUseId:t,text:r,agentContext:n};this.entries.set(t,s),this.order.push(t)}removeTextChildrenUnder(t){let n=[];for(let[r,o]of this.entries)o.kind==="text"&&o.agentContext===t&&n.push(r);for(let r of n)this.entries.delete(r);if(n.length>0){let r=new Set(n);this.order=this.order.filter(o=>!r.has(o))}}hasPending(){return this.entries.size>0}hasEntry(t){return this.entries.get(t)?.kind==="tool"}getOverlay(){let t=this.buildChildMap(),n=[],r=Rt(),o=V(),s=c=>ue(c,o),i=[];for(let c of this.order){let u=this.entries.get(c);!u||u.kind!=="tool"||u.agentContext||i.push(u)}let a=i,l=0;if(i.length>Nk){let c=i.filter(f=>!f.result),u=i.filter(f=>f.result),d=Math.max(0,Nk-c.length),p=new Set(u.slice(-d));l=u.length-p.size,a=i.filter(f=>!f.result||p.has(f))}for(let c of a){let u=t.get(c.toolUseId);if(Je.has(c.toolName)&&u&&u.length>0)c.headerEmitted?n.push(s(m.dim(r.turnRoot))):n.push(s(m.dim(r.turnRoot)+c.prefix)),Sl(u,t,n,o,void 0,r),c.thinkingTail&&n.push(s(m.dim(r.spine)+m.thinking("\u2307 "+Be(c.thinkingTail))));else if(!(Je.has(c.toolName)&&c.headerEmitted))if(c.result){if(n.push(s(" "+c.prefix+m.dim(" \u2014 ")+fr(c.result.isError)+" "+Fn(c.result,void 0,60,c.toolName))),c.diff&&!c.result.isError)for(let d of rn(c.diff,"overlay"," "))n.push(s(d))}else n.push(s(" "+c.prefix+m.dim(" \u2026"))),c.thinkingTail&&n.push(s(m.dim(r.spine)+m.thinking("\u2307 "+Be(c.thinkingTail))))}return l>0&&n.push(s(" "+m.dim(`\u2026 +${l} done`))),n.join(`
|
|
2081
2081
|
`)}ancestorDepthOf(t){let n=new Set([t]),r=0,o=t,s=32;for(;o!==void 0&&r<s;){let i=this.entries.get(o);if(!i||i.kind!=="tool")break;let a=i.agentContext;if(a===void 0||n.has(a))break;n.add(a);let l=this.entries.get(a);if(!l||l.kind!=="tool")break;r+=1,o=a}return r}flushSource(t,n){let r=this.entries.get(t);if(!r||r.kind!=="tool")return[];let o=this.ancestorDepthOf(t),s=[];{let p=[],f=new Set([t]),g=r.agentContext;for(;g!==void 0&&!f.has(g);){f.add(g);let h=this.entries.get(g);if(!h||h.kind!=="tool")break;p.push({entry:h,depth:this.ancestorDepthOf(h.toolUseId)}),g=h.agentContext}p.reverse();for(let{entry:h,depth:b}of p)h.headerEmitted||(s.push(Ep(h,b)),h.headerEmitted=!0)}let i=new Set([t]),a=[t];for(;a.length>0;){let p=a.shift();for(let[f,g]of this.entries){if(i.has(f))continue;(g.kind==="tool",g.agentContext)===p&&(i.add(f),g.kind==="tool"&&a.push(f))}}let l=new Map;for(let p of this.order){if(!i.has(p))continue;let f=this.entries.get(p);if(!f)continue;let g=(f.kind==="tool",f.agentContext);if(!g)continue;let h=l.get(g);h||(h=[],l.set(g,h)),h.push(f)}let c=l.get(r.toolUseId)??[],u=r.headerEmitted?Bs(r,c,l,n,o).join(`
|
|
2082
|
-
`):Us(r,c,l,n,o);for(let p of i)this.entries.delete(p);this.order=this.order.filter(p=>!i.has(p));let d=u===""?[]:[u];return[...s,...d]}flushCompletedRoots(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let c of this.order){let u=this.entries.get(c);!u||u.kind!=="tool"||u.agentContext||u.result!==void 0&&r.push(c)}if(r.length===0)return[];let o=[],s=new Map,i=[];for(let c of r){let u=this.entries.get(c);if(!u||u.kind!=="tool")continue;let d=n.get(u.toolUseId);if(Je.has(u.toolName))if(o.push(...So(s,i,t)),s.clear(),i.length=0,u.headerEmitted){let p=Bs(u,d??[],n,t,0);o.push(...p)}else o.push(Us(u,d??[],n,t));else s.has(u.toolName)||(s.set(u.toolName,[]),i.push(u.toolName)),s.get(u.toolName).push(u)}o.push(...So(s,i,t));let a=new Set(r),l=[...r];for(;l.length>0;){let c=l.shift();for(let[u,d]of this.entries){if(a.has(u))continue;(d.kind==="tool",d.agentContext)===c&&(a.add(u),d.kind==="tool"&&l.push(u))}}for(let c of a)this.entries.delete(c);return this.order=this.order.filter(c=>!a.has(c)),o}flush(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let a of this.order){let l=this.entries.get(a);!l||l.kind!=="tool"||l.agentContext||r.push(a)}let o=[],s=new Map,i=[];for(let a of r){let l=this.entries.get(a);if(!l||l.kind!=="tool")continue;let c=n.get(l.toolUseId);if(Je.has(l.toolName))if(o.push(...So(s,i,t)),s.clear(),i.length=0,l.headerEmitted){let u=Bs(l,c??[],n,t,0);o.push(...u)}else o.push(Us(l,c??[],n,t));else s.has(l.toolName)||(s.set(l.toolName,[]),i.push(l.toolName)),s.get(l.toolName).push(l)}return o.push(...So(s,i,t)),this.entries.clear(),this.order=[],this.agentIdStack=[],o}buildChildMap(){let t=new Map;for(let n of this.order){let r=this.entries.get(n);if(!r)continue;let o=(r.kind==="tool",r.agentContext);if(!o)continue;let s=t.get(o);s||(s=[],t.set(o,s)),s.push(r)}return t}};var ko=class{buffer="";startedAt=null;endedAt=null;hasEmitted=!1;push(t){this.hasEmitted||(this.buffer+=t,this.startedAt||(this.startedAt=Date.now()))}markEnded(){this.endedAt===null&&this.startedAt!==null&&(this.endedAt=Date.now())}isActive(){return!this.hasEmitted}hasBufferedContent(){return this.buffer.trim().length>0}peek(){return this.buffer}consume(){return this.hasEmitted=!0,this.buffer}collapse(){if(this.hasEmitted||!this.startedAt)return!this.startedAt&&!this.hasEmitted&&je()&&console.error("[afk:thinking] collapse() short-circuited: no thinking chunks received this turn. Model may not support extended thinking, or API ignored the thinking parameter."),null;this.hasEmitted=!0;let t=this.endedAt??Date.now(),n=Math.max(0,t-this.startedAt),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(this.buffer.length/4);return` ${m.thinking("\u25C6 thought for "+r+" \xB7 "+o+" tok")}`}inlineSummary(){if(!this.startedAt||!this.hasBufferedContent())return null;let t=this.endedAt??Date.now(),n=Math.max(0,t-this.startedAt),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(this.buffer.length/4);return`thought ${r} \xB7 ${o} tok`}};var Rp="__main__";function Uk(e){let t={startedAt:Date.now(),lastEventAt:Date.now(),stats:{tokens:0,toolUses:0},contentBuffer:"",done:!1,errored:!1,stalledTicks:0};return e!==void 0&&(t.agentType=e),t}function vo(e,t){return{type:"tool_result",toolUseId:"synthetic",content:e,isError:t}}function Bk(e){let t=["Done"],n=[];e.stats.toolUses&&n.push(`${e.stats.toolUses} tool${e.stats.toolUses===1?"":"s"}`),e.stats.tokens&&n.push(`${
|
|
2082
|
+
`):Us(r,c,l,n,o);for(let p of i)this.entries.delete(p);this.order=this.order.filter(p=>!i.has(p));let d=u===""?[]:[u];return[...s,...d]}flushCompletedRoots(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let c of this.order){let u=this.entries.get(c);!u||u.kind!=="tool"||u.agentContext||u.result!==void 0&&r.push(c)}if(r.length===0)return[];let o=[],s=new Map,i=[];for(let c of r){let u=this.entries.get(c);if(!u||u.kind!=="tool")continue;let d=n.get(u.toolUseId);if(Je.has(u.toolName))if(o.push(...So(s,i,t)),s.clear(),i.length=0,u.headerEmitted){let p=Bs(u,d??[],n,t,0);o.push(...p)}else o.push(Us(u,d??[],n,t));else s.has(u.toolName)||(s.set(u.toolName,[]),i.push(u.toolName)),s.get(u.toolName).push(u)}o.push(...So(s,i,t));let a=new Set(r),l=[...r];for(;l.length>0;){let c=l.shift();for(let[u,d]of this.entries){if(a.has(u))continue;(d.kind==="tool",d.agentContext)===c&&(a.add(u),d.kind==="tool"&&l.push(u))}}for(let c of a)this.entries.delete(c);return this.order=this.order.filter(c=>!a.has(c)),o}flush(t){if(this.entries.size===0)return[];let n=this.buildChildMap(),r=[];for(let a of this.order){let l=this.entries.get(a);!l||l.kind!=="tool"||l.agentContext||r.push(a)}let o=[],s=new Map,i=[];for(let a of r){let l=this.entries.get(a);if(!l||l.kind!=="tool")continue;let c=n.get(l.toolUseId);if(Je.has(l.toolName))if(o.push(...So(s,i,t)),s.clear(),i.length=0,l.headerEmitted){let u=Bs(l,c??[],n,t,0);o.push(...u)}else o.push(Us(l,c??[],n,t));else s.has(l.toolName)||(s.set(l.toolName,[]),i.push(l.toolName)),s.get(l.toolName).push(l)}return o.push(...So(s,i,t)),this.entries.clear(),this.order=[],this.agentIdStack=[],o}buildChildMap(){let t=new Map;for(let n of this.order){let r=this.entries.get(n);if(!r)continue;let o=(r.kind==="tool",r.agentContext);if(!o)continue;let s=t.get(o);s||(s=[],t.set(o,s)),s.push(r)}return t}};var ko=class{buffer="";startedAt=null;endedAt=null;hasEmitted=!1;push(t){this.hasEmitted||(this.buffer+=t,this.startedAt||(this.startedAt=Date.now()))}markEnded(){this.endedAt===null&&this.startedAt!==null&&(this.endedAt=Date.now())}isActive(){return!this.hasEmitted}hasBufferedContent(){return this.buffer.trim().length>0}peek(){return this.buffer}consume(){return this.hasEmitted=!0,this.buffer}collapse(){if(this.hasEmitted||!this.startedAt)return!this.startedAt&&!this.hasEmitted&&je()&&console.error("[afk:thinking] collapse() short-circuited: no thinking chunks received this turn. Model may not support extended thinking, or API ignored the thinking parameter."),null;this.hasEmitted=!0;let t=this.endedAt??Date.now(),n=Math.max(0,t-this.startedAt),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(this.buffer.length/4);return` ${m.thinking("\u25C6 thought for "+r+" \xB7 "+o+" tok")}`}inlineSummary(){if(!this.startedAt||!this.hasBufferedContent())return null;let t=this.endedAt??Date.now(),n=Math.max(0,t-this.startedAt),r=n<1e3?`${n}ms`:`${(n/1e3).toFixed(1)}s`,o=Math.ceil(this.buffer.length/4);return`thought ${r} \xB7 ${o} tok`}};var Rp="__main__";function Uk(e){let t={startedAt:Date.now(),lastEventAt:Date.now(),stats:{tokens:0,toolUses:0},contentBuffer:"",done:!1,errored:!1,stalledTicks:0};return e!==void 0&&(t.agentType=e),t}function vo(e,t){return{type:"tool_result",toolUseId:"synthetic",content:e,isError:t}}function Bk(e){let t=["Done"],n=[];e.stats.toolUses&&n.push(`${e.stats.toolUses} tool${e.stats.toolUses===1?"":"s"}`),e.stats.tokens&&n.push(`${te(e.stats.tokens)} tok`);let r=e.responseMetadata?.durationMs,o=Date.now()-e.startedAt;typeof r=="number"&&(n.push(se(r)),o>r*1.5&&o-r>=1e3&&n.push(`${se(o)} wall`)),n.length===0&&o>0&&n.push(se(o));let s=e.thinkingLane?.inlineSummary();return s&&n.push(s),n.length>0&&t.push(`(${n.join(" \xB7 ")})`),t.join(" ")}function Ap(e){let t=Math.max(1,V()-2);return Math.max(1,t-e)}function Wk(e,t){return yN(e)?kt(e,{maxWidth:t}):ae(e,t)}function Hk(e,t,n){if(!n||!e.trim())return"";let r;return Gk(e)?r=`
|
|
2083
2083
|
\u258D streaming code\u2026
|
|
2084
2084
|
`:r=Wk(e,t),ae(r,t)}function _p(e,t){return e.split(`
|
|
2085
2085
|
`).map(n=>n?t+n:"").join(`
|
|
@@ -2096,14 +2096,14 @@ ${u}`}function rp(e,t){let n=VS[t.status];e.out.line(` ${n} ${m.bold(t.jobId)}
|
|
|
2096
2096
|
`)}function Ip(e,t,n){n.streamingMarkdown.current?n.streamingMarkdown.current.commitPending():t.contentBuffer.trim()&&(Mp(t.contentBuffer,n.out),t.contentBuffer=""),To(n);let o=gn(e).split(`
|
|
2097
2097
|
`);if(n.isTTY&&n.compositor)for(let s of o)n.compositor.commitAbove(s);else for(let s of o)n.out.line(s)}function Pp(e,t){if(!t.streamingMarkdown.current&&e.contentBuffer.trim()&&Mp(e.contentBuffer,t.out),e.contentBuffer="",t.coordinator){if(t.thinkingMode!=="off"){let n=t.thinkingLane.collapse();if(n){let r=n,o=t.compositor,s=t.isTTY,i=t.out;t.coordinator.schedule({anchor:"before-content",commits:[()=>{s&&o?o.commitAbove(r):i.line(r)}]})}}if(t.toolLane.hasPending()){let n=t.toolLane.flush(),r=t.compositor,o=t.overlayComposer,s=t.isTTY,i=t.out;t.coordinator.schedule({anchor:"before-content",commits:[()=>{if(s&&r){for(let a of n)r.commitAbove(a);r.commitAbove(""),o?(o.invalidate(),o.flush()):r.setOverlay("")}else{for(let a of n)i.line(a);i.line("")}}]})}}else{if(t.thinkingMode!=="off"){let n=t.thinkingLane.collapse();n&&(t.isTTY&&t.compositor?t.compositor.commitAbove(n):t.out.line(n))}To(t)}}function Mp(e,t){let n=kt(e);for(let r of n.split(`
|
|
2098
2098
|
`))t.line(r)}function Op(e,t){let n=Ci(e.message,e.stack);for(let r of n.split(`
|
|
2099
|
-
`))t.line(r)}function To(e){if(!e.toolLane.hasPending())return;let t=e.toolLane.flushCompletedRoots();if(e.isTTY&&e.compositor){if(t.length>0){for(let n of t)e.compositor.commitAbove(n);e.compositor.commitAbove("")}e.overlayComposer?(e.overlayComposer.markDirty("tool-lane"),e.overlayComposer.flush()):e.compositor.setOverlay(e.toolLane.getOverlay())}else if(t.length>0){for(let n of t)e.out.line(n);e.out.line("")}}function Zk(e,t,n,r){switch(n.stageTracker&&Xk(n.stageTracker,e),e.type){case"progress":r.set(e.progress.taskId,e.progress),n.isTTY&&gr(n,r);return;case"chunk":{let o=e.chunk;if(o.type==="tool_use_detail")n.thinkingLane.markEnded(),n.streamingMarkdown.current?.commitPending(),n.isTTY&&To(n),n.toolLane.addStartWithAgentContext(o.toolUseId,o.toolName,o.toolInput,void 0),t.stats.toolUses+=1,n.isTTY&&n.compositor&&n.compositor.setSpinner({enabled:!0,rotateVerbEveryMs:3500}),n.isTTY&&gr(n,r);else if(o.type==="tool_result")n.streamingMarkdown.current?.commitPending(),n.toolLane.addResult(o.toolUseId,o),n.isTTY&&gr(n,r);else if(o.type==="tool_diff")n.toolLane.addDiff(o.toolUseId,o.diff),n.isTTY&&gr(n,r);else if(o.type==="content"){n.thinkingLane.markEnded();let s=ap(o.content);if(n.activeSkillName&&!n.skillBadgeEmitted){let i=lp(s,n.activeSkillName);if(s=i.text,i.found){n.skillBadgeEmitted=!0;let{color:a,glyph:l}=jd("skill"),c=" "+a(l+" ")+a.bold(n.activeSkillName);n.isTTY&&n.compositor?n.compositor.commitAbove(c):n.out.line(c)}}else n.activeSkillName&&(s=lp(s,n.activeSkillName).text);if(!s)return;t.contentBuffer+=s,n.isTTY&&(n.compositor&&n.compositor.setSpinner({enabled:!1}),To(n),n.streamingMarkdown.current||(n.streamingMarkdown.current=new vl({...n.compositor?{compositor:n.compositor}:{},...n.overlayComposer?{overlayComposer:n.overlayComposer}:{}})),n.streamingMarkdown.current.push(s))}else if(o.type==="thinking"){if(n.thinkingMode==="off")return;n.thinkingLane.push(o.content),n.isTTY&&gr(n,r)}return}case"message":t.contentBuffer||(t.contentBuffer=ap(e.message.content));return;case"error":t.errored=!0,Op(e.error,n.out);return;case"done":t.done=!0,e.metadata&&(t.responseMetadata=e.metadata),Pp(t,n);return;case"suggestion":return;case"panel":Ip(e.spec,t,n);return}}function gr(e,t){if(!e.compositor)return;if(e.overlayComposer){e.overlayComposer.invalidate(),e.overlayComposer.flush();return}let n=[];if(e.stageTracker&&n.push(" "+Tl(e.stageTracker.stage,{dim:m.dim,accent:m.brand,bold:m.bold})),e.thinkingMode==="live"&&e.thinkingLane.hasBufferedContent()){let r=xl(e.thinkingLane.peek(),{cols:V()});r&&n.push(r)}if(e.toolLane.hasPending()&&n.push(e.toolLane.getOverlay()),t&&t.size>0){let r=[];for(let o of t.values())r.push(...Oa(o));r.length>0&&n.push(r.join(`
|
|
2099
|
+
`))t.line(r)}function To(e){if(!e.toolLane.hasPending())return;let t=e.toolLane.flushCompletedRoots();if(e.isTTY&&e.compositor){if(t.length>0){for(let n of t)e.compositor.commitAbove(n);e.compositor.commitAbove("")}e.overlayComposer?(e.overlayComposer.markDirty("tool-lane"),e.overlayComposer.flush()):e.compositor.setOverlay(e.toolLane.getOverlay())}else if(t.length>0){for(let n of t)e.out.line(n);e.out.line("")}}function Zk(e,t,n,r){switch(n.stageTracker&&Xk(n.stageTracker,e),e.type){case"progress":r.set(e.progress.taskId,e.progress),n.isTTY&&gr(n,r);return;case"chunk":{let o=e.chunk;if(o.type==="tool_use_detail")n.thinkingLane.markEnded(),n.streamingMarkdown.current?.commitPending(),n.isTTY&&To(n),n.toolLane.addStartWithAgentContext(o.toolUseId,o.toolName,o.toolInput,void 0),t.stats.toolUses+=1,n.isTTY&&n.compositor&&n.compositor.setSpinner({enabled:!0,rotateVerbEveryMs:3500}),n.isTTY&&gr(n,r);else if(o.type==="tool_result")n.streamingMarkdown.current?.commitPending(),n.toolLane.addResult(o.toolUseId,o),n.isTTY&&gr(n,r);else if(o.type==="tool_diff")n.toolLane.addDiff(o.toolUseId,o.diff),n.isTTY&&gr(n,r);else if(o.type==="content"){n.thinkingLane.markEnded();let s=ap(o.content);if(n.activeSkillName&&!n.skillBadgeEmitted){let i=lp(s,n.activeSkillName);if(s=i.text,i.found){n.skillBadgeEmitted=!0;let{color:a,glyph:l}=jd("skill"),c=" "+a(l+" ")+a.bold(n.activeSkillName);n.isTTY&&n.compositor?n.compositor.commitAbove(c):n.out.line(c)}}else n.activeSkillName&&(s=lp(s,n.activeSkillName).text);if(!s)return;t.contentBuffer+=s,n.isTTY&&(n.compositor&&n.compositor.setSpinner({enabled:!1}),To(n),n.streamingMarkdown.current||(n.streamingMarkdown.current=new vl({...n.compositor?{compositor:n.compositor}:{},...n.overlayComposer?{overlayComposer:n.overlayComposer}:{}})),n.streamingMarkdown.current.push(s))}else if(o.type==="thinking"){if(n.thinkingMode==="off")return;n.thinkingLane.push(o.content),n.isTTY&&gr(n,r)}return}case"message":t.contentBuffer||(t.contentBuffer=ap(e.message.content));return;case"error":t.errored=!0,Op(e.error,n.out);return;case"done":t.done=!0,e.metadata&&(t.responseMetadata=e.metadata),Pp(t,n);return;case"suggestion":return;case"panel":Ip(e.spec,t,n);return}}function gr(e,t){if(!e.compositor)return;if(e.overlayComposer){e.overlayComposer.invalidate(),e.overlayComposer.flush();return}let n=[];if(e.stageTracker&&n.push(" "+Tl(e.stageTracker.stage,{dim:m.dim,accent:m.brand,bold:m.bold})),e.thinkingMode==="live"&&e.thinkingLane.isActive()&&e.thinkingLane.hasBufferedContent()){let r=xl(e.thinkingLane.peek(),{cols:V()});r&&n.push(r)}if(e.toolLane.hasPending()&&n.push(e.toolLane.getOverlay()),t&&t.size>0){let r=[];for(let o of t.values())r.push(...Oa(o));r.length>0&&n.push(r.join(`
|
|
2100
2100
|
`))}n.length>0&&e.compositor.setOverlay(n.join(`
|
|
2101
2101
|
`))}var Rl=class{beforeContent=[];afterSubagent=new Map;afterContent=[];schedule(t){let{anchor:n}=t;if(n==="before-content")this.beforeContent.push(t);else if(n==="after-content")this.afterContent.push(t);else{let r=n.slice(15),o=this.afterSubagent.get(r);o||(o=[],this.afterSubagent.set(r,o)),o.push(t)}}drainSubagent(t){for(let r of this.beforeContent.splice(0))for(let o of r.commits)o();let n=this.afterSubagent.get(t);if(n){this.afterSubagent.delete(t);for(let r of n)for(let o of r.commits)o()}}async flushAll(t){for(let n of this.beforeContent.splice(0))for(let r of n.commits)r();if(t)try{await t()}catch{}for(let[n,r]of Array.from(this.afterSubagent)){this.afterSubagent.delete(n);for(let o of r)for(let s of o.commits)s()}for(let n of this.afterContent.splice(0))for(let r of n.commits)r()}};function $p(e,t){let n=e.trimEnd();if(!n.trim())return"";let r=Math.max(t*4,400),o=n.length>r?n.slice(-r):n,s=/[.!?](?=\s)|\n+/g,i=-1,a;for(;(a=s.exec(o))!==null;)i=a.index+a[0].length;let l=i>=0?o.slice(i):o;return l=l.replace(/\s+/g," ").trim(),l?(l.length>t&&(l=l.slice(0,Math.max(1,t-1))+"\u2026"),l):""}function Al(e,t){if(!(!e||!e.trim())&&!t.isTTY)for(let n of EN(e))t.out.line(n)}function EN(e){if(!e)return[];let t=m.dim("\u2502 "),n=" ",r=Math.max(1,V()-n.length-2-2),o=[];for(let s of e.split(`
|
|
2102
2102
|
`)){let i=ae(s,r);for(let a of i.split(`
|
|
2103
2103
|
`))o.push(n+t+a)}return o}function Qk(e,t,n,r){if(r.isTTY){let s=n.syntheticAgentToolUseId;s&&r.toolLane.setThinkingTail(s,void 0),n.contentBuffer=""}else n.contentBuffer.trim()&&(Al(n.contentBuffer,r),n.contentBuffer="");let o=gn(e);for(let s of o.split(`
|
|
2104
2104
|
`))r.isTTY&&r.compositor?r.compositor.commitAbove(s):r.out.line(s);r.isTTY&&r.compositor?r.compositor.commitAbove(""):r.out.line("")}function Dp(e,t,n,r){if(t.syntheticAgentToolUseId)return;let o=t.agentType?.trim()||"agent",s=process.stdout.columns??100,i=Math.max(20,s-14);if(r!==void 0&&n.toolLane.mergeAgentLabel(r,o,i)){t.syntheticAgentToolUseId=r;return}let a=`__synth_agent_${e}`;n.toolLane.addStartWithAgentContext(a,"Agent",`(${o})`,r,i),t.syntheticAgentToolUseId=a}function ev(e,t,n,r,o){let s=t.syntheticAgentToolUseId;if(!s||t.errored)return;if(!n.isTTY&&t.contentBuffer&&Al(t.contentBuffer,n),t.contentBuffer="",!n.isTTY&&t.thinkingLane?.hasBufferedContent()){let a=t.thinkingLane.collapse();a&&(n.out.line(a),n.out.line(""))}n.toolLane.setThinkingTail(s,void 0),r.delete(s),o.delete(s);let i=Bk(t);n.toolLane.setAgentResultSummary(s,i),n.toolLane.addResult(s,vo(i,!1)),n.isTTY&&n.compositor&&n.compositor.setOverlay(n.toolLane.getOverlay())}var _l=new Map,Eo=new Map;function tv(e,t,n,r){let o=n.syntheticAgentToolUseId;if(o)switch(e.type){case"progress":e.progress.totalTokens&&(n.stats.tokens=e.progress.totalTokens),e.progress.toolUses!==void 0&&(n.stats.progressReportedToolUses=e.progress.toolUses);return;case"chunk":{let s=e.chunk;if(s.type==="tool_use_detail"){n.thinkingLane?.markEnded(),n.currentTextEntryId=void 0;let i=r.streamingMarkdown.get(t);i&&i.commitPending(),r.toolLane.setThinkingTail(o,void 0);let a=process.stdout.columns??100,l=Math.max(20,a-14);r.toolLane.addStartWithAgentContext(s.toolUseId,s.toolName,s.toolInput,o,l),n.stats.toolUses+=1,r.isTTY&&(r.overlayComposer?(r.overlayComposer.markDirty("tool-lane"),r.overlayComposer.flush()):r.compositor&&r.compositor.setOverlay(r.toolLane.getOverlay()))}else if(s.type==="tool_result"){let i=r.streamingMarkdown.get(t);i&&i.commitPending(),r.toolLane.addResult(s.toolUseId,s),r.isTTY&&(r.overlayComposer?(r.overlayComposer.markDirty("tool-lane"),r.overlayComposer.flush()):r.compositor&&r.compositor.setOverlay(r.toolLane.getOverlay()))}else if(s.type==="tool_diff")r.toolLane.addDiff(s.toolUseId,s.diff),r.isTTY&&(r.overlayComposer?(r.overlayComposer.markDirty("tool-lane"),r.overlayComposer.flush()):r.compositor&&r.compositor.setOverlay(r.toolLane.getOverlay()));else if(s.type==="content")if(n.thinkingLane?.markEnded(),n.currentTextEntryId||(n.currentTextEntryId="__in_text_block__"),n.contentBuffer+=s.content,r.isTTY&&r.compositor){if(s.content.trim()){let i=process.stdout.columns??100,a=Math.max(20,i-14),l=$p(n.contentBuffer,a),c=Date.now(),u=_l.get(o)??0,d=l?/[.!?…]$/.test(l):!1;l&&(c-u>=1500||d)&&(_l.set(o,c),r.toolLane.setThinkingTail(o,l))}{let i=Date.now(),a=Eo.get(o)??0;i-a>=1500&&(Eo.set(o,i),r.compositor.setOverlay(r.toolLane.getOverlay()))}}else{let i=n.contentBuffer.lastIndexOf(`
|
|
2105
2105
|
`);if(i!==-1){let a=n.contentBuffer.slice(0,i);n.contentBuffer=n.contentBuffer.slice(i+1),Al(a,r)}}else if(s.type==="thinking"){if(r.thinkingMode==="off")return;if(n.thinkingLane||(n.thinkingLane=new ko),n.thinkingLane.push(s.content),r.thinkingMode==="live"&&r.isTTY&&r.compositor){let i=process.stdout.columns??100,a=Math.max(20,i-14),l=$p(n.thinkingLane.peek(),a);l&&r.toolLane.setThinkingTail(o,l);{let c=Date.now(),u=Eo.get(o)??0;c-u>=1500&&(Eo.set(o,c),r.compositor.setOverlay(r.toolLane.getOverlay()))}}}return}case"message":return;case"error":n.errored=!0,r.toolLane.setThinkingTail(o,void 0),_l.delete(o),Eo.delete(o);{let s=`error \u2014 ${e.error.message}`;r.toolLane.setAgentResultSummary(o,s),r.toolLane.addResult(o,vo(s,!0))}r.isTTY&&r.compositor&&r.compositor.setOverlay(r.toolLane.getOverlay());return;case"done":n.done=!0,e.metadata&&(n.responseMetadata=e.metadata),ev(t,n,r,_l,Eo);return;case"suggestion":return;case"panel":Qk(e.spec,t,n,r);return}}var Cl=class{sink;order;slots=new Map;dirty=!1;constructor(t,n){this.sink=t,this.order=[...n]}register(t){this.slots.set(t.key,t),this.dirty=!0}markDirty(t){this.slots.has(t)&&(this.dirty=!0)}flush(){if(!this.dirty)return;this.dirty=!1;let t=[];for(let n of this.order){let r=this.slots.get(n);if(r===void 0)continue;let o=r.render();o.length>0&&t.push(o)}this.sink.setOverlay(t.join(`
|
|
2106
|
-
`))}invalidate(){this.dirty=!0}};function nv(e,t=2){if(t<1||!Number.isInteger(t))throw new RangeError(`makeDedupingLineWriter: maxRepeat must be a positive integer, got ${t}`);let n=null,r=0,o=()=>{if(n!==null&&r>t){let s=r-t;e.line(` \u2026 (line repeated ${s} more time${s===1?"":"s"})`)}};return{line(s){let i=s??"";i===n?(r++,r<=t&&e.line(i)):(o(),n=i,r=1,e.line(i))},raw(s){o(),n=null,r=0,e.raw(s)},success(s){o(),n=null,r=0,e.success(s)},info(s){o(),n=null,r=0,e.info(s)},warn(s){o(),n=null,r=0,e.warn(s)},error(s){o(),n=null,r=0,e.error(s)},flush(){o(),n=null,r=0}}}var xN=3e4,RN=" \xB7 waiting ",AN=375;function rv(e,t){e.register({key:"stage-rail",render:()=>t.stageTracker?" "+Tl(t.stageTracker.stage,{dim:m.dim,accent:m.brand,bold:m.bold}):""}),e.register({key:"thinking-live",render:()=>t.thinkingMode!=="live"||!t.thinkingLane.hasBufferedContent()?"":xl(t.thinkingLane.peek(),{cols:V()})??""}),e.register({key:"markdown-pending",render:()=>{let n=t.streamingMarkdownRef.current;return n?n.renderPending():""}}),e.register({key:"tool-lane",render:()=>t.toolLane.hasPending()?t.toolLane.getOverlay():""}),e.register({key:"progress-banner",render:()=>{let n=[];for(let r of t.lastProgressByTask.values())n.push(...Oa(r));return n.length>0?n.join(`
|
|
2106
|
+
`))}invalidate(){this.dirty=!0}};function nv(e,t=2){if(t<1||!Number.isInteger(t))throw new RangeError(`makeDedupingLineWriter: maxRepeat must be a positive integer, got ${t}`);let n=null,r=0,o=()=>{if(n!==null&&r>t){let s=r-t;e.line(` \u2026 (line repeated ${s} more time${s===1?"":"s"})`)}};return{line(s){let i=s??"";i===n?(r++,r<=t&&e.line(i)):(o(),n=i,r=1,e.line(i))},raw(s){o(),n=null,r=0,e.raw(s)},success(s){o(),n=null,r=0,e.success(s)},info(s){o(),n=null,r=0,e.info(s)},warn(s){o(),n=null,r=0,e.warn(s)},error(s){o(),n=null,r=0,e.error(s)},flush(){o(),n=null,r=0}}}var xN=3e4,RN=" \xB7 waiting ",AN=375;function rv(e,t){e.register({key:"stage-rail",render:()=>t.stageTracker?" "+Tl(t.stageTracker.stage,{dim:m.dim,accent:m.brand,bold:m.bold}):""}),e.register({key:"thinking-live",render:()=>t.thinkingMode!=="live"||!t.thinkingLane.isActive()||!t.thinkingLane.hasBufferedContent()?"":xl(t.thinkingLane.peek(),{cols:V()})??""}),e.register({key:"markdown-pending",render:()=>{let n=t.streamingMarkdownRef.current;return n?n.renderPending():""}}),e.register({key:"tool-lane",render:()=>t.toolLane.hasPending()?t.toolLane.getOverlay():""}),e.register({key:"progress-banner",render:()=>{let n=[];for(let r of t.lastProgressByTask.values())n.push(...Oa(r));return n.length>0?n.join(`
|
|
2107
2107
|
`):""}}),e.register({key:"interrupt",render:()=>_N(t.getInterrupting())})}function _N(e){return e?" "+m.warning("\u26A0 interrupting\u2026 (Ctrl+C again to exit)"):""}function ov(e,t){return Ge.subscribe(()=>{t||!e||(e.invalidate(),e.flush())})}function sv(e){if(e.disposed)return!1;let t=!1,n=Date.now();for(let[r,o]of e.sources){if(o.done||o.errored||!o.syntheticAgentToolUseId)continue;let s=n-o.lastEventAt;if(s>xN)if(o.stalledTicks+=1,o.stalledTicks>=AN*2)je()&&process.stderr.write(`[stream-renderer] auto_settle_timeout ${JSON.stringify({sourceId:r,elapsedMs:s,syntheticAgentToolUseId:o.syntheticAgentToolUseId})}
|
|
2108
2108
|
`),e.toolLane.addResult(o.syntheticAgentToolUseId,vo("[no-result \u2014 timed out]",!1)),o.done=!0,t=!0;else{let i=o.agentType??r,a=RN+se(s);o.pauseAnnotation!==a&&(o.pauseAnnotation=a,e.toolLane.addStartWithAgentContext(o.syntheticAgentToolUseId,"Agent",`(${i})${a}`,void 0),t=!0)}}return t&&e.isTTY&&e.overlayComposer&&(e.overlayComposer.markDirty("tool-lane"),e.overlayComposer.flush()),t}function Lp(e){return{out:e.out,isTTY:e.isTTY,compositor:e.compositor,overlayComposer:e.overlayComposer,toolLane:e.toolLane,thinkingLane:e.thinkingLane,thinkingMode:e.thinkingMode,streamingMarkdown:e.streamingMarkdown,coordinator:e.coordinator,...e.isTTY&&e.stageTracker?{stageTracker:e.stageTracker}:{},...e.activeSkillName?{activeSkillName:e.activeSkillName}:{}}}function Fp(e){return{isTTY:e.isTTY,compositor:e.compositor,overlayComposer:e.overlayComposer,toolLane:e.toolLane,out:e.out,streamingMarkdown:e.streamingMarkdown,thinkingMode:e.thinkingMode}}function iv(e){if(e.parentId===void 0)return;let t=e.sources.get(e.parentId);if(t!==void 0)return t.syntheticAgentToolUseId;if(e.toolLane.hasEntry(e.parentId))return e.parentId;je()&&process.stderr.write(`[stream-renderer] parentId_fallback_unresolved ${JSON.stringify({parentId:e.parentId,sourceId:e.sourceId})}
|
|
2109
2109
|
`)}var xo=class{out;thinkingMode;isTTY;captureMode;reducedMotion;onCancel;onBackground;activeSkillName;history;autocompleteState;promptText;scrollRegion;ownsCompositor=!0;borrowedCompositor=null;priorOnCancel=void 0;interrupting=!1;coordinator=new Rl;compositor=null;overlayComposer=null;streamingMarkdownRef={current:null};toolLane=new Ws;thinkingLane=new ko;stageTracker=Yk();sources=new Map;subagentMarkdown=new Map;lastProgressByTask=new Map;disposed=!1;pauseTickInterval=null;resizeUnsub=null;sink;constructor(t){this.captureMode=t.captureMode??sS(),this.reducedMotion=t.reducedMotion??iS(),this.out=this.captureMode?nv(t.out,2):t.out;let n=t.thinkingMode??(t.verbose===!0?"live":"summary");this.thinkingMode=this.captureMode&&n==="live"?"summary":n,this.onCancel=t.onCancel,this.onBackground=t.onBackground,this.isTTY=!(t.forceNonTty??!1)&&!!process.stdout.isTTY&&!!process.stdin.isTTY,this.activeSkillName=t.activeSkillName,this.history=t.history,this.autocompleteState=t.autocompleteState,this.promptText=t.promptText,this.scrollRegion=t.scrollRegion,t.compositor&&(this.borrowedCompositor=t.compositor,this.ownsCompositor=!1),this.sink=(r,o)=>this.process(r,o)}async arm(){if(this.disposed||!this.isTTY||this.compositor)return;let t;if(this.borrowedCompositor)t=this.borrowedCompositor,t.setInputMode("streaming"),this.priorOnCancel=t.getOnCancel(),this.onCancel&&t.setOnCancel(this.onCancel);else{let n={has:r=>Xe().some(o=>o.name===`/${r}`)};t=new wo({stdout:process.stdout,stdin:process.stdin,...this.onCancel?{onCancel:this.onCancel}:{},...this.onBackground?{onBackground:this.onBackground}:{},...this.history?{history:this.history}:{},...this.autocompleteState?{autocompleteState:this.autocompleteState}:{},...this.promptText!==void 0?{promptText:this.promptText}:{},formatInputBuffer:r=>Ln(r,n),...this.scrollRegion?{scrollRegion:this.scrollRegion}:{},captureMode:this.captureMode}),await t.arm()}this.compositor=t,this.overlayComposer=new Cl(t,["stage-rail","thinking-live","markdown-pending","tool-lane","progress-banner","interrupt"]),rv(this.overlayComposer,{stageTracker:this.stageTracker,thinkingMode:this.thinkingMode,thinkingLane:this.thinkingLane,streamingMarkdownRef:this.streamingMarkdownRef,toolLane:this.toolLane,lastProgressByTask:this.lastProgressByTask,getInterrupting:()=>this.interrupting}),t.setSpinner({enabled:!this.reducedMotion,rotateVerbEveryMs:3500}),this.pauseTickInterval=setInterval(()=>this.checkPauseAnnotations(),80),this.resizeUnsub=ov(this.overlayComposer,!1)}getCompositor(){return this.compositor}setInterrupting(t){this.disposed||(this.interrupting=t,this.overlayComposer&&(this.overlayComposer.markDirty("interrupt"),this.overlayComposer.flush()))}process(t,n){if(this.disposed)return;let r=n?.subagentId??Rp,o=r===Rp,s=this.sources.get(r);if(!s&&(s=Uk(n?.agentType),this.sources.set(r,s),!o)){let i=iv({parentId:n?.parentId,sources:this.sources,toolLane:this.toolLane,sourceId:r});Dp(r,s,Fp({isTTY:this.isTTY,compositor:this.compositor,overlayComposer:this.overlayComposer,toolLane:this.toolLane,out:this.out,streamingMarkdown:this.subagentMarkdown,thinkingMode:this.thinkingMode}),i)}if(o)Zk(t,s,Lp({out:this.out,isTTY:this.isTTY,compositor:this.compositor,overlayComposer:this.overlayComposer,toolLane:this.toolLane,thinkingLane:this.thinkingLane,thinkingMode:this.thinkingMode,streamingMarkdown:this.streamingMarkdownRef,coordinator:this.coordinator,...this.isTTY?{stageTracker:this.stageTracker}:{},...this.activeSkillName?{activeSkillName:this.activeSkillName}:{}}),this.lastProgressByTask);else{if(tv(t,r,s,Fp({isTTY:this.isTTY,compositor:this.compositor,overlayComposer:this.overlayComposer,toolLane:this.toolLane,out:this.out,streamingMarkdown:this.subagentMarkdown,thinkingMode:this.thinkingMode})),s.lastEventAt=Date.now(),s.pauseAnnotation!==void 0&&s.syntheticAgentToolUseId){s.pauseAnnotation=void 0,s.stalledTicks=0;let a=s.agentType??r;this.toolLane.addStartWithAgentContext(s.syntheticAgentToolUseId,"Agent",`(${a})`,void 0)}if((t.type==="done"||t.type==="error")&&this.isTTY){let a=s.syntheticAgentToolUseId;if(a&&this.toolLane.hasEntry(a)){let c=this.toolLane.flushSource(a),u=this.compositor,d=this.overlayComposer,p=this.toolLane,f=this.out;this.coordinator.schedule({anchor:`after-subagent:${r}`,commits:[()=>{if(u){for(let g of c)u.commitAbove(g);u.commitAbove(""),d?(d.markDirty("tool-lane"),d.flush()):u.setOverlay(p.getOverlay())}else{for(let g of c)f.line(g);f.line("")}}]});try{this.streamingMarkdownRef.current&&this.streamingMarkdownRef.current.commitPending()}finally{this.coordinator.drainSubagent(r)}}let l=Lp({out:this.out,isTTY:this.isTTY,compositor:this.compositor,overlayComposer:this.overlayComposer,toolLane:this.toolLane,thinkingLane:this.thinkingLane,thinkingMode:this.thinkingMode,streamingMarkdown:this.streamingMarkdownRef,coordinator:this.coordinator,...this.isTTY?{stageTracker:this.stageTracker}:{},...this.activeSkillName?{activeSkillName:this.activeSkillName}:{}});gr(l,this.lastProgressByTask)}}}async dispose(){if(this.disposed)return;this.disposed=!0,this.resizeUnsub&&(this.resizeUnsub(),this.resizeUnsub=null);let t=this.streamingMarkdownRef.current?()=>this.streamingMarkdownRef.current.flush():void 0;await this.coordinator.flushAll(t),this.streamingMarkdownRef.current&&(this.streamingMarkdownRef.current.dispose(),this.streamingMarkdownRef.current=null);for(let r of this.subagentMarkdown.values()){try{await r.flush()}catch{}r.dispose()}if(this.subagentMarkdown.clear(),this.toolLane.hasPending()){let r=this.toolLane.flush();if(this.isTTY&&this.compositor){for(let o of r)this.compositor.commitAbove(o);this.compositor.commitAbove(""),this.overlayComposer?(this.overlayComposer.markDirty("tool-lane"),this.overlayComposer.flush()):this.compositor.setOverlay(this.toolLane.getOverlay())}else{for(let o of r)this.out.line(o);this.out.line("")}}if(this.pauseTickInterval&&(clearInterval(this.pauseTickInterval),this.pauseTickInterval=null),this.compositor){if(this.ownsCompositor)try{this.compositor.disarm()}catch{}else{try{this.compositor.setSpinner({enabled:!1})}catch(r){J("[stream-renderer] borrow-dispose setSpinner: "+String(r))}try{this.overlayComposer?(this.overlayComposer.invalidate(),this.overlayComposer.flush()):this.compositor.setOverlay("")}catch(r){J("[stream-renderer] borrow-dispose setOverlay: "+String(r))}try{this.compositor.setInputMode("idle")}catch(r){J("[stream-renderer] borrow-dispose setInputMode: "+String(r))}try{this.compositor.setOnCancel(this.priorOnCancel??null)}catch(r){J("[stream-renderer] borrow-dispose setOnCancel: "+String(r))}this.priorOnCancel=void 0}this.compositor=null,this.borrowedCompositor=null}let n=this.out;if(typeof n.flush=="function")try{n.flush()}catch{}}checkPauseAnnotations(){sv({compositor:this.compositor,disposed:this.disposed,sources:this.sources,toolLane:this.toolLane,isTTY:this.isTTY,overlayComposer:this.overlayComposer,stageTracker:this.stageTracker,thinkingMode:this.thinkingMode,thinkingLane:this.thinkingLane,streamingMarkdownRef:this.streamingMarkdownRef,lastProgressByTask:this.lastProgressByTask,out:this.out,pauseTickInterval:this.pauseTickInterval,resizeUnsub:this.resizeUnsub})}};function Il(e,t){let n=t.verbose??T.AFK_SKILL_STREAM_VERBOSE==="1",r=t.out??e.out,o=e.getCompositor?.()??null;return new xo({out:r,verbose:n,activeSkillName:t.skillName,onCancel:t.onCancel??(()=>{}),...o?{compositor:o}:{}})}function Ro(e){let t=e!==void 0?r=>{e.fn(r)}:r=>{console.log(r)},n=e!==void 0&&e.rawFn!==void 0?r=>{e.rawFn(r)}:r=>{process.stdout.write(r)};return{line(r=""){t(r)},raw(r){n(r)},success(r){t(m.success("\u2713 ")+r)},info(r){t(m.info("\u2139 ")+r)},warn(r){t(m.warning("\u26A0 ")+r)},error(r){t(m.error("\u2717 ")+r)}}}var CN="You are initializing this project for use with AFK (an AI agent CLI).\n\nYour job: scan this project and generate an `AFK.md` file in the project root. AFK.md is a plain markdown file (no YAML frontmatter) that serves as the system prompt for all AFK sessions in this project.\n\n## Steps\n\n1. **Discover project metadata** \u2014 read these files if they exist:\n - `package.json`, `tsconfig.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`, `Makefile`, `CMakeLists.txt`\n - `.github/workflows/` (CI config)\n - `docker-compose.yml`, `Dockerfile`\n - `README.md` or `README`\n - Any existing `CLAUDE.md` or `AGENTS.md` (borrow relevant context)\n\n2. **Scan directory structure** \u2014 list top-level directories and key subdirectories to understand the project layout.\n\n3. **Generate AFK.md** with these sections:\n - **What This Is** \u2014 one-paragraph description of the project (language, framework, purpose)\n - **Commands** \u2014 build, test, lint, dev commands (extracted from package.json scripts, Makefile targets, etc.)\n - **Architecture** \u2014 key directories and their purpose, entry points, major subsystems\n - **Conventions** \u2014 coding style, naming patterns, anything notable from config files (strictness levels, linting rules)\n - Only include sections where you found real content. Skip empty sections.\n\n4. **Write the file** \u2014 write AFK.md to the project root. Keep it concise \u2014 under 150 lines. This file is loaded into every session, so brevity matters.\n\n## Format rules\n- Plain markdown, no YAML frontmatter\n- Use code blocks for commands\n- Use tables for directory layouts\n- Don't include boilerplate or filler \u2014 every line should earn its place",cv={name:"/init",summary:"Scan project and generate AFK.md",hint:"When you're in a fresh repo and want the model to bootstrap an AFK.md system prompt that captures conventions, commands, and architecture.",async handler(e,t){let n=lv(process.cwd(),"AFK.md"),r=lv(process.cwd(),"CLAUDE.md"),o=[];o.push({type:"text",text:dl("init",t)});let s=CN;if(av(n)&&!t.includes("--force")&&(s+=`
|
|
@@ -2149,8 +2149,8 @@ ${fU(i)}
|
|
|
2149
2149
|
`),this.client=a,this.connected=!0,this.pendingAuthTransport=void 0;let l=await sc(this.client.listTools(),s,()=>new Error(`MCP server "${this.serverName}" listTools timed out after ${s}ms`),()=>a.close().catch(()=>{})),c=this.client.getServerVersion();return{tools:l.tools,serverInfo:c?{name:c.name,version:c.version}:void 0}}async listTools(){if(!this.client)throw new Error(`McpClient(${this.serverName}): not connected`);let t=this.config.timeout??rm;return(await sc(this.client.listTools(),t,()=>new Error(`MCP server "${this.serverName}" listTools timed out after ${t}ms`))).tools}async refreshTools(){return this.listTools()}async callTool(t,n,r){if(!this.client)return{content:`MCP server "${this.serverName}" is not connected`,isError:!0};if(r.aborted)return{content:"Tool call aborted",isError:!0};let o=this.config.timeout??rm,s;try{s=await this.client.callTool({name:t,arguments:n??{}},kU,{signal:r,timeout:o})}catch(i){let a=i instanceof Error?i.message:String(i);return{content:`MCP tool "${this.serverName}.${t}" failed: ${a}`,isError:!0}}return vU(s)}async finishAuth(t){if(!this.pendingAuthTransport)throw new Error(`McpClient(${this.serverName}): no pending OAuth transport \u2014 server is not in oauth_pending state`);await this.pendingAuthTransport.finishAuth(t)}async disconnect(){if(this.pendingAuthTransport=void 0,!this.client)return;let t=this.client;this.client=void 0,this.connected=!1;try{await t.close()}catch{}}};function vU(e){let t=[];for(let r of e.content??[])if(r.type==="text")t.push(r.text);else if(r.type==="image")t.push(`[image block: mimeType=${r.mimeType}, ${r.data.length} bytes base64]`);else if(r.type==="resource"){let o="resource"in r&&typeof r.resource=="object"?r.resource.uri??"(unknown)":"(unknown)";t.push(`[resource block: ${o}]`)}else t.push(`[unknown block: ${JSON.stringify(r)}]`);let n=t.join(`
|
|
2150
2150
|
`);return{content:n.length===0?"(empty tool result)":n,...e.isError?{isError:!0}:{}}}function TU(e,t,n){let r=t.type??(t.command?"stdio":"streamable-http");return{primary:oc(e,t,n),fallback:r==="streamable-http"?()=>oc(e,{...t,type:"sse"},n):null}}function EU(e){return e instanceof wT&&(e.code===404||e.code===405)}function xU(e){return e instanceof wT?e.code:void 0}function sc(e,t,n,r){let o=null,s=new Promise((i,a)=>{o=setTimeout(()=>{if(r!==void 0)try{let l=r();l&&typeof l.then=="function"&&l.catch(()=>{})}catch{}a(n())},t)});return Promise.race([e,s]).finally(()=>{o!==null&&clearTimeout(o)})}import{createHash as RU}from"node:crypto";var ST="mcp__",kT="__",sm=64,AU=6;function Gs(e){if(e.length===0)return"_";let n=e.replace(/[^a-zA-Z0-9_-]/g,"_").replace(/_{2,}/g,"_");return n.length===0?"_":n}function _U(e){return RU("sha256").update(e).digest("hex").slice(0,AU)}function vT(e,t){let n=Gs(e),r=Gs(t),o=`${ST}${n}${kT}${r}`;if(o.length<=sm)return o;let i=`${`${ST}${_U(e)}${kT}`}${r}`;return i.length<=sm?i:i.slice(0,sm)}function zs(e){let t=new Map,n=new Map;for(let{serverName:o,toolNames:s}of e)for(let i of s){let a=vT(o,i),l={serverName:o,originalToolName:i},c=t.get(a);if(c===void 0){t.set(a,l);continue}if(c.serverName===o&&c.originalToolName===i)continue;let u=n.get(a)??[c];u.push(l),n.set(a,u)}let r=[];for(let[o,s]of n)r.push({wireName:o,pairs:s});return{tools:t,conflicts:r}}var qs=class e{records;nameRegistry;onToolsRefreshed;constructor(t){this.records=t;let n=[];for(let[o,s]of t)s.state.status==="connected"&&n.push({serverName:o,toolNames:s.tools.map(i=>i.name)});let r=zs(n);if(r.conflicts.length>0){let o=r.conflicts.map(s=>{let i=s.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");return` ${s.wireName} \u2190 ${i}`});throw new Error(`MCP tool name conflicts (rename one of the servers in mcp.json):
|
|
2151
2151
|
${o.join(`
|
|
2152
|
-
`)}`)}this.nameRegistry=r.tools}static async fromConfig(t,n={}){if(n.warnings&&n.warnings.length>0)for(let c of n.warnings)console.warn(`[mcp] ${c}`);let r=new Map,o=[],s={manager:void 0};for(let[c,u]of Object.entries(t)){let d=Gs(c);if(d!==c&&console.warn(`[mcp] server name "${c}" sanitized to "${d}" for wire encoding`),u.disabled){r.set(c,{client:void 0,tools:[],state:{serverName:c,config:u,status:"disabled",toolCount:0}});continue}let f={client:void 0,tools:[],state:{serverName:c,config:u,status:"connecting",toolCount:0}};r.set(c,f);let g=new Mo(c,u);f.client=g,g.onTransportError=b=>{f.state.status="error",f.state.error=ic(b.message,200),console.warn(`[mcp:${c}] transport error: ${b.message}`)},g.onToolListChanged=()=>{s.manager?.refreshServer(c).catch(b=>{let y=b instanceof Error?b.message:String(b);console.warn(`[mcp:${c}] refreshServer failed: ${y}`)})};let h=(async()=>{try{let{tools:b,serverInfo:y}=await g.connect();f.tools=b,f.state.status="connected",f.state.toolCount=b.length,f.state.lastListedAt=Date.now();let w=y?`${y.name}@${y.version}`:"unknown";console.log(`[mcp:${c}] connected (${w}) \u2014 ${b.length} tool(s)`)}catch(b){if(b instanceof om){f.state.status="oauth_pending",console.log(`[mcp:${c}] OAuth authorization required \u2014 check Telegram or stderr for the auth URL`);return}let y=b instanceof Error?b.message:String(b);if(f.state.status="error",f.state.error=ic(y,200),u.alwaysLoad===!0)throw new Error(`MCP server "${c}" is marked alwaysLoad but failed to connect: ${y}`);console.warn(`[mcp:${c}] connect failed: ${y}`)}})();o.push(h)}let a=(await Promise.allSettled(o)).find(c=>c.status==="rejected");if(a){for(let c of r.values())c.client&&await c.client.disconnect().catch(()=>{});throw a.reason}let l=new e(r);return s.manager=l,l}getMcpTools(){let t=[];for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);if(!s||s.state.status!=="connected")continue;let i=s.tools.find(a=>a.name===o);i&&t.push(CU(n,i))}return t}getMcpHandlers(){let t=new Map;for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);!s||s.state.status!=="connected"||t.set(n,async(i,a)=>s.client?s.client.callTool(o,i,a):{content:`MCP server "${r}" is not connected`,isError:!0})}return t}async refreshServer(t){let n=this.records.get(t);if(!n||!n.client||n.state.status!=="connected")throw new Error(`McpManager.refreshServer("${t}"): server is not connected`);let r=await n.client.refreshTools();for(let[s,i]of this.nameRegistry)i.serverName===t&&this.nameRegistry.delete(s);let o=zs([{serverName:t,toolNames:r.map(s=>s.name)}]);if(o.conflicts.length>0)for(let s of o.conflicts){let i=s.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");console.warn(`[mcp:${t}] wire-name conflict after refresh \u2014 skipping: ${s.wireName} \u2190 ${i}`)}for(let[s,i]of o.tools)this.nameRegistry.set(s,i);n.tools=r,n.state.toolCount=r.length,n.state.lastListedAt=Date.now(),console.log(`[mcp:${t}] tool list refreshed \u2014 ${r.length} tool(s)`),this.onToolsRefreshed?.(t)}getServerStates(){return[...this.records.values()].map(t=>({...t.state}))}getMcpToolWireNames(){return[...this.nameRegistry.keys()]}async completeAuth(t,n){let r=this.records.get(t);if(!r)throw new Error(`McpManager.completeAuth("${t}"): server not found`);if(r.state.status!=="oauth_pending")throw new Error(`McpManager.completeAuth("${t}"): server is not in oauth_pending state (current status: ${r.state.status})`);if(!r.client)throw new Error(`McpManager.completeAuth("${t}"): no client record \u2014 server was never connected`);await r.client.finishAuth(n),await r.client.disconnect().catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${t}] completeAuth disconnect warning: ${a}`)});let o=new Mo(t,r.state.config);o.onTransportError=i=>{r.state.status="error",r.state.error=ic(i.message,200),console.warn(`[mcp:${t}] transport error: ${i.message}`)},o.onToolListChanged=()=>{this.refreshServer(t).catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${t}] refreshServer failed: ${a}`)})},r.state.status="connecting",r.state.error=void 0,r.client=o;try{let{tools:i,serverInfo:a}=await o.connect();r.tools=i,r.state.status="connected",r.state.toolCount=i.length,r.state.lastListedAt=Date.now();let l=a?`${a.name}@${a.version}`:"unknown";console.log(`[mcp:${t}] OAuth complete \u2014 connected (${l}) \u2014 ${i.length} tool(s)`)}catch(i){let a=i instanceof Error?i.message:String(i);throw r.state.status="error",r.state.error=ic(a,200),new Error(`McpManager.completeAuth("${t}"): reconnect failed: ${a}`)}for(let[i,a]of this.nameRegistry)a.serverName===t&&this.nameRegistry.delete(i);let s=zs([{serverName:t,toolNames:r.tools.map(i=>i.name)}]);for(let[i,a]of s.tools)this.nameRegistry.set(i,a);this.onToolsRefreshed?.(t)}hasAnyConnected(){for(let t of this.records.values())if(t.state.status==="connected")return!0;return!1}size(){return this.records.size}async disconnectAll(){let t=[];for(let[n,r]of this.records)r.client&&t.push(r.client.disconnect().catch(o=>{let s=o instanceof Error?o.message:String(o);console.warn(`[mcp:${n}] disconnect error: ${s}`)}));await Promise.all(t)}};function CU(e,t){let n=t.description??`MCP tool ${t.name}`;return{name:e,description:n,input_schema:t.inputSchema}}function ic(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}H();U();import{existsSync as Ys,lstatSync as IU,readFileSync as PU,readdirSync as MU}from"node:fs";import{join as Vs}from"node:path";function ac(){return Vs(Gt(),"mcp.json")}function TT(e=process.cwd()){return Vs(e,".mcp.json")}var OU=5;function im(e=Fe()){if(!Ys(e))return[];let t=[];return ET(e,e,0,t,new Set),t}function ET(e,t,n,r,o){if(n>OU||o.has(t))return;o.add(t);let s=Vs(t,".claude-plugin","plugin.json");if(Ys(s)){let a=Vs(t,".claude-plugin","mcp.json");Ys(a)&&r.push(a);return}let i;try{i=MU(t)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=Vs(t,a),c;try{c=IU(l)}catch{continue}c.isDirectory()&&ET(e,l,n+1,r,o)}}function $U(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,error:`server "${e}" must be an object`};let n=t,r=n.type;if(r===void 0)if(typeof n.command=="string")r="stdio";else if(typeof n.url=="string")r="streamable-http";else return{ok:!1,error:`server "${e}" has no \`command\` or \`url\`; cannot infer transport`};if(r==="stdio"){if(typeof n.command!="string"||n.command.length===0)return{ok:!1,error:`stdio server "${e}" requires non-empty \`command\``}}else if(r==="streamable-http"||r==="sse"){if(typeof n.url!="string"||n.url.length===0)return{ok:!1,error:`${r} server "${e}" requires non-empty \`url\``}}else return{ok:!1,error:`server "${e}" has unsupported \`type\`: ${String(r)}`};let o={type:r};if(typeof n.command=="string"&&(o.command=n.command),Array.isArray(n.args)&&(o.args=n.args.filter(s=>typeof s=="string")),n.env!==void 0&&typeof n.env=="object"&&n.env!==null){let s={};for(let[i,a]of Object.entries(n.env))typeof a=="string"&&(s[i]=a);o.env=s}if(typeof n.url=="string"&&(o.url=n.url),n.headers!==void 0&&typeof n.headers=="object"&&n.headers!==null){let s={};for(let[i,a]of Object.entries(n.headers))typeof a=="string"&&(s[i]=a);o.headers=s}return typeof n.oauth=="boolean"&&(o.oauth=n.oauth),typeof n.disabled=="boolean"&&(o.disabled=n.disabled),typeof n.alwaysLoad=="boolean"&&(o.alwaysLoad=n.alwaysLoad),typeof n.timeout=="number"&&n.timeout>0&&(o.timeout=n.timeout),{ok:!0,config:o}}function Js(e){if(!Ys(e))return{mcpServers:{},sources:[],warnings:[]};let t=[],n;try{n=JSON.parse(PU(e,"utf-8"))}catch(i){let a=i instanceof Error?i.message:String(i);return t.push(`mcp.json at ${e}: parse error \u2014 ${a}`),{mcpServers:{},sources:[e],warnings:t}}if(n===null||typeof n!="object"||Array.isArray(n))return t.push(`mcp.json at ${e}: top-level must be an object`),{mcpServers:{},sources:[e],warnings:t};let o=n.mcpServers;if(o==null||typeof o!="object")return{mcpServers:{},sources:[e],warnings:t};let s={};for(let[i,a]of Object.entries(o)){let l=$U(i,a);l.ok?s[i]=l.config:t.push(`mcp.json at ${e}: skipping ${l.error}`)}return{mcpServers:s,sources:[e],warnings:t}}function am(e={}){let t=[],n=[];if(e.pluginsRoot!==null){let a=e.pluginsRoot,l=a?im(a):im();for(let c of l)t.push({path:c,loaded:Js(c)})}if(!e.skipUserGlobal){let a=ac();t.push({path:a,loaded:Js(a)})}if(!e.skipProjectLocal&&T.AFK_ALLOW_PROJECT_MCP!=="0"){let a=TT(e.cwd);Ys(a)&&(t.push({path:a,loaded:Js(a)}),n.push(`mcp: loaded project-local config from ${a} \u2014 set AFK_ALLOW_PROJECT_MCP=0 to disable auto-load`))}e.cliOverride!==void 0&&t.push({path:e.cliOverride,loaded:Js(e.cliOverride)});let r=new Map,o=[...n],s=[];for(let a of t){for(let l of a.loaded.warnings)o.push(l);if(a.loaded.sources.length>0)for(let l of a.loaded.sources)s.includes(l)||s.push(l);for(let[l,c]of Object.entries(a.loaded.mcpServers)){let u=r.get(l);u&&o.push(`mcp: server "${l}" defined in ${u.source} is overridden by ${a.path}`),r.set(l,{config:c,source:a.path})}}let i={};for(let[a,l]of r)i[a]=l.config;return{mcpServers:i,sources:s,warnings:o}}Za();function lm(e){return e.replace(/\bsk-ant-[A-Za-z0-9_-]{10,}/g,"sk-ant-[REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{10,}/g,"sk-[REDACTED]").replace(/Bearer\s+[A-Za-z0-9._-]{10,}/gi,"Bearer [REDACTED]").replace(/Authorization:\s*\S+/gi,"Authorization: [REDACTED]")}function Xs(e,t,n){let r=n instanceof Error?n.message:String(n);e.fn(m.warning(`\u26A0 [resume-swap] ${t}: ${lm(r)}`))}async function xT(e,t){if(t.isInFlight()===!0)return{ok:!1,reason:"A turn is in flight \u2014 wait for it to finish before resuming."};let n;try{n=t.buildSession(e)}catch(i){let a=i instanceof Error?i.message:String(i);return{ok:!1,reason:`buildSession failed: ${lm(a)}`}}let r;if(!await n.waitForInitialization().then(()=>!0,i=>(r=lm(i instanceof Error?i.message:String(i)),!1))){await n.close().catch(a=>{Xs(t.completionWriter,"new session close after init failure",a)});let i=`Session initialization failed: ${r??"unknown error"}`;return t.completionWriter.fn(m.warning(`\u26A0 ${i}`)),{ok:!1,reason:i}}await t.backgroundRegistry.cancelAll().catch(i=>{Xs(t.completionWriter,"cancelAll failed",i)}),await t.sessionRef.current.close().catch(i=>{Xs(t.completionWriter,"session close failed",i)}),t.sessionRef.current=n,e.stored?(za(t.stats,e.stored,e.resumeId),t.stats.turnCosts=[],t.stats.turnTokens=[]):(t.stats.totalTurns=0,t.stats.totalCostUsd=0,t.stats.totalTokens=0,t.stats.totalDurationMs=0,t.stats.turns=[],t.stats.sessionId=e.resumeId,t.stats.sessionStartTime=Date.now(),t.stats.turnCosts=[],t.stats.turnTokens=[]),t.stats.planMode=!1,delete t.stats.pendingPlanExit;try{t.onSwapped(e)}catch(i){Xs(t.completionWriter,"onSwapped callback threw",i)}t.contextSampler.attach(n),await Ul(n).catch(i=>{Xs(t.completionWriter,"autoRegisterPluginPassthroughs failed",i)});let s=[`\u21AA Resumed ${e.id}`];return t.stats.totalTurns>0&&s.push(`${t.stats.totalTurns} prior turn${t.stats.totalTurns===1?"":"s"}`),t.stats.totalCostUsd>0&&s.push(Le(t.stats.totalCostUsd)),t.stats.totalTokens>0&&s.push(ee(t.stats.totalTokens)+" tokens"),t.completionWriter.fn(m.brand(s.join(" \xB7 "))),qa(t.stats,t.completionWriter),t.statusLine.repaint(As(t.stats,t.contextSampler)),{ok:!0,sessionId:n.sessionId??t.stats.sessionId??e.resumeId}}function RT(e){return new st(nr({model:e.model,apiKey:le(),maxTurns:e.maxTurns,hookRegistry:e.hookRegistry,...e.systemPrompt!==void 0?{systemPrompt:e.systemPrompt}:{},...e.systemPromptSource!==void 0?{systemPromptSource:e.systemPromptSource}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.maxOutputTokens!==void 0?{maxOutputTokens:e.maxOutputTokens}:{},...e.resumeConfig,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.traceWriter!==void 0?{traceWriter:e.traceWriter}:{},...e.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:e.autoResumeOnUsageLimit}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},provider:e.provider}))}async function _T(e,t){let n=mo(e),r=fo(n),o=n?.stored?.model??e.model,s,i,a;s=Pn(e.thinking)??eo(),i=Mn(e.effort)??to(),a=ro(e.maxOutputTokens)??ks();let l=Qr()??Zr(),c=tt(),u=c.systemPromptSource,d=c.autoRouting?.interactive??!0,p=Ma(l,d,"repl"),f={current:null},g=le(),h=new Y({apiKey:g,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{}}),b=n?.stored?.sessionId,y=La(b?{sessionLabel:b}:{}),w=new ra(y?{traceWriter:y.writer}:{});qS(w);let E=c.bgSummaries===!0&&g?new nc({registry:w,apiKey:g,maxCallsPerSession:c.maxSummaryCallsPerSession??200}):void 0;E?.start(),JS(E);let v=ia(c.openaiBaseUrl!==void 0?{openaiBaseUrl:c.openaiBaseUrl}:{}),_={get sessionId(){return f.current?.sessionId},getInputStreamRef(){return f.current?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return f.current?.abortSignal??new AbortController().signal}},I=aa(o,g,v,c.baseUrl,y?.writer,w,t?.cwd),R=new xn({subagentManager:h,parentSession:_,defaultConfig:{apiKey:g,systemPrompt:l,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{}},defaultSubagentModel:In(o),childProviderFactory:v,childSkillExecutorFactory:I,backgroundRegistry:w,depth:0,...t?.cwd!==void 0?{cwd:t.cwd}:{}}),C=new Rn({parentSession:_,defaultModel:o,defaultSubagentModel:In(o),apiKey:g,childProviderFactory:v,childSkillExecutorFactory:I,backgroundRegistry:w,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},...y?.writer!==void 0?{traceWriter:y.writer}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{}}),M=new ao({parentSession:_,defaultModel:o,defaultSubagentModel:In(o),apiKey:g,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},systemPrompt:l??""}),$=new qe,x;{let $e=t?.cwd??process.cwd(),Ke=am({cwd:$e,...e.mcpConfig!==void 0?{cliOverride:e.mcpConfig}:{}}),gi=Object.values(Ke.mcpServers).filter(Wo=>!Wo.disabled).length;if(gi>0){let Wo=Ke.sources.length===1?Ke.sources[0]:`${Ke.sources.length} source(s)`;console.log(m.dim(` mcp: ${gi} server(s) from ${Wo??ac()}`)),x=await qs.fromConfig(Ke.mcpServers,{warnings:Ke.warnings})}else if(Ke.warnings.length>0)for(let Wo of Ke.warnings)console.warn(`[mcp] ${Wo}`)}let A=wa(e.provider,{subagentExecutor:R,skillExecutor:C,composeExecutor:M,memoryStore:$,model:String(o),...c.openaiBaseUrl!==void 0?{openaiBaseUrl:c.openaiBaseUrl}:{},...x!==void 0?{mcpManager:x}:{}})??new Ue({permissions:{allowedTools:[...wn,...Qn,...vt,"agent","skill","compose",...x?.getMcpToolWireNames()??[]]},subagentExecutor:R,skillExecutor:C,composeExecutor:M,memoryStore:$,surface:"cli",...x!==void 0?{mcpManager:x}:{}}),P=Na(o);n?.stored&&za(P,n.stored,n.resumeId),P.cwd=t?.cwd??process.cwd(),y&&console.log(m.dim(` trace: ${y.tracePath}`));let N={fn:$e=>console.log($e),idleFn:$e=>console.log($e)},K=new Ga,q=mT(process.stdout,{statusLine:K}),D=lo($e=>{N.fn($a($e))},"cli",$,()=>P.planMode?"plan":"default").registry,F={model:o,resumeConfig:r,systemPrompt:p,systemPromptSource:u,thinking:s,effort:i,maxOutputTokens:a,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},provider:A,hookRegistry:D,traceWriter:y?.writer,cwd:t?.cwd,maxTurns:parseInt(e.maxTurns,10),autoResumeOnUsageLimit:c.autoResumeOnUsageLimit},W=RT(F);f.current=W;let ne=new Ql,G=Ro(N),L=new ec(W),te={session:f,stats:P,out:G,ui:{clearScreen:()=>{K.stop(),L.reset(),process.stdout.write("\x1B[3J\x1B[2J\x1B[H"),K.start(),K.repaint(As(P,L))},repaintStatusLine:()=>K.repaint(As(P,L))},ledger:ne,...x!==void 0?{mcpManager:x}:{}},Te=$e=>(ne.clear(),xT($e,{sessionRef:f,stats:P,contextSampler:L,statusLine:K,backgroundRegistry:w,completionWriter:N,isInFlight:()=>Oe.getInFlight?.()??!1,onSwapped:Ke=>{Oe.resumeTarget=Ke,Oe.clearVerdictLedger?.()},buildSession:Ke=>RT({...F,model:Ke.stored?.model??F.model,resumeConfig:fo(Ke)})})),Oe={session:f,memoryStore:$,stats:P,statusLine:K,contextSampler:L,completionWriter:N,replRenderer:q,slashCtx:te,rl:null,options:e,...n!==void 0?{resumeTarget:n}:{},teardownTrustedSkillEvents:void 0,backgroundRegistry:w,...E!==void 0?{bgSummarizer:E}:{},requestResume:Te,getInFlight:()=>!1,...x!==void 0?{mcpManager:x}:{}},Me=$e=>{N.fn(mv($e,{isTTY:process.stdout.isTTY,columns:process.stdout.columns}))},ct=$e=>{N.fn(pv($e,{isTTY:process.stdout.isTTY,columns:process.stdout.columns})),ne.record($e)};wy(Me),yy(ct),Oe.teardownTrustedSkillEvents=()=>{Sy(Me),by(ct)},pT(),A instanceof Ue&&hv(A);let Pr=AT.createInterface({input:process.stdin,output:process.stdout,terminal:!1});Oe.rl=Pr;let Bo={current:null};return Oe.inputSurfaceRef=Bo,Dt.install(Ka({readLine:$e=>new Promise((Ke,gi)=>{Pr.question($e,Ke),Pr.once("close",()=>gi(new Error("readline closed")))}),writer:{line:($e="")=>process.stdout.write($e+`
|
|
2153
|
-
`)},pendingCount:()=>Dt.pendingCount(),suspendInput:()=>Bo.current?.suspendForElicitation(),resumeInput:()=>Bo.current?.resumeAfterElicitation()})),
|
|
2152
|
+
`)}`)}this.nameRegistry=r.tools}static async fromConfig(t,n={}){if(n.warnings&&n.warnings.length>0)for(let c of n.warnings)console.warn(`[mcp] ${c}`);let r=new Map,o=[],s={manager:void 0};for(let[c,u]of Object.entries(t)){let d=Gs(c);if(d!==c&&console.warn(`[mcp] server name "${c}" sanitized to "${d}" for wire encoding`),u.disabled){r.set(c,{client:void 0,tools:[],state:{serverName:c,config:u,status:"disabled",toolCount:0}});continue}let f={client:void 0,tools:[],state:{serverName:c,config:u,status:"connecting",toolCount:0}};r.set(c,f);let g=new Mo(c,u);f.client=g,g.onTransportError=b=>{f.state.status="error",f.state.error=ic(b.message,200),console.warn(`[mcp:${c}] transport error: ${b.message}`)},g.onToolListChanged=()=>{s.manager?.refreshServer(c).catch(b=>{let y=b instanceof Error?b.message:String(b);console.warn(`[mcp:${c}] refreshServer failed: ${y}`)})};let h=(async()=>{try{let{tools:b,serverInfo:y}=await g.connect();f.tools=b,f.state.status="connected",f.state.toolCount=b.length,f.state.lastListedAt=Date.now();let w=y?`${y.name}@${y.version}`:"unknown";console.log(`[mcp:${c}] connected (${w}) \u2014 ${b.length} tool(s)`)}catch(b){if(b instanceof om){f.state.status="oauth_pending",console.log(`[mcp:${c}] OAuth authorization required \u2014 check Telegram or stderr for the auth URL`);return}let y=b instanceof Error?b.message:String(b);if(f.state.status="error",f.state.error=ic(y,200),u.alwaysLoad===!0)throw new Error(`MCP server "${c}" is marked alwaysLoad but failed to connect: ${y}`);console.warn(`[mcp:${c}] connect failed: ${y}`)}})();o.push(h)}let a=(await Promise.allSettled(o)).find(c=>c.status==="rejected");if(a){for(let c of r.values())c.client&&await c.client.disconnect().catch(()=>{});throw a.reason}let l=new e(r);return s.manager=l,l}getMcpTools(){let t=[];for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);if(!s||s.state.status!=="connected")continue;let i=s.tools.find(a=>a.name===o);i&&t.push(CU(n,i))}return t}getMcpHandlers(){let t=new Map;for(let[n,{serverName:r,originalToolName:o}]of this.nameRegistry){let s=this.records.get(r);!s||s.state.status!=="connected"||t.set(n,async(i,a)=>s.client?s.client.callTool(o,i,a):{content:`MCP server "${r}" is not connected`,isError:!0})}return t}async refreshServer(t){let n=this.records.get(t);if(!n||!n.client||n.state.status!=="connected")throw new Error(`McpManager.refreshServer("${t}"): server is not connected`);let r=await n.client.refreshTools();for(let[s,i]of this.nameRegistry)i.serverName===t&&this.nameRegistry.delete(s);let o=zs([{serverName:t,toolNames:r.map(s=>s.name)}]);if(o.conflicts.length>0)for(let s of o.conflicts){let i=s.pairs.map(a=>`${a.serverName}.${a.originalToolName}`).join(", ");console.warn(`[mcp:${t}] wire-name conflict after refresh \u2014 skipping: ${s.wireName} \u2190 ${i}`)}for(let[s,i]of o.tools)this.nameRegistry.set(s,i);n.tools=r,n.state.toolCount=r.length,n.state.lastListedAt=Date.now(),console.log(`[mcp:${t}] tool list refreshed \u2014 ${r.length} tool(s)`),this.onToolsRefreshed?.(t)}getServerStates(){return[...this.records.values()].map(t=>({...t.state}))}getMcpToolWireNames(){return[...this.nameRegistry.keys()]}async completeAuth(t,n){let r=this.records.get(t);if(!r)throw new Error(`McpManager.completeAuth("${t}"): server not found`);if(r.state.status!=="oauth_pending")throw new Error(`McpManager.completeAuth("${t}"): server is not in oauth_pending state (current status: ${r.state.status})`);if(!r.client)throw new Error(`McpManager.completeAuth("${t}"): no client record \u2014 server was never connected`);await r.client.finishAuth(n),await r.client.disconnect().catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${t}] completeAuth disconnect warning: ${a}`)});let o=new Mo(t,r.state.config);o.onTransportError=i=>{r.state.status="error",r.state.error=ic(i.message,200),console.warn(`[mcp:${t}] transport error: ${i.message}`)},o.onToolListChanged=()=>{this.refreshServer(t).catch(i=>{let a=i instanceof Error?i.message:String(i);console.warn(`[mcp:${t}] refreshServer failed: ${a}`)})},r.state.status="connecting",r.state.error=void 0,r.client=o;try{let{tools:i,serverInfo:a}=await o.connect();r.tools=i,r.state.status="connected",r.state.toolCount=i.length,r.state.lastListedAt=Date.now();let l=a?`${a.name}@${a.version}`:"unknown";console.log(`[mcp:${t}] OAuth complete \u2014 connected (${l}) \u2014 ${i.length} tool(s)`)}catch(i){let a=i instanceof Error?i.message:String(i);throw r.state.status="error",r.state.error=ic(a,200),new Error(`McpManager.completeAuth("${t}"): reconnect failed: ${a}`)}for(let[i,a]of this.nameRegistry)a.serverName===t&&this.nameRegistry.delete(i);let s=zs([{serverName:t,toolNames:r.tools.map(i=>i.name)}]);for(let[i,a]of s.tools)this.nameRegistry.set(i,a);this.onToolsRefreshed?.(t)}hasAnyConnected(){for(let t of this.records.values())if(t.state.status==="connected")return!0;return!1}size(){return this.records.size}async disconnectAll(){let t=[];for(let[n,r]of this.records)r.client&&t.push(r.client.disconnect().catch(o=>{let s=o instanceof Error?o.message:String(o);console.warn(`[mcp:${n}] disconnect error: ${s}`)}));await Promise.all(t)}};function CU(e,t){let n=t.description??`MCP tool ${t.name}`;return{name:e,description:n,input_schema:t.inputSchema}}function ic(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}H();U();import{existsSync as Ys,lstatSync as IU,readFileSync as PU,readdirSync as MU}from"node:fs";import{join as Vs}from"node:path";function ac(){return Vs(Gt(),"mcp.json")}function TT(e=process.cwd()){return Vs(e,".mcp.json")}var OU=5;function im(e=Fe()){if(!Ys(e))return[];let t=[];return ET(e,e,0,t,new Set),t}function ET(e,t,n,r,o){if(n>OU||o.has(t))return;o.add(t);let s=Vs(t,".claude-plugin","plugin.json");if(Ys(s)){let a=Vs(t,".claude-plugin","mcp.json");Ys(a)&&r.push(a);return}let i;try{i=MU(t)}catch{return}for(let a of i){if(a.startsWith("."))continue;let l=Vs(t,a),c;try{c=IU(l)}catch{continue}c.isDirectory()&&ET(e,l,n+1,r,o)}}function $U(e,t){if(t===null||typeof t!="object"||Array.isArray(t))return{ok:!1,error:`server "${e}" must be an object`};let n=t,r=n.type;if(r===void 0)if(typeof n.command=="string")r="stdio";else if(typeof n.url=="string")r="streamable-http";else return{ok:!1,error:`server "${e}" has no \`command\` or \`url\`; cannot infer transport`};if(r==="stdio"){if(typeof n.command!="string"||n.command.length===0)return{ok:!1,error:`stdio server "${e}" requires non-empty \`command\``}}else if(r==="streamable-http"||r==="sse"){if(typeof n.url!="string"||n.url.length===0)return{ok:!1,error:`${r} server "${e}" requires non-empty \`url\``}}else return{ok:!1,error:`server "${e}" has unsupported \`type\`: ${String(r)}`};let o={type:r};if(typeof n.command=="string"&&(o.command=n.command),Array.isArray(n.args)&&(o.args=n.args.filter(s=>typeof s=="string")),n.env!==void 0&&typeof n.env=="object"&&n.env!==null){let s={};for(let[i,a]of Object.entries(n.env))typeof a=="string"&&(s[i]=a);o.env=s}if(typeof n.url=="string"&&(o.url=n.url),n.headers!==void 0&&typeof n.headers=="object"&&n.headers!==null){let s={};for(let[i,a]of Object.entries(n.headers))typeof a=="string"&&(s[i]=a);o.headers=s}return typeof n.oauth=="boolean"&&(o.oauth=n.oauth),typeof n.disabled=="boolean"&&(o.disabled=n.disabled),typeof n.alwaysLoad=="boolean"&&(o.alwaysLoad=n.alwaysLoad),typeof n.timeout=="number"&&n.timeout>0&&(o.timeout=n.timeout),{ok:!0,config:o}}function Js(e){if(!Ys(e))return{mcpServers:{},sources:[],warnings:[]};let t=[],n;try{n=JSON.parse(PU(e,"utf-8"))}catch(i){let a=i instanceof Error?i.message:String(i);return t.push(`mcp.json at ${e}: parse error \u2014 ${a}`),{mcpServers:{},sources:[e],warnings:t}}if(n===null||typeof n!="object"||Array.isArray(n))return t.push(`mcp.json at ${e}: top-level must be an object`),{mcpServers:{},sources:[e],warnings:t};let o=n.mcpServers;if(o==null||typeof o!="object")return{mcpServers:{},sources:[e],warnings:t};let s={};for(let[i,a]of Object.entries(o)){let l=$U(i,a);l.ok?s[i]=l.config:t.push(`mcp.json at ${e}: skipping ${l.error}`)}return{mcpServers:s,sources:[e],warnings:t}}function am(e={}){let t=[],n=[];if(e.pluginsRoot!==null){let a=e.pluginsRoot,l=a?im(a):im();for(let c of l)t.push({path:c,loaded:Js(c)})}if(!e.skipUserGlobal){let a=ac();t.push({path:a,loaded:Js(a)})}if(!e.skipProjectLocal&&T.AFK_ALLOW_PROJECT_MCP!=="0"){let a=TT(e.cwd);Ys(a)&&(t.push({path:a,loaded:Js(a)}),n.push(`mcp: loaded project-local config from ${a} \u2014 set AFK_ALLOW_PROJECT_MCP=0 to disable auto-load`))}e.cliOverride!==void 0&&t.push({path:e.cliOverride,loaded:Js(e.cliOverride)});let r=new Map,o=[...n],s=[];for(let a of t){for(let l of a.loaded.warnings)o.push(l);if(a.loaded.sources.length>0)for(let l of a.loaded.sources)s.includes(l)||s.push(l);for(let[l,c]of Object.entries(a.loaded.mcpServers)){let u=r.get(l);u&&o.push(`mcp: server "${l}" defined in ${u.source} is overridden by ${a.path}`),r.set(l,{config:c,source:a.path})}}let i={};for(let[a,l]of r)i[a]=l.config;return{mcpServers:i,sources:s,warnings:o}}Za();function lm(e){return e.replace(/\bsk-ant-[A-Za-z0-9_-]{10,}/g,"sk-ant-[REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{10,}/g,"sk-[REDACTED]").replace(/Bearer\s+[A-Za-z0-9._-]{10,}/gi,"Bearer [REDACTED]").replace(/Authorization:\s*\S+/gi,"Authorization: [REDACTED]")}function Xs(e,t,n){let r=n instanceof Error?n.message:String(n);e.fn(m.warning(`\u26A0 [resume-swap] ${t}: ${lm(r)}`))}async function xT(e,t){if(t.isInFlight()===!0)return{ok:!1,reason:"A turn is in flight \u2014 wait for it to finish before resuming."};let n;try{n=t.buildSession(e)}catch(i){let a=i instanceof Error?i.message:String(i);return{ok:!1,reason:`buildSession failed: ${lm(a)}`}}let r;if(!await n.waitForInitialization().then(()=>!0,i=>(r=lm(i instanceof Error?i.message:String(i)),!1))){await n.close().catch(a=>{Xs(t.completionWriter,"new session close after init failure",a)});let i=`Session initialization failed: ${r??"unknown error"}`;return t.completionWriter.fn(m.warning(`\u26A0 ${i}`)),{ok:!1,reason:i}}await t.backgroundRegistry.cancelAll().catch(i=>{Xs(t.completionWriter,"cancelAll failed",i)}),await t.sessionRef.current.close().catch(i=>{Xs(t.completionWriter,"session close failed",i)}),t.sessionRef.current=n,e.stored?(za(t.stats,e.stored,e.resumeId),t.stats.turnCosts=[],t.stats.turnTokens=[]):(t.stats.totalTurns=0,t.stats.totalCostUsd=0,t.stats.totalTokens=0,t.stats.totalDurationMs=0,t.stats.turns=[],t.stats.sessionId=e.resumeId,t.stats.sessionStartTime=Date.now(),t.stats.turnCosts=[],t.stats.turnTokens=[]),t.stats.planMode=!1,delete t.stats.pendingPlanExit;try{t.onSwapped(e)}catch(i){Xs(t.completionWriter,"onSwapped callback threw",i)}t.contextSampler.attach(n),await Ul(n).catch(i=>{Xs(t.completionWriter,"autoRegisterPluginPassthroughs failed",i)});let s=[`\u21AA Resumed ${e.id}`];return t.stats.totalTurns>0&&s.push(`${t.stats.totalTurns} prior turn${t.stats.totalTurns===1?"":"s"}`),t.stats.totalCostUsd>0&&s.push(Le(t.stats.totalCostUsd)),t.stats.totalTokens>0&&s.push(te(t.stats.totalTokens)+" tokens"),t.completionWriter.fn(m.brand(s.join(" \xB7 "))),qa(t.stats,t.completionWriter),t.statusLine.repaint(As(t.stats,t.contextSampler)),{ok:!0,sessionId:n.sessionId??t.stats.sessionId??e.resumeId}}function RT(e){return new st(nr({model:e.model,apiKey:le(),maxTurns:e.maxTurns,hookRegistry:e.hookRegistry,...e.systemPrompt!==void 0?{systemPrompt:e.systemPrompt}:{},...e.systemPromptSource!==void 0?{systemPromptSource:e.systemPromptSource}:{},...e.thinking!==void 0?{thinking:e.thinking}:{},...e.effort!==void 0?{effort:e.effort}:{},...e.maxOutputTokens!==void 0?{maxOutputTokens:e.maxOutputTokens}:{},...e.resumeConfig,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.traceWriter!==void 0?{traceWriter:e.traceWriter}:{},...e.autoResumeOnUsageLimit!==void 0?{autoResumeOnUsageLimit:e.autoResumeOnUsageLimit}:{},...e.baseUrl!==void 0?{baseUrl:e.baseUrl}:{},provider:e.provider}))}async function _T(e,t){let n=mo(e),r=fo(n),o=n?.stored?.model??e.model,s,i,a;s=Pn(e.thinking)??eo(),i=Mn(e.effort)??to(),a=ro(e.maxOutputTokens)??ks();let l=Qr()??Zr(),c=tt(),u=c.systemPromptSource,d=c.autoRouting?.interactive??!0,p=Ma(l,d,"repl"),f={current:null},g=le(),h=new Y({apiKey:g,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{}}),b=n?.stored?.sessionId,y=La(b?{sessionLabel:b}:{}),w=new ra(y?{traceWriter:y.writer}:{});qS(w);let E=c.bgSummaries===!0&&g?new nc({registry:w,apiKey:g,maxCallsPerSession:c.maxSummaryCallsPerSession??200}):void 0;E?.start(),JS(E);let v=ia(c.openaiBaseUrl!==void 0?{openaiBaseUrl:c.openaiBaseUrl}:{}),_={get sessionId(){return f.current?.sessionId},getInputStreamRef(){return f.current?.getInputStreamRef?.()??{pushUserMessage:()=>{}}},get abortSignal(){return f.current?.abortSignal??new AbortController().signal}},I=aa(o,g,v,c.baseUrl,y?.writer,w,t?.cwd),R=new xn({subagentManager:h,parentSession:_,defaultConfig:{apiKey:g,systemPrompt:l,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{}},defaultSubagentModel:In(o),childProviderFactory:v,childSkillExecutorFactory:I,backgroundRegistry:w,depth:0,...t?.cwd!==void 0?{cwd:t.cwd}:{}}),C=new Rn({parentSession:_,defaultModel:o,defaultSubagentModel:In(o),apiKey:g,childProviderFactory:v,childSkillExecutorFactory:I,backgroundRegistry:w,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},...y?.writer!==void 0?{traceWriter:y.writer}:{},...t?.cwd!==void 0?{cwd:t.cwd}:{}}),M=new ao({parentSession:_,defaultModel:o,defaultSubagentModel:In(o),apiKey:g,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},systemPrompt:l??""}),$=new qe,x;{let $e=t?.cwd??process.cwd(),Ke=am({cwd:$e,...e.mcpConfig!==void 0?{cliOverride:e.mcpConfig}:{}}),gi=Object.values(Ke.mcpServers).filter(Wo=>!Wo.disabled).length;if(gi>0){let Wo=Ke.sources.length===1?Ke.sources[0]:`${Ke.sources.length} source(s)`;console.log(m.dim(` mcp: ${gi} server(s) from ${Wo??ac()}`)),x=await qs.fromConfig(Ke.mcpServers,{warnings:Ke.warnings})}else if(Ke.warnings.length>0)for(let Wo of Ke.warnings)console.warn(`[mcp] ${Wo}`)}let A=wa(e.provider,{subagentExecutor:R,skillExecutor:C,composeExecutor:M,memoryStore:$,model:String(o),...c.openaiBaseUrl!==void 0?{openaiBaseUrl:c.openaiBaseUrl}:{},...x!==void 0?{mcpManager:x}:{}})??new Ue({permissions:{allowedTools:[...wn,...Qn,...vt,"agent","skill","compose",...x?.getMcpToolWireNames()??[]]},subagentExecutor:R,skillExecutor:C,composeExecutor:M,memoryStore:$,surface:"cli",...x!==void 0?{mcpManager:x}:{}}),P=Na(o);n?.stored&&za(P,n.stored,n.resumeId),P.cwd=t?.cwd??process.cwd(),y&&console.log(m.dim(` trace: ${y.tracePath}`));let N={fn:$e=>console.log($e),idleFn:$e=>console.log($e)},K=new Ga,q=mT(process.stdout,{statusLine:K}),D=lo($e=>{N.fn($a($e))},"cli",$,()=>P.planMode?"plan":"default").registry,F={model:o,resumeConfig:r,systemPrompt:p,systemPromptSource:u,thinking:s,effort:i,maxOutputTokens:a,...c.baseUrl!==void 0?{baseUrl:c.baseUrl}:{},provider:A,hookRegistry:D,traceWriter:y?.writer,cwd:t?.cwd,maxTurns:parseInt(e.maxTurns,10),autoResumeOnUsageLimit:c.autoResumeOnUsageLimit},W=RT(F);f.current=W;let ne=new Ql,G=Ro(N),L=new ec(W),ee={session:f,stats:P,out:G,ui:{clearScreen:()=>{ee.getCompositor?.()?.setOverlay(""),K.stop(),L.reset(),process.stdout.write("\x1B[3J\x1B[2J\x1B[H"),K.start(),K.repaint(As(P,L))},repaintStatusLine:()=>K.repaint(As(P,L))},ledger:ne,...x!==void 0?{mcpManager:x}:{}},Te=$e=>(ne.clear(),xT($e,{sessionRef:f,stats:P,contextSampler:L,statusLine:K,backgroundRegistry:w,completionWriter:N,isInFlight:()=>Oe.getInFlight?.()??!1,onSwapped:Ke=>{Oe.resumeTarget=Ke,Oe.clearVerdictLedger?.()},buildSession:Ke=>RT({...F,model:Ke.stored?.model??F.model,resumeConfig:fo(Ke)})})),Oe={session:f,memoryStore:$,stats:P,statusLine:K,contextSampler:L,completionWriter:N,replRenderer:q,slashCtx:ee,rl:null,options:e,...n!==void 0?{resumeTarget:n}:{},teardownTrustedSkillEvents:void 0,backgroundRegistry:w,...E!==void 0?{bgSummarizer:E}:{},requestResume:Te,getInFlight:()=>!1,...x!==void 0?{mcpManager:x}:{}},Me=$e=>{N.fn(mv($e,{isTTY:process.stdout.isTTY,columns:process.stdout.columns}))},ct=$e=>{N.fn(pv($e,{isTTY:process.stdout.isTTY,columns:process.stdout.columns})),ne.record($e)};wy(Me),yy(ct),Oe.teardownTrustedSkillEvents=()=>{Sy(Me),by(ct)},pT(),A instanceof Ue&&hv(A);let Pr=AT.createInterface({input:process.stdin,output:process.stdout,terminal:!1});Oe.rl=Pr;let Bo={current:null};return Oe.inputSurfaceRef=Bo,Dt.install(Ka({readLine:$e=>new Promise((Ke,gi)=>{Pr.question($e,Ke),Pr.once("close",()=>gi(new Error("readline closed")))}),writer:{line:($e="")=>process.stdout.write($e+`
|
|
2153
|
+
`)},pendingCount:()=>Dt.pendingCount(),suspendInput:()=>Bo.current?.suspendForElicitation(),resumeInput:()=>Bo.current?.resumeAfterElicitation()})),ee.requestResume=Te,Oe}H();import{promises as Zs}from"node:fs";import*as IT from"node:os";import*as lc from"node:path";async function CT(e,t,n=!1){await Zs.mkdir(e,{recursive:!0});let r=new Date().toISOString().replace(/[:.]/g,"-"),o=lc.join(e,`${r}.md`),s=n?" (continued)":"";return await Zs.writeFile(o,`# Session \u2014 ${new Date().toISOString()}${s}
|
|
2154
2154
|
|
|
2155
2155
|
- model: ${t}
|
|
2156
2156
|
|
|
@@ -2182,12 +2182,12 @@ _ended: ${new Date().toISOString()}_
|
|
|
2182
2182
|
`)+`
|
|
2183
2183
|
`,l=await cm(t,um|dm|NU|pm,384);try{await l.writeFile(a)}finally{await l.close()}kr=Qs}})}async function LT(e){if(e.initialBuffer!==void 0&&e.initialBuffer.length>0)return{text:e.initialBuffer,attachments:[]};let t=null;if(e.onSigint){let n=e.onSigint;t=()=>n(),process.on("SIGINT",t)}try{return{text:await bk({rl:e.rl,promptFn:e.promptFn}),attachments:[]}}finally{t&&process.removeListener("SIGINT",t)}}import{emitKeypressEvents as GU}from"readline";import*as lt from"ansi-escapes";import mm from"string-width";var HU="\x1B[?2004h",KU="\x1B[?2004l";function FT(e,t){let n=e.isRaw;e.setRawMode(!0),e.resume(),t.write(HU);let r=!1;return{restore(){if(!r){r=!0;try{t.write(KU)}catch{}try{e.setRawMode(n)}catch{}}}}}function uc(){let e={dropdownOpen:!1,candidates:[],selectedIndex:0,viewportStart:0,suppressedSignature:null,trigger:null,reset(){e.dropdownOpen=!1,e.candidates=[],e.selectedIndex=0,e.viewportStart=0,e.suppressedSignature=null,e.trigger=null}};return e}async function NT(e){let t=process.stdin,n=process.stdout,r=e.compositor?.isArmed()?{restore:()=>{}}:FT(t,n),o=e.statusLine?.getExtraRows()??0;GU(t);let s=e.promptFn(),i=mm(Ce(s)),a=null,l=null;try{return e.statusLine?.setExtraRows(o+1),await new Promise((c,u)=>{let d=j.seed(e.initialBuffer??""),p=e.autocompleteState??uc();p.reset();let f=0,g=!1,h=!1,b=0,y=0,w=0,k=null,E=[],v=6,_=0,I=!1,R=8,C={has:q=>Xe().some(D=>D.name===`/${q}`)},M=()=>{if((w>0||y>0)&&n.write(lt.cursorUp(w+y)),n.write("\r"),n.write(lt.eraseDown),E.length>0)n.write($s(E)+`
|
|
2184
2184
|
`),w=1;else if(k!==null){let L=k;k=null,n.write(L+`
|
|
2185
|
-
`),w=1}else w=0;n.write(s+Ln(d.buffer,C)),p.trigger=Ms(d.buffer,d.cursor);let q=`${d.cursor}:${d.buffer}`;p.suppressedSignature!==null&&p.suppressedSignature!==q&&(p.suppressedSignature=null),p.trigger&&p.suppressedSignature===null?(p.trigger.kind==="slash"?p.candidates=gl(p.trigger.query).slice(0,12):p.trigger.kind==="file"?p.candidates=hl(p.trigger.query).slice(0,12):p.candidates=Os(p.trigger.command,p.trigger.query),p.dropdownOpen=p.candidates.length>0):(p.dropdownOpen=!1,p.candidates=[]),p.selectedIndex>=p.candidates.length&&(p.selectedIndex=Math.max(0,p.candidates.length-1)),p.viewportStart>p.selectedIndex&&(p.viewportStart=p.selectedIndex),p.selectedIndex>=p.viewportStart+v&&(p.viewportStart=p.selectedIndex-v+1);let D=n.columns||80;if(f=0,p.dropdownOpen&&D>40){let L=Math.min(D-4,60),
|
|
2185
|
+
`),w=1}else w=0;n.write(s+Ln(d.buffer,C)),p.trigger=Ms(d.buffer,d.cursor);let q=`${d.cursor}:${d.buffer}`;p.suppressedSignature!==null&&p.suppressedSignature!==q&&(p.suppressedSignature=null),p.trigger&&p.suppressedSignature===null?(p.trigger.kind==="slash"?p.candidates=gl(p.trigger.query).slice(0,12):p.trigger.kind==="file"?p.candidates=hl(p.trigger.query).slice(0,12):p.candidates=Os(p.trigger.command,p.trigger.query),p.dropdownOpen=p.candidates.length>0):(p.dropdownOpen=!1,p.candidates=[]),p.selectedIndex>=p.candidates.length&&(p.selectedIndex=Math.max(0,p.candidates.length-1)),p.viewportStart>p.selectedIndex&&(p.viewportStart=p.selectedIndex),p.selectedIndex>=p.viewportStart+v&&(p.viewportStart=p.selectedIndex-v+1);let D=n.columns||80;if(f=0,p.dropdownOpen&&D>40){let L=Math.min(D-4,60),ee=Math.min(p.candidates.length-p.viewportStart,v);for(let Me=0;Me<ee;Me++){let ct=p.viewportStart+Me,Pr=ml(p.candidates[ct],ct===p.selectedIndex,L,p.trigger?.kind);n.write(`
|
|
2186
2186
|
`+Pr);let Bo=mm(Ce(Pr));f+=Math.max(1,Math.ceil(Bo/D))}let Te=Math.min(D-4,80),Oe=fl(p.candidates[p.selectedIndex]?.hint,Te);if(Oe!==null){n.write(`
|
|
2187
2187
|
`+Oe);let Me=mm(Ce(Oe));f+=Math.max(1,Math.ceil(Me/D))}}let F=up(d.buffer,i,D),{row:W,col:ne}=$n(d.buffer,d.cursor,i,D),G=Math.max(0,F-W+f);G>0&&n.write(lt.cursorUp(G)),n.write("\r"),ne>0&&n.write(lt.cursorForward(ne)),y=F},$=!1,x=()=>{I||(I=!0,setImmediate(()=>{I&&!$&&(I=!1,M())}))};M();let A=()=>{let q=p.candidates[p.selectedIndex];if(!q)return!1;let D=d.buffer.slice(0,d.cursor),F=d.buffer.slice(d.cursor),W,ne;if(p.trigger?.kind==="slash"){let G=/\/[A-Za-z_-]*$/.exec(D);W=G?D.length-G[0].length:d.cursor,ne=q.value+(F.startsWith(" ")?"":" ")}else if(p.trigger?.kind==="flag"){let G=/--[a-z0-9-]*$/.exec(D);W=G?D.length-G[0].length:d.cursor,ne=q.value+(F.startsWith(" ")?"":" ")}else{let G=D.search(/[^\s]*$/);W=G>=0?G:d.cursor,ne=q.value}return d=j.replaceRange(d,{start:W,end:d.cursor},ne),p.dropdownOpen=!1,p.viewportStart=0,p.selectedIndex=0,M(),!0},P=()=>{(w>0||y>0)&&n.write(lt.cursorUp(w+y)),n.write("\r"),n.write(lt.eraseDown),f=0;let q=cr({buffer:Ln(d.buffer,C),promptText:s,isTTY:!!n.isTTY,attachmentSummary:bo(E)}),D=()=>n.write(q+`
|
|
2188
2188
|
`);e.statusLine?.withFullScrollRegion?e.statusLine.withFullScrollRegion(D):D(),K(),c({text:d.buffer,attachments:[...E]}),y=0},N=q=>{y>0&&n.write(lt.cursorUp(y)),f>0&&(n.write(lt.eraseDown),f=0),n.write(`
|
|
2189
2189
|
`),K(),u(q),y=0},K=()=>{$=!0,a&&t.removeListener("keypress",a),l&&l(),a=null,l=null};a=(q,D)=>{let F=Date.now(),W=F-_<R;_=F;let ne=D?.sequence||"";if(ne==="\x1B[200~"){g=!0,b=d.buffer.length;return}if(ne==="\x1B[201~"){g=!1,d.buffer.length===b?h||(h=!0,mr().then(L=>{L?(k=null,E.push(L)):k="[clipboard: no image found]",x()}).catch(()=>{}).finally(()=>{h=!1})):(M(),h||(h=!0,mr().then(L=>{L&&(k=null,E.push(L),x())}).catch(()=>{}).finally(()=>{h=!1})));return}if(D?.ctrl&&D?.name==="c"){e.onSigint?e.onSigint():N(new Error("SIGINT"));return}if(D?.ctrl&&D?.name==="d"){d.buffer.length===0&&((w>0||y>0)&&n.write(lt.cursorUp(w+y)),f>0&&(n.write(lt.eraseDown),f=0),n.write(`
|
|
2190
|
-
`),K(),c({text:"",attachments:[...E]}),y=0);return}if(D?.ctrl&&D?.name==="v"){h||(h=!0,mr().then(L=>{L?(k=null,E.push(L)):k="[clipboard: no image found]",x()}).catch(()=>{}).finally(()=>{h=!1}));return}if(D?.name==="escape"){p.dropdownOpen&&(p.suppressedSignature=`${d.cursor}:${d.buffer}`,p.dropdownOpen=!1,p.candidates=[],M());return}if(D?.ctrl&&D?.name==="a"){let L=j.moveLineStart(d);L!==d&&(d=L,M());return}if(D?.ctrl&&D?.name==="e"){let L=j.moveLineEnd(d);L!==d&&(d=L,M());return}if(D?.ctrl&&D?.name==="b"){let L=j.moveLeft(d);L!==d&&(d=L,M());return}if(D?.ctrl&&D?.name==="f"){let L=j.moveRight(d);L!==d&&(d=L,M());return}if(D?.meta&&D?.name==="b"){let L=j.moveWordBackward(d);L!==d&&(d=L,M());return}if(D?.meta&&D?.name==="f"){let L=j.moveWordForward(d);L!==d&&(d=L,M());return}if(D?.ctrl&&D?.name==="w"){let L=j.deleteWordBackward(d);L!==d&&(d=L,e.history?.resetRecall(),M());return}if(D?.ctrl&&D?.name==="l"){y=0,w=0,n.write("\x1B[H\x1B[2J"),M();return}if(D?.ctrl&&D?.name==="p"||D?.name==="up"){if(p.dropdownOpen){p.selectedIndex>0&&(p.selectedIndex--,p.selectedIndex<p.viewportStart&&(p.viewportStart=p.selectedIndex),M());return}let L=n.columns||80,
|
|
2190
|
+
`),K(),c({text:"",attachments:[...E]}),y=0);return}if(D?.ctrl&&D?.name==="v"){h||(h=!0,mr().then(L=>{L?(k=null,E.push(L)):k="[clipboard: no image found]",x()}).catch(()=>{}).finally(()=>{h=!1}));return}if(D?.name==="escape"){p.dropdownOpen&&(p.suppressedSignature=`${d.cursor}:${d.buffer}`,p.dropdownOpen=!1,p.candidates=[],M());return}if(D?.ctrl&&D?.name==="a"){let L=j.moveLineStart(d);L!==d&&(d=L,M());return}if(D?.ctrl&&D?.name==="e"){let L=j.moveLineEnd(d);L!==d&&(d=L,M());return}if(D?.ctrl&&D?.name==="b"){let L=j.moveLeft(d);L!==d&&(d=L,M());return}if(D?.ctrl&&D?.name==="f"){let L=j.moveRight(d);L!==d&&(d=L,M());return}if(D?.meta&&D?.name==="b"){let L=j.moveWordBackward(d);L!==d&&(d=L,M());return}if(D?.meta&&D?.name==="f"){let L=j.moveWordForward(d);L!==d&&(d=L,M());return}if(D?.ctrl&&D?.name==="w"){let L=j.deleteWordBackward(d);L!==d&&(d=L,e.history?.resetRecall(),M());return}if(D?.ctrl&&D?.name==="l"){y=0,w=0,n.write("\x1B[H\x1B[2J"),M();return}if(D?.ctrl&&D?.name==="p"||D?.name==="up"){if(p.dropdownOpen){p.selectedIndex>0&&(p.selectedIndex--,p.selectedIndex<p.viewportStart&&(p.viewportStart=p.selectedIndex),M());return}let L=n.columns||80,ee=j.moveUpLine(d,L,i);if(ee.moved)d=ee.state,e.history?.resetRecall(),M();else if(e.history){let Te=e.history.back(d.buffer);Te!==null&&(d=j.seed(Te),M())}return}if(D?.ctrl&&D?.name==="n"||D?.name==="down"){if(p.dropdownOpen){p.selectedIndex<p.candidates.length-1&&(p.selectedIndex++,p.selectedIndex>=p.viewportStart+v&&(p.viewportStart=p.selectedIndex-v+1),M());return}let L=n.columns||80,ee=j.moveDownLine(d,L,i);if(ee.moved)d=ee.state,e.history?.resetRecall(),M();else if(e.history){let Te=e.history.forward();Te!==null&&(d=j.seed(Te),M())}return}if(D?.name==="left"){let L=j.moveLeft(d);L!==d&&(d=L,M());return}if(D?.name==="right"){let L=j.moveRight(d);L!==d&&(d=L,M());return}if(D?.name==="home"){let L=j.moveHome(d);L!==d&&(d=L,M());return}if(D?.name==="end"){let L=j.moveEnd(d);L!==d&&(d=L,M());return}if(D?.ctrl&&D?.name==="u"){let L=j.deleteToLineStart(d);L!==d&&(d=L,e.history?.resetRecall(),M());return}if(D?.ctrl&&D?.name==="k"){let L=j.deleteToLineEnd(d);L!==d&&(d=L,e.history?.resetRecall(),M());return}if(D?.ctrl&&D?.name==="x"){E.length>0&&(E.pop(),M());return}if(D?.name==="backspace"){if(D?.meta){let ee=j.deleteWordBackward(d);ee!==d&&(d=ee,e.history?.resetRecall(),M());return}let L=j.backspace(d);L!==d?(d=L,e.history?.resetRecall(),M()):E.length>0&&(E.pop(),M());return}if(D?.name==="delete"){if(D?.meta){let ee=j.deleteWordForward(d);ee!==d&&(d=ee,e.history?.resetRecall(),M());return}let L=j.deleteForward(d);L!==d&&(d=L,e.history?.resetRecall(),M());return}if(D?.name==="return"){let L=D?.shift===!0||ne==="\x1B[13;2u",ee=D?.meta===!0;if(L||ee){d=j.insert(d,`
|
|
2191
2191
|
`),e.history?.resetRecall(),M();return}if(g){d=j.insert(d,`
|
|
2192
2192
|
`);return}if(W){d=j.insert(d,`
|
|
2193
2193
|
`),x();return}if(p.dropdownOpen){let Te=p.trigger?.kind,Oe=A();Te==="slash"&&Oe&&P()}else d.buffer.endsWith("\\")?(d=j.replaceRange(d,{start:d.buffer.length-1,end:d.buffer.length},`
|
|
@@ -2198,10 +2198,10 @@ _ended: ${new Date().toISOString()}_
|
|
|
2198
2198
|
`).find(b=>b.trim().length>0)?.trim()??"",g=f.length>0?f:`${e.kind} (no structured fields)`,h=ae(fn(g),n).split(`
|
|
2199
2199
|
`);for(let b of h)d.push(i+" "+Ae(b,n)+" "+i)}else for(let f of l){let g=m.dim(Ae(f.label,c)),h=ae(fn(f.value),u).split(`
|
|
2200
2200
|
`),b=h[0]??"";d.push(i+" "+g+" "+Ae(b,u)+" "+i);for(let y of h.slice(1))d.push(i+" "+" ".repeat(c)+" "+Ae(y,u)+" "+i)}d.push(a);let p=m.dim(ue(t.affordance,n));return d.push(i+" "+Ae(p,n)+" "+i),d.push(s),d.join(`
|
|
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(ee(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 ~${ee(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 ${ee(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(`${ee(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+`
|
|
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.1"}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';
|
|
@@ -2231,7 +2231,7 @@ Run \`afk i\` then \`/resume\` to list saved sessions.
|
|
|
2231
2231
|
`),process.exitCode=1;return}let r=tt(),o=T.AFK_WORKTREE_BRANCH_PREFIX??r.interactive?.worktreeBranchPrefix,s=T.AFK_WORKTREE_BOOT_PRUNE==="0",i=await YT({disabled:s}),a,l;if(t.worktree!==void 0)try{l=await ya(t.worktree,o!==void 0?{branchPrefix:o}:void 0),a=l.path,n.text=`Worktree ready at ${l.path} (branch: ${l.branch})`}catch(x){n.fail("Worktree setup failed"),B(x)}let c=i.ran&&i.removedCount>0?`Pruned ${i.removedCount} stale worktree(s). Run /worktree list for details.`:void 0,u;try{u=await _T(t,a!==void 0?{cwd:a}:void 0)}catch(x){n.fail("Invalid options"),B(x)}let d=XB(t,r),p=le();if(l!==void 0&&t.worktree===!0&&d&&p!==void 0){let x=l;u.firstTurnHook=async A=>{let P=await QT({handle:x,message:A,token:p,session:u.session.current,...o!==void 0?{branchPrefix:o}:{}});if(P.status==="renamed")console.log(m.dim("\u21AA ")+`Renamed \u2192 ${vr.relative(process.cwd(),P.newPath)||P.newPath} `+m.dim(`(branch: ${P.newBranch})`));else if(P.status==="failed"){let N=P.partial==="branch"?" (worktree dir moved, branch rename failed)":"";console.warn(m.warning("\u26A0 ")+`Worktree auto-rename failed${N}: ${P.reason}. `+m.dim("Continuing with the original name."))}else{let N=YB(P.reason,P.detail);N!==void 0&&console.log(m.dim("\u21AA ")+`Worktree auto-rename skipped (${N}). `+m.dim("Keeping timestamp name."))}}}ir(async()=>{u.teardownTrustedSkillEvents?.(),Dt.uninstall(),u.bgSummarizer?.stop(),await u.backgroundRegistry.cancelAll().catch(()=>{}),await u.session.current.close(),u.mcpManager&&await u.mcpManager.disconnectAll(),u.memoryStore.close(),l!==void 0&&await l.cleanup({force:u.stats.totalTurns===0})}),n.succeed("Session ready"),l!==void 0&&console.log(m.dim(" \u21AA worktree: ")+m.dim(Ba(l.path,{maxWidth:60}))+m.dim(` (branch: ${l.branch})`));let f=await PT(()=>u.stats.model);console.log(m.dim(` transcript: ${f.path()}`)),ir(async()=>{await f.appendEnded()});let g=!1,h=()=>{if(u.stats.totalTurns===0)return;let x=uo(u.stats);return g=!0,x};ir(async()=>{if(!g)try{h()}catch{}});let b={turnInFlight:!1,lastSigintAt:0};u.getInFlight=()=>b.turnInFlight;let y=1500,w=()=>{let x=Date.now();if(b.turnInFlight){u.session.current.interrupt().catch(()=>{}),b.lastSigintAt=x,b.notifyInterrupting?.(!0);let A=`
|
|
2232
2232
|
`+m.warning("\u26A0 Interrupted. Press Ctrl+C again to exit."),P=b.activeCompositor;if(P&&P.isArmed())try{P.commitAbove(A)}catch{console.log(A)}else console.log(A);return}if(x-b.lastSigintAt<y){u.session.current?.abort("sigint"),u.rl.close();return}b.lastSigintAt=x,console.log(`
|
|
2233
2233
|
`+m.info("\u2139 ")+"Press Ctrl+C again (or /exit) to quit.")};process.on("SIGINT",w),ir(async()=>{process.removeListener("SIGINT",w)});let k=!1,E=()=>{if(k)return;k=!0,u.session.current?.abort("sigterm");try{u.rl.close()}catch{}setTimeout(()=>{Ua().finally(()=>process.exit(0))},2e3).unref()};process.on("SIGTERM",E),ir(async()=>{process.removeListener("SIGTERM",E)});let v=!1,_=()=>{if(v)return;v=!0,u.session.current?.abort("sighup");try{u.rl.close()}catch{}setTimeout(()=>{Ua().finally(()=>process.exit(0))},2e3).unref()};process.on("SIGHUP",_),ir(async()=>{process.removeListener("SIGHUP",_)}),process.stdout.write("\x1B[3J\x1B[2J\x1B[H");let I=1,R=process.stdout.write.bind(process.stdout),C=process.stderr.write.bind(process.stderr),M=x=>(typeof x=="string"?x:x instanceof Uint8Array?Buffer.from(x).toString("utf8"):String(x)).match(/\n/g)?.length??0,$=x=>((A,...P)=>(I+=M(A),x(A,...P)));process.stdout.write=$(R),process.stderr.write=$(C);try{if(gc!==null){let{updateInfo:A,pendingMessage:P}=gc;gc=null,P!==null&&process.stderr.write(P),A!==null&&fc(A)}let x=u.resumeTarget?`Resuming ${u.resumeTarget.id} \xB7 ${u.stats.totalTurns} prior turn${u.stats.totalTurns===1?"":"s"}`:void 0;console.log(`
|
|
2234
|
-
`+Gf({mode:"Interactive Mode",model:u.stats.model,version:an(),...l!==void 0?{worktree:l.branch}:{},cwd:a??process.cwd(),...x!==void 0?{metaLine:x}:{},hintLine:"/help \xB7 /model \xB7 /resume \xB7 Esc to interrupt \xB7 /exit to quit"})),c!==void 0&&console.log(m.dim(` ${c}`)),u.resumeTarget&&qa(u.stats,u.completionWriter),console.log()}finally{process.stdout.write=R,process.stderr.write=C}u.preArmAnchorRow=I,u.statusLine.start(),u.slashCtx.ui.repaintStatusLine(),u.rl.on("close",async()=>{u.statusLine.stop(),ZB(u,l,h),console.log(m.info("\u2139 ")+"Goodbye!"),await Ua(),process.exit(0)}),await JT(u,f,b,w)})}function ZB(e,t,n){if(e.stats.totalTurns===0)return;console.log(ge("Session Summary"));let r=[`${e.stats.totalTurns} turn${e.stats.totalTurns===1?"":"s"}`,se(Date.now()-e.stats.sessionStartTime)];e.stats.totalCostUsd>0&&r.push(Le(e.stats.totalCostUsd)),e.stats.totalTokens>0&&r.push(
|
|
2234
|
+
`+Gf({mode:"Interactive Mode",model:u.stats.model,version:an(),...l!==void 0?{worktree:l.branch}:{},cwd:a??process.cwd(),...x!==void 0?{metaLine:x}:{},hintLine:"/help \xB7 /model \xB7 /resume \xB7 Esc to interrupt \xB7 /exit to quit"})),c!==void 0&&console.log(m.dim(` ${c}`)),u.resumeTarget&&qa(u.stats,u.completionWriter),console.log()}finally{process.stdout.write=R,process.stderr.write=C}u.preArmAnchorRow=I,u.statusLine.start(),u.slashCtx.ui.repaintStatusLine(),u.rl.on("close",async()=>{u.statusLine.stop(),ZB(u,l,h),console.log(m.info("\u2139 ")+"Goodbye!"),await Ua(),process.exit(0)}),await JT(u,f,b,w)})}function ZB(e,t,n){if(e.stats.totalTurns===0)return;console.log(ge("Session Summary"));let r=[`${e.stats.totalTurns} turn${e.stats.totalTurns===1?"":"s"}`,se(Date.now()-e.stats.sessionStartTime)];e.stats.totalCostUsd>0&&r.push(Le(e.stats.totalCostUsd)),e.stats.totalTokens>0&&r.push(te(e.stats.totalTokens)+" tokens"),console.log(m.dim(" "+r.join(" \xB7 ")));let o=t?vr.basename(t.path):"none";console.log(m.dim(` model: ${e.stats.model} \xB7 worktree: ${o}`));try{let i=e.stats.cwd??process.cwd(),l=JB("git",["diff","--shortstat","HEAD"],{cwd:i,encoding:"utf8",timeout:2e3}).trim();console.log(m.dim(` edits: ${l||"no files changed"}`))}catch{}let s=e.stats.sessionId;try{let i=n();!s&&i&&(s=vr.basename(i,".json"))}catch{}s&&console.log(m.dim(" Continue with: ")+m.brand(go(s,e.stats.model))),console.log()}H();import QB from"ora";function uE(e){e.command("status").description("Check agent connection status").option("-f, --format <format>","Output format (text|json)","text").action(async t=>{let n=QB("Checking status...").start();try{let r=Ye(),o=Ee(r),s=kd(r),i=o==="openai-compatible"||o==="openai-codex";if(await new st({model:i?"gpt-4o-mini":"haiku",...s!==void 0?{apiKey:s}:{},maxTurns:1}).close(),n.succeed(`${o} provider reachable`),t.format==="json"){let l=le(),c=Ss(),u=l?T.ANTHROPIC_API_KEY?"ANTHROPIC_API_KEY":"CLAUDE_CODE_OAUTH_TOKEN":null,d=c?T.OPENAI_API_KEY?"OPENAI_API_KEY":"CODEX_API_KEY":null;console.log(JSON.stringify({providers:{anthropic:{ok:!!l,source:u},codex:{ok:!!c,source:d}},model:String(r),bypass:!0},null,2))}else console.log(`
|
|
2235
2235
|
`+Uf("Agent AFK \xB7 Status",[{label:"Provider",value:o,kind:"info"},{label:"Auth",value:i?s?"Found (OPENAI_API_KEY / CODEX_API_KEY)":"Reading ~/.codex/auth.json (run `afk provider auth diagnose`)":s?"Found (ANTHROPIC_API_KEY)":"Falling back to Claude OAuth",kind:s?"ok":"warn"},{label:"Model",value:String(r),kind:"info"},{label:"Bypass",value:"Permissions disabled",kind:"warn"}])+`
|
|
2236
2236
|
`)}catch(r){n.fail("Connection failed"),B(r)}})}H();function dE(e){e.command("config").description("View current configuration").option("-f, --format <format>","Output format (text|json)","text").action(t=>{let n=T.AFK_MODEL??T.CLAUDE_MODEL,r=n??"sonnet",o=Ee(n),s=T.ANTHROPIC_API_KEY||T.CLAUDE_CODE_OAUTH_TOKEN,i=T.OPENAI_API_KEY||T.CODEX_API_KEY,a=o==="anthropic"?s:i,l=s?T.ANTHROPIC_API_KEY?"ANTHROPIC_API_KEY":"CLAUDE_CODE_OAUTH_TOKEN":null,c=i?T.OPENAI_API_KEY?"OPENAI_API_KEY":"CODEX_API_KEY":null;if(t.format==="json")console.log(JSON.stringify({model:r,provider:o,apiKey:{present:!!a,source:o==="anthropic"?l:c},thinking:T.AFK_THINKING||null,effort:T.AFK_EFFORT||null,bypass:!0,raw_env:{AFK_MODEL:T.AFK_MODEL??null,AFK_THINKING:T.AFK_THINKING??null,AFK_EFFORT:T.AFK_EFFORT??null,ANTHROPIC_API_KEY:T.ANTHROPIC_API_KEY?"set":"unset",CLAUDE_CODE_OAUTH_TOKEN:T.CLAUDE_CODE_OAUTH_TOKEN?"set":"unset",OPENAI_API_KEY:T.OPENAI_API_KEY?"set":"unset",CODEX_API_KEY:T.CODEX_API_KEY?"set":"unset"}},null,2));else{console.log(m.info(`\u{1F4CB} Current Configuration:
|
|
2237
2237
|
`)),console.log(` Model: ${m.info(n?r:r+" (default)")}`),console.log(` Provider: ${m.plan(o)}`),console.log(o==="anthropic"?` API Key: ${a?m.success("\u2713 Set (ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN)"):m.warning("\u26A0 Not set \u2014 subprocess will fall back to OAuth / keychain")}`:` API Key: ${a?m.success("\u2713 Set (OPENAI_API_KEY / CODEX_API_KEY)"):m.warning("\u26A0 Not set \u2014 falling back to `codex login` state")}`);let u=T.AFK_THINKING||"(unset \u2014 SDK default)";console.log(` Thinking: ${m.info(u)}`);let d=T.AFK_EFFORT||"(unset \u2014 SDK default)";console.log(` Effort: ${m.info(d)}`),console.log(` Bypass Permissions: ${m.warning("true (enabled)")}`),console.log(m.meta(`
|