// @bun
import{Ia as j,Ja as _e,Ka as R,Na as ue}from"./chunk-vgcxarg8.js";import{$a as Lo,Oa as Ao,Ua as $o,Wa as Wo,Ya as Ko,Za as Xo,_a as Zo}from"./chunk-pyghqftx.js";import{ab as ir}from"./chunk-25h2ccq7.js";import"./chunk-910vkvsf.js";import{rb as Jo}from"./chunk-qaknq49b.js";import"./chunk-8095zpgy.js";import{Mc as E,Nf as pe,Xc as B,pf as se,vf as ne}from"./chunk-hqvcxwes.js";import"./chunk-dc4d6g7j.js";import{uj as ge}from"./chunk-vs8xggw3.js";import{Aj as go,Dj as Ho,vj as U,wj as re,xj as ye}from"./chunk-wmhmg5fw.js";import"./chunk-b0x7wzag.js";import"./chunk-e39gegdb.js";import{Jj as he,Mj as te}from"./chunk-gmt7f7kk.js";import"./chunk-qysx0asq.js";import"./chunk-c5jsd4mw.js";import"./chunk-9k6sqsj1.js";import"./chunk-2150ew87.js";import"./chunk-6mn8xp1g.js";import{zo as fe}from"./chunk-2szzt9yn.js";import{qq as Z,sq as J}from"./chunk-vcm8340w.js";import"./chunk-5sm3bawt.js";import"./chunk-439fnydv.js";import{ht as lo}from"./chunk-h4nqzdt7.js";import{At as ke,Ct as L}from"./chunk-g2rmdpb3.js";import"./chunk-fjf6txcy.js";import"./chunk-m9a3r7rv.js";import"./chunk-qze335a6.js";import"./chunk-0dcnzv90.js";import"./chunk-ecs98jj1.js";import"./chunk-kmd1ghec.js";import"./chunk-hzdm0yt0.js";import"./chunk-ajc5mn2j.js";import"./chunk-fgfsckqx.js";import"./chunk-6vd03edf.js";import{Cy as X,VA as M,bD as w}from"./chunk-bt9y3st3.js";import"./chunk-x3d5kerf.js";import"./chunk-vk8psqqh.js";import{PG as uo}from"./chunk-xyhgvt88.js";import q from"path";var ro=["markdown","table","text","reasoning","bash","write","edit","patch","task","todo","question","error","mix"],to=["edit","bash","read","task","external","doom"],so=["multi","single","checklist","custom"];function Ee(o){let e=(o||"edit").toLowerCase();return to.find((r)=>r===e)}function Re(o){let e=(o||"multi").toLowerCase();return so.find((r)=>r===e)}var eo=["# Direct Mode Demo","","This is a realistic assistant response for direct-mode formatting checks.","It mixes **bold**, _italic_, `inline code`, links, code fences, and tables in one streamed reply.","","## Summary","","- Restored the final markdown flush so the last block is committed on idle.","- Switched markdown scrollback commits back to top-level block boundaries.","- Added footer-level regression coverage for split-footer rendering.","","## Status","","| Area | Before | After | Notes |","| --- | --- | --- | --- |","| Direct mode | Missing final rows | Stable | Final markdown block now flushes on idle |","| Tables | Dropped in streaming mode | Visible | Block-based commits match the working OpenTUI demo |","| Tests | Partial coverage | Broader coverage | Includes a footer-level split render capture |","","> This sample intentionally includes a wide table so you can spot wrapping and commit bugs quickly.","","```ts","const result = { markdown: true, tables: 2, stable: true }","```","","## Files","","| File | Change |","| --- | --- |","| `scrollback.surface.ts` | Align markdown commit logic with the split-footer demo |","| `footer.ts` | Keep active surfaces across footer-height-only resizes |","| `footer.test.ts` | Capture real split-footer markdown payloads during idle completion |","","Next step: run `/fmt table` if you want a tighter table-only sample."].join(`
`),Ae=["# Table Sample","","| Kind | Example | Notes |","| --- | --- | --- |","| Pipe | `A\\|B` | Escaped pipes should stay in one cell |","| Unicode | `\u6F22\u5B57` | Wide characters should remain aligned |","| Wrap | `LongTokenWithoutNaturalBreaks_1234567890` | Useful for width stress |","| Status | done | Final row should still appear after idle |"].join(`
`);function Q(o,e){o.append({kind:"system",text:e,phase:"start",source:"system"})}function $e(o){o.event({type:"stream.subagent",state:{tabs:[],details:{},permissions:[],questions:[]}})}function We(o,e){o.footer.event({type:"stream.subagent",state:{tabs:[{sessionID:e.sessionID,partID:e.partID,callID:e.callID,label:e.label,description:e.description,status:e.status,title:e.title,toolCalls:e.toolCalls,lastUpdatedAt:Date.now()}],details:{[e.sessionID]:{sessionID:e.sessionID,commits:e.commits}},permissions:[],questions:[]}})}function K(o,e){return new Promise((r)=>{if(!e){setTimeout(r,o);return}if(e.aborted){r();return}let s=()=>{clearTimeout(l),e.removeEventListener("abort",s),r()},l=setTimeout(()=>{e.removeEventListener("abort",s),r()},o);e.addEventListener("abort",s,{once:!0})})}function Bo(o){if(o.length<=48)return[o];let e=Math.ceil(o.length/3);return[o.slice(0,e),o.slice(e,e*2),o.slice(e*2)]}function $(o,e,r){return o[e]+=1,`demo_${r}_${o[e]}`}function D(o,e){let r=$o({data:o.data,event:e,sessionID:o.id,thinking:o.thinking,limits:o.limits()});o.data=r.data,Wo({footer:o.footer},r)}function no(o){let e=$(o,"msg","msg");return D(o,{type:"message.updated",properties:{sessionID:o.id,info:{id:e,sessionID:o.id,role:"assistant",time:{created:Date.now()},parentID:`user_${e}`,modelID:"demo",providerID:"demo",mode:"demo",agent:"demo",path:{cwd:process.cwd(),root:process.cwd()},cost:0.001,tokens:{input:120,output:320,reasoning:80,cache:{read:0,write:0}}}}}),e}async function G(o,e,r){let s=no(o),l=$(o,"part","part"),d=Date.now();D(o,{type:"message.part.updated",properties:{sessionID:o.id,time:Date.now(),part:{id:l,sessionID:o.id,messageID:s,type:"text",text:"",time:{start:d}}}});let n="";for(let a of Bo(e)){if(r?.aborted)return;n+=a,D(o,{type:"message.part.delta",properties:{sessionID:o.id,messageID:s,partID:l,field:"text",delta:a}}),await K(45,r)}D(o,{type:"message.part.updated",properties:{sessionID:o.id,time:Date.now(),part:{id:l,sessionID:o.id,messageID:s,type:"text",text:n,time:{start:d,end:Date.now()}}}})}async function ko(o,e,r){let s=no(o),l=$(o,"part","part"),d=Date.now();D(o,{type:"message.part.updated",properties:{sessionID:o.id,time:Date.now(),part:{id:l,sessionID:o.id,messageID:s,type:"reasoning",text:"",time:{start:d}}}});let n="";for(let a of Bo(e)){if(r?.aborted)return;n+=a,D(o,{type:"message.part.delta",properties:{sessionID:o.id,messageID:s,partID:l,field:"text",delta:a}}),await K(45,r)}D(o,{type:"message.part.updated",properties:{sessionID:o.id,time:Date.now(),part:{id:l,sessionID:o.id,messageID:s,type:"reasoning",text:n,time:{start:d,end:Date.now()}}}})}function y(o,e,r){return{msg:no(o),part:$(o,"part","part"),call:$(o,"call","call"),tool:e,input:r,start:Date.now()}}function io(o,e,r={}){D(o,{type:"message.part.updated",properties:{sessionID:o.id,time:Date.now(),part:{id:e.part,sessionID:o.id,messageID:e.msg,type:"tool",callID:e.call,tool:e.tool,state:{status:"running",input:e.input,metadata:r,time:{start:e.start}}}}})}function O(o,e){io(o,e.ref);let r=$(o,"perm","perm");o.perms.set(r,{ref:e.ref,done:e.done}),D(o,{type:"permission.asked",properties:{id:r,sessionID:o.id,permission:e.permission,patterns:e.patterns,metadata:e.metadata??{},always:e.always,tool:{messageID:e.ref.msg,callID:e.ref.call}}})}function T(o,e,r){D(o,{type:"message.part.updated",properties:{sessionID:o.id,time:Date.now(),part:{id:e.part,sessionID:o.id,messageID:e.msg,type:"tool",callID:e.call,tool:e.tool,state:{status:"completed",input:e.input,output:r.output,title:r.title,metadata:r.metadata??{},time:{start:e.start,end:Date.now()}}}}})}function yo(o,e,r){D(o,{type:"message.part.updated",properties:{sessionID:o.id,time:Date.now(),part:{id:e.part,sessionID:o.id,messageID:e.msg,type:"tool",callID:e.call,tool:e.tool,state:{status:"error",input:e.input,error:r,metadata:{},time:{start:e.start,end:Date.now()}}}}})}function _o(o,e){let r={id:`session.error:${o.id}:${Date.now()}`,type:"session.error",properties:{sessionID:o.id,error:{name:"UnknownError",data:{message:e}}}};D(o,r)}async function Po(o,e){let r=y(o,"bash",{command:"git status",workdir:process.cwd(),description:"Show git status"});io(o,r),await K(70,e),T(o,r,{title:"git status",output:`${process.cwd()}
git status
On branch demo
nothing to commit, working tree clean
`,metadata:{exitCode:0}})}function So(o){let e=q.join(process.cwd(),"src","demo-format.ts"),r=y(o,"write",{filePath:e,content:`export const demo = 42
`});T(o,r,{title:"write",output:"",metadata:{}})}function qo(o){let e=q.join(process.cwd(),"src","demo-format.ts"),r=y(o,"edit",{filePath:e});T(o,r,{title:"edit",output:"",metadata:{diff:`@@ -1 +1 @@
-export const demo = 1
+export const demo = 42
`}})}function To(o){let e=q.join(process.cwd(),"src","demo-format.ts"),r=y(o,"apply_patch",{patchText:`*** Begin Patch
*** End Patch`});T(o,r,{title:"apply_patch",output:"",metadata:{files:[{type:"update",filePath:e,relativePath:"src/demo-format.ts",diff:`@@ -1 +1 @@
-export const demo = 1
+export const demo = 42
`,deletions:1},{type:"add",filePath:q.join(process.cwd(),"README-demo.md"),relativePath:"README-demo.md",diff:`@@ -0,0 +1,4 @@
+# Demo
+This is a generated preview file.
`,deletions:0}]}})}function Co(o){let e=y(o,"task",{description:"Scan run/* for reducer touchpoints",subagent_type:"explore"});T(o,e,{title:"Reducer touchpoints found",output:"",metadata:{toolcalls:4,sessionId:"sub_demo_1"}});let r={id:"sub_demo_tool_1",type:"tool",sessionID:"sub_demo_1",messageID:"sub_demo_msg_tool",callID:"sub_demo_call_1",tool:"read",state:{status:"running",input:{filePath:"packages/muxcode/src/cli/cmd/run/stream.ts",offset:1,limit:200},time:{start:Date.now()}}};We(o,{sessionID:"sub_demo_1",partID:e.part,callID:e.call,label:"Explore",description:"Scan run/* for reducer touchpoints",status:"completed",title:"Reducer touchpoints found",toolCalls:4,commits:[{kind:"user",text:"Scan run/* for reducer touchpoints",phase:"start",source:"system"},{kind:"reasoning",text:"Thinking: tracing reducer and footer boundaries",phase:"progress",source:"reasoning",messageID:"sub_demo_msg_reasoning",partID:"sub_demo_reasoning_1"},{kind:"tool",text:"running read",phase:"start",source:"tool",messageID:"sub_demo_msg_tool",partID:"sub_demo_tool_1",tool:"read",part:r},{kind:"assistant",text:"Footer updates flow through stream.ts into RunFooter",phase:"progress",source:"assistant",messageID:"sub_demo_msg_text",partID:"sub_demo_text_1"}]})}function jo(o){let e=y(o,"todowrite",{todos:[{content:"Trigger permission UI",status:"completed"},{content:"Trigger question UI",status:"in_progress"},{content:"Tune tool formatting",status:"pending"}]});T(o,e,{title:"todowrite",output:"",metadata:{}})}function Eo(o){let e=y(o,"question",{questions:[{header:"Style",question:"Which output style do you want to inspect?",options:[{label:"Diff",description:"Show diff block"},{label:"Code",description:"Show code block"}],multiple:!1},{header:"Extras",question:"Pick extra rows",options:[{label:"Usage",description:"Add usage row"},{label:"Duration",description:"Add duration row"}],multiple:!0,custom:!0}]});T(o,e,{title:"question",output:"",metadata:{answers:[["Diff"],["Usage","custom-note"]]}})}function Be(o,e="edit"){let r=process.cwd(),s=q.join(r,"src","demo-format.ts");if(e==="bash"){let a=y(o,"bash",{command:"git status --short",workdir:r,description:"Inspect worktree changes"});O(o,{ref:a,permission:"bash",patterns:["git status --short"],always:["*"],done:{title:"git status --short",output:`${r}
git status --short
 M src/demo-format.ts
?? src/demo-permission.ts
`,metadata:{exitCode:0}}});return}if(e==="read"){let n=q.join(r,"package.json"),a=y(o,"read",{filePath:n,offset:1,limit:80});O(o,{ref:a,permission:"read",patterns:[n],always:[n],done:{title:"read",output:["1: {",'2:   "name": "muxcode",','3:   "private": true',"4: }"].join(`
`),metadata:{}}});return}if(e==="task"){let n=y(o,"task",{description:"Inspect footer spacing across direct-mode prompts",subagent_type:"explore"});O(o,{ref:n,permission:"task",patterns:["explore"],always:["*"],done:{title:"Footer spacing checked",output:"",metadata:{toolcalls:3,sessionId:"sub_demo_perm_1"}}});return}if(e==="external"){let n=q.join(q.dirname(r),"demo-shared"),a=q.join(n,"README.md"),m=y(o,"read",{filePath:a,offset:1,limit:40});O(o,{ref:m,permission:"external_directory",patterns:[`${n}/**`],metadata:{parentDir:n,filepath:a},always:[`${n}/**`],done:{title:"read",output:`1: # External demo
2: Shared preview file
Path: ${a}`,metadata:{}}});return}if(e==="doom"){let n=y(o,"task",{description:"Retry the formatter after repeated failures",subagent_type:"general"});O(o,{ref:n,permission:"doom_loop",patterns:["*"],always:["*"],done:{title:"Retry allowed",output:`Continuing after repeated failures.
`,metadata:{}}});return}let l=`@@ -1 +1 @@
-export const demo = 1
+export const demo = 42
`,d=y(o,"edit",{filePath:s,filepath:s,diff:l});O(o,{ref:d,permission:"edit",patterns:[s],always:[s],done:{title:"edit",output:"",metadata:{diff:l}}})}function Oe(o,e="multi"){let r=(()=>{if(e==="single")return[{header:"Mode",question:"Which footer should be the reference for spacing checks?",options:[{label:"Permission",description:"Inspect the permission footer"},{label:"Question",description:"Keep this question footer open"},{label:"Prompt",description:"Return to the normal composer"}],multiple:!1,custom:!1}];if(e==="checklist")return[{header:"Checks",question:"Select the direct-mode cases you want to inspect next",options:[{label:"Diff",description:"Show an edit diff in the footer"},{label:"Task",description:"Show a structured task summary"},{label:"Todo",description:"Show a todo snapshot"},{label:"Error",description:"Show an error transcript row"}],multiple:!0,custom:!1}];if(e==="custom")return[{header:"Reply",question:"What custom answer should appear in the footer preview?",options:[{label:"Short note",description:"Keep the answer to one line"},{label:"Wrapped note",description:"Use a longer answer to test wrapping"}],multiple:!1,custom:!0}];return[{header:"Layout",question:"Which footer view should stay active while testing?",options:[{label:"Prompt",description:"Return to prompt"},{label:"Question",description:"Keep question open"}],multiple:!1},{header:"Rows",question:"Pick formatting previews",options:[{label:"Diff",description:"Emit edit diff"},{label:"Task",description:"Emit task card"},{label:"Todo",description:"Emit todo card"}],multiple:!0,custom:!0}]})(),s=y(o,"question",{questions:r});io(o,s);let l=$(o,"ask","ask");o.asks.set(l,{ref:s}),D(o,{type:"question.asked",properties:{id:l,sessionID:o.id,questions:r,tool:{messageID:s.msg,callID:s.call}}})}async function Me(o,e,r,s){if(e==="text")return await G(o,r||eo,s),!0;if(e==="markdown"||e==="md")return await G(o,r||eo,s),!0;if(e==="table")return await G(o,r||Ae,s),!0;if(e==="reasoning")return await ko(o,r||"Planning next steps [REDACTED] while preserving reducer ordering.",s),!0;if(e==="bash")return await Po(o,s),!0;if(e==="write")return So(o),!0;if(e==="edit")return qo(o),!0;if(e==="patch")return To(o),!0;if(e==="task")return Co(o),!0;if(e==="todo")return jo(o),!0;if(e==="question")return Eo(o),!0;if(e==="error")return _o(o,r||"demo error event"),!0;if(e==="mix")return await G(o,eo,s),await K(50,s),await ko(o,"Thinking through formatter edge cases [REDACTED].",s),await K(50,s),await Po(o,s),So(o),qo(o),To(o),Co(o),jo(o),Eo(o),_o(o,"demo mixed scenario error"),!0;return!1}function Ro(o){Q(o.footer,["Demo slash commands enabled for interactive mode.",`- /permission [kind] (${to.join(", ")})`,`- /question [kind] (${so.join(", ")})`,`- /fmt <kind> (${ro.join(", ")})`,"Examples:","- /permission bash","- /question custom","- /fmt markdown","- /fmt table","- /fmt text your custom text"].join(`
`))}function ao(o){let e={id:o.sessionID,thinking:o.thinking,data:Ao(),footer:o.footer,limits:o.limits,msg:0,part:0,call:0,perm:0,ask:0,perms:new Map,asks:new Map};return{start:async()=>{Ro(e)},prompt:async(a,m)=>{let I=a.text.trim().split(/\s+/),g=I[0]||"";if($e(e.footer),g==="/help")return Ro(e),!0;if(g==="/permission"){let c=Ee(I[1]);if(!c)return Q(e.footer,`Pick a permission kind: ${to.join(", ")}`),!0;return Be(e,c),!0}if(g==="/question"){let c=Re(I[1]);if(!c)return Q(e.footer,`Pick a question kind: ${so.join(", ")}`),!0;return Oe(e,c),!0}if(g==="/fmt"){let c=(I[1]||"").toLowerCase(),u=I.slice(2).join(" ");if(!c)return Q(e.footer,`Pick a kind: ${ro.join(", ")}`),!0;if(await Me(e,c,u,m))return!0;return Q(e.footer,`Unknown kind "${c}". Use: ${ro.join(", ")}`),!0}return!1},permission:(a)=>{let m=e.perms.get(a.requestID);if(!m||!a.reply)return!1;e.perms.delete(a.requestID);let p={id:`permission.replied:${a.requestID}:${Date.now()}`,type:"permission.replied",properties:{sessionID:e.id,requestID:a.requestID,reply:a.reply}};if(D(e,p),a.reply==="reject")return yo(e,m.ref,a.message||"permission rejected"),!0;return T(e,m.ref,m.done),!0},questionReply:(a)=>{let m=e.asks.get(a.requestID);if(!m||!a.answers)return!1;e.asks.delete(a.requestID);let p={id:`question.replied:${a.requestID}:${Date.now()}`,type:"question.replied",properties:{sessionID:e.id,requestID:a.requestID,answers:a.answers}};return D(e,p),T(e,m.ref,{title:"question",output:"",metadata:{answers:a.answers}}),!0},questionReject:(a)=>{let m=e.asks.get(a.requestID);if(!m)return!1;return e.asks.delete(a.requestID),D(e,{type:"question.rejected",properties:{sessionID:e.id,requestID:a.requestID}}),yo(e,m.ref,"question rejected"),!0}}}function Oo(o,e){if(o.current)return o.current;let r=e().finally(()=>{if(o.current===r)o.current=void 0});return o.current=r,r}import Ue from"path";var Mo=Ue.join(L.Path.state,"model.json");class H extends X.Service()("@muxcode/RunVariant"){}function Ne(o,e){return`${o}/${e}`}function Uo(o){return Ne(o.providerID,o.modelID)}function Qe(o,e){let r=o?.find((s)=>s.id===e.providerID);return{provider:r?.name??e.providerID,model:r?.models[e.modelID]?.name??e.modelID}}function W(o,e,r){let s=Qe(r,o),l=e?` \xB7 ${e}`:"";return`${s.model} \xB7 ${s.provider}${l}`}function zo(o,e){if(e.length===0)return;if(!o)return e[0];let r=e.indexOf(o);if(r===-1||r===e.length-1)return;return e[r+1]}function co(o,e){return Lo(Array.isArray(e)?Ko(e):e,o)}function No(o,e){if(!o)return;if(e.length===0||e.includes(o))return o;return}function z(o,e,r,s){if(o!==void 0)return o;let l=No(r,s),d=No(e,s);if(d!==void 0)return d;return l}function Qo(o){if(!lo(o))return{};let e=lo(o.variant)?Object.fromEntries(Object.entries(o.variant).flatMap(([r,s])=>{if(typeof s!=="string")return[];return[[r,s]]})):void 0;return{...o,variant:e}}function Ke(o=J.defaultLayer){return M.fresh(M.effect(H,w.gen(function*(){let e=yield*J.Service,r=w.fn("RunVariant.read")(function*(){return yield*e.readJson(Mo).pipe(w.map(Qo),w.catchCause(()=>w.succeed(Qo(void 0))))}),s=w.fn("RunVariant.resolveSavedVariant")(function*(d){if(!d)return;return(yield*r()).variant?.[Uo(d)]}),l=w.fn("RunVariant.saveVariant")(function*(d,n){if(!d)return;let a=yield*r(),m={...a.variant},p=Uo(d);if(n)m[p]=n;if(!n)delete m[p];yield*e.writeJson(Mo,{...a,variant:m}).pipe(w.orElseSucceed(()=>{return}))});return H.of({resolveSavedVariant:s,saveVariant:l})})).pipe(M.provide(o)))}function Le(o=J.defaultLayer){let e=Z(H,Ke(o));return{resolveSavedVariant:(r)=>e.runPromise((s)=>s.resolveSavedVariant(r)).catch(()=>{return}),saveVariant:(r,s)=>e.runPromise((l)=>l.saveVariant(r,s)).catch(()=>{})}}var Go=Le();async function mo(o){return Go.resolveSavedVariant(o)}function fo(o,e){Go.saveVariant(o,e)}var Yo={leader:go.LeaderDefault,leaderTimeout:2000,commandList:[{key:"ctrl+p"}],variantCycle:[{key:"ctrl+t"}],interrupt:[{key:"escape"}],historyPrevious:[{key:"up"}],historyNext:[{key:"down"}],inputClear:[{key:"ctrl+c"}],inputSubmit:[{key:"return"}],inputNewline:[{key:"shift+return,ctrl+return,alt+return,ctrl+j"}]},ze={};class Y extends X.Service()("@muxcode/RunBoot"){}function Ge(){return Oo(ze,()=>Ho.get())}function Je(){return{providers:[],variants:[],limits:{}}}function Fo(){return{first:!0,history:[],variant:void 0}}function He(o){let e=o.keybinds.get("leader")?.[0]?.key;if(!e)return go.LeaderDefault;return typeof e==="string"?e:Jo(e)}function Xe(o){if(!o)return Yo;return{leader:He(o),leaderTimeout:o.leader_timeout,commandList:o.keybinds.get("command.palette.show"),variantCycle:o.keybinds.get("variant.cycle"),interrupt:o.keybinds.get("session.interrupt"),historyPrevious:o.keybinds.get("prompt.history.previous"),historyNext:o.keybinds.get("prompt.history.next"),inputClear:o.keybinds.get("prompt.clear"),inputSubmit:o.keybinds.get("input.submit"),inputNewline:o.keybinds.get("input.newline")}}var Ze=M.effect(Y,w.gen(function*(){let o=w.fn("RunBoot.config")(()=>w.promise(()=>Ge().catch(()=>{return}))),e=w.fn("RunBoot.resolveModelInfo")(function*(d,n,a){let m=yield*w.promise(()=>d.config.providers({directory:n}).then((c)=>c.data?.providers).catch(()=>{return})),p=yield*w.promise(()=>m?Promise.resolve(m):d.provider.list().then((c)=>c.data?.all??[]).catch(()=>[])),I=Object.fromEntries(p.flatMap((c)=>Object.entries(c.models??{}).flatMap(([u,t])=>{let k=t?.limit?.context;if(typeof k!=="number"||k<=0)return[];return[[`${c.id}/${u}`,k]]})));if(!a)return{providers:p,variants:[],limits:I};let g=p.find((c)=>c.id===a.providerID)?.models?.[a.modelID];return{providers:p,variants:Object.keys(g?.variants??{}),limits:I}}),r=w.fn("RunBoot.resolveSessionInfo")(function*(d,n,a){let m=yield*w.promise(()=>Xo(d,n).catch(()=>{return}));if(!m)return Fo();return{first:m.first,history:Zo(m),variant:co(a,m)}}),s=w.fn("RunBoot.resolveFooterKeybinds")(function*(){return Xe(yield*o())}),l=w.fn("RunBoot.resolveDiffStyle")(function*(){return(yield*o())?.diff_style??"auto"});return Y.of({resolveModelInfo:e,resolveSessionInfo:r,resolveFooterKeybinds:s,resolveDiffStyle:l})})),F=Z(Y,Ze);async function Vo(o,e,r){return F.runPromise((s)=>s.resolveModelInfo(o,e,r)).catch(()=>Je())}async function xo(o,e,r){return F.runPromise((s)=>s.resolveSessionInfo(o,e,r)).catch(()=>Fo())}async function vo(){return F.runPromise((o)=>o.resolveFooterKeybinds()).catch(()=>Yo)}async function oe(){return F.runPromise((o)=>o.resolveDiffStyle()).catch(()=>"auto")}var Fe=50,ee="Untitled session",ie=0;function Ve(o){let e=[];for(let r of o){if(r==="_"){e.push({char:" ",mark:"full"});continue}if(r==="^"){e.push({char:"\u2580",mark:"mix"});continue}if(r==="~"){e.push({char:"\u2580",mark:"top"});continue}e.push({char:r,mark:"text"})}return e}function xe(o){if(!o)return ee;let e="",r=!1;for(let s of o.trim()){if(s===" "||s===`
`||s==="\r"||s==="\t"){r=!0;continue}if(r&&e.length>0)e+=" ";e+=s,r=!1}if(!e)return ee;return te(e,Fe)}function ve(o,e,r){if(r.left>=e.width)return;o.add(new ne(e.renderContext,{id:`run-direct-splash-line-${ie++}`,position:"absolute",left:r.left,top:r.top,width:Math.max(1,e.width-r.left),height:1,wrapMode:"none",content:r.text,fg:r.fg,bg:r.bg,attributes:r.attrs}))}function C(o,e,r,s,l,d,n){o.push({left:e,top:r,text:s,fg:l,bg:d,attrs:n})}function V(o,e){if(o instanceof E)return o;if(typeof o==="string"){if(o==="transparent"||o==="none")return E.fromValues(0,0,0,0);if(o.startsWith("#"))return E.fromHex(o)}return e}function ho(o,e){return E.fromIndex(o,E.fromHex(e))}function po(o,e,r){let s=r.left;for(let l of Ve(e)){if(l.mark==="full"||l.mark==="mix"){C(o,s,r.top,l.char,r.fg,r.shadow,r.attrs),s+=1;continue}if(l.mark==="top"){C(o,s,r.top,l.char,r.shadow,void 0,r.attrs),s+=1;continue}C(o,s,r.top,l.char,r.fg,void 0,r.attrs),s+=1}}function ae(o,e,r){let s=Math.max(1,r.width),l=x(o),d=[],n=V(o.theme.left,ho(81,"#38bdf8")),a=V(o.theme.right,E.defaultForeground(E.fromHex("#f8fafc"))),m=V(o.theme.leftShadow,ho(238,"#334155")),p=1;if(e==="entry"){let g=V(o.theme.rightShadow,ho(240,"#475569"));for(let c=0;c<U.left.length;c+=1){let u=U.left[c]??"",t=U.right[c]??"";po(d,u,{left:0,top:c,fg:n,shadow:m}),po(d,t,{left:u.length+1,top:c,fg:a,shadow:g})}if(p=U.left.length,o.showSession!==!1){let c=U.left.length+1,u="Session".padEnd(10," ");C(d,0,c,u,n,void 0,B.DIM),C(d,u.length,c,l.title,a,void 0,B.BOLD),p=c+1}}if(e==="exit"){let g=re.right.slice(1),c=1,u=(g[0]?.length??0)+2,t="Session  ",k="Continue ";for(let P=0;P<g.length;P+=1)po(d,g[P]??"",{left:0,top:1+P,fg:n,shadow:m});if(o.showSession!==!1)C(d,u,1,"Session  ",n,void 0,B.DIM),C(d,u+9,1,l.title,a,void 0,B.BOLD);C(d,u,2,"Continue ",n,void 0,B.DIM),C(d,u+9,2,`muxcode run -i -s ${l.session_id}`,a,void 0,B.BOLD),p=1+g.length}let I=new se(r.renderContext,{id:`run-direct-splash-${e}-${ie++}`,position:"absolute",left:0,top:0,width:s,height:p});for(let g of d)ve(I,r,g);return{root:I,width:s,height:p,rowColumns:s,startOnNewLine:!0,trailingNewline:!1}}function x(o){return{title:xe(o.title),session_id:o.session_id}}function le(o){return(e)=>ae(o,"entry",e)}function de(o){return(e)=>ae(o,"exit",e)}var or=7;function er(o){if(o.isDestroyed)return;if(o.externalOutputMode==="capture-stdout")o.externalOutputMode="passthrough";if(o.screenMode==="split-footer")o.screenMode="main-screen";if(!o.isDestroyed)o.destroy()}function ce(o,e){if(o&&!fe.isDefaultTitle(o))return{title:o,showSession:!0};let r=e.find((s)=>s.text.trim().length>0);return{title:r?.text??o,showSession:!!r}}function rr(o){let e=he(o.agent??"build");if(!o.model)return{agentLabel:e,modelLabel:"Model default"};return{agentLabel:e,modelLabel:W(o.model,o.variant)}}function me(o,e,r,s){if(e[r])return!1;if(!s)return!1;return e[r]=!0,o.writeToScrollback(s),o.requestRender(),!0}async function we(o){return R("RunLifecycle.boot",{"muxcode.agent.name":o.agent,"muxcode.directory":o.directory,"muxcode.first":o.first,"muxcode.model.provider":o.model?.providerID,"muxcode.model.id":o.model?.modelID,"muxcode.model.variant":o.variant,"session.id":o.getSessionID?.()||o.sessionID||void 0},async()=>{let e=ge();try{let r=await pe({stdin:e.stdin,targetFps:30,maxFps:60,useMouse:!1,autoFocus:!1,openConsoleOnError:!1,exitOnCtrlC:!1,useKittyKeyboard:{events:process.platform==="win32"},screenMode:"split-footer",footerHeight:or,externalOutputMode:"capture-stdout",consoleMode:"disabled",clearOnShutdown:!1}),s=await ue(r);r.setBackgroundColor(s.background);let l={entry:!1,exit:!1},d=ce(o.sessionTitle,o.history),n=x({title:d.title,session_id:o.sessionID}),a=import("./chunk-sa0d9wk7.js"),m=me(r,l,"entry",le({...n,theme:s.splash,showSession:d.showSession}));await r.idle().catch(()=>{});let{RunFooter:p}=await a,I=rr({agent:o.agent,model:o.model,variant:o.variant}),g=new p(r,{directory:o.directory,findFiles:o.findFiles,agents:o.agents,resources:o.resources,sessionID:o.getSessionID??(()=>o.sessionID),...I,model:o.model,variant:o.variant,first:o.first,history:o.history,theme:s,wrote:m,keybinds:o.keybinds,diffStyle:o.diffStyle,onPermissionReply:o.onPermissionReply,onQuestionReply:o.onQuestionReply,onQuestionReject:o.onQuestionReject,onCycleVariant:o.onCycleVariant,onModelSelect:o.onModelSelect,onVariantSelect:o.onVariantSelect,onInterrupt:o.onInterrupt,onSubagentSelect:o.onSubagentSelect}),c=()=>{g.requestExit()};process.on("SIGINT",c);let u=!1;return{footer:g,close:async(k)=>{if(u)return;return u=!0,R("RunLifecycle.close",{"muxcode.show_exit":k.showExit,"session.id":k.sessionID||o.getSessionID?.()||o.sessionID||void 0},async()=>{process.off("SIGINT",c);try{await g.idle().catch(()=>{});let P=r.isDestroyed?!1:k.showExit;if(!r.isDestroyed&&P){let f=k.sessionID||o.getSessionID?.()||o.sessionID,v=ce(k.sessionTitle??o.sessionTitle,k.history??o.history);me(r,l,"exit",de({...x({title:v.title,session_id:f}),theme:s.splash})),await r.idle().catch(()=>{})}}finally{g.close(),await g.idle().catch(()=>{}),g.destroy(),er(r),e.cleanup?.()}})}}}catch(r){throw e.cleanup?.(),r}})}import wo from"fs";import bo from"path";var N;function tr(){return new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z")}function sr(){return bo.join(L.Path.log,"direct",`${tr()}-${process.pid}.jsonl`)}function nr(){return bo.join(L.Path.log,"direct","latest.json")}function be(o){return JSON.stringify(o,(e,r)=>{if(typeof r==="bigint")return String(r);return r},0)}function De(){if(N!==void 0)return N||void 0;if(!process.env.MUXCODE_DIRECT_TRACE){N=!1;return}let o=sr();return wo.mkdirSync(bo.dirname(o),{recursive:!0}),wo.writeFileSync(nr(),be({time:new Date().toISOString(),pid:process.pid,cwd:process.cwd(),argv:process.argv.slice(2),path:o})+`
`),N={write(e,r){wo.appendFileSync(o,be({time:new Date().toISOString(),pid:process.pid,type:e,data:r})+`
`)}},N.write("trace.start",{argv:process.argv.slice(2),cwd:process.cwd(),path:o}),N}function Pe(o){if(!o)return;return async(e,r)=>{let s=await o(e.sdk,r);if(!s.id)throw Error("Failed to create session");return{sessionID:s.id,sessionTitle:s.title,agent:r.agent}}}function Do(o,e){return!o.resolveSession||!!e.sessionID}function ar(o,e){return e.resume===!0||!o.resolveSession||!!o.demo}function Ie(o,e){if(!e)return[];return Object.keys(o.find((r)=>r.id===e.providerID)?.models?.[e.modelID]?.variants??{})}async function lr(o,e,r){if(!r.shown||!Do(e,r))return;return o.sdk.session.get({sessionID:r.sessionID}).then((s)=>s.data?.title).catch(()=>{return})}async function Se(o){return R("RunInteractive.session",{"muxcode.mode":o.resolveSession?"local":"attach","muxcode.initial_input":!!o.initialInput,"muxcode.demo":o.demo},async(e)=>{let r=performance.now(),s=De(),l=vo(),d=oe(),n=await o.boot(),a=Vo(n.sdk,n.directory,n.model),m=n.resume===!0?xo(n.sdk,n.sessionID,n.model):Promise.resolve({first:!0,history:[],variant:void 0}),p=mo(n.model),[I,g,c,u]=await Promise.all([l,d,m,p]),t={shown:!c.first,aborting:!1,model:n.model,providers:[],variants:[],limits:{},activeVariant:z(n.variant,c.variant,u,[]),sessionID:n.sessionID,history:[...c.history],sessionTitle:n.sessionTitle,agent:n.agent};j(e,{"muxcode.directory":n.directory,"muxcode.resume":n.resume===!0,"muxcode.agent.name":t.agent,"muxcode.model.provider":t.model?.providerID,"muxcode.model.id":t.model?.modelID,"muxcode.model.variant":t.activeVariant,"session.id":t.sessionID||void 0});let k=()=>{if(!o.resolveSession||t.sessionID)return Promise.resolve();if(t.session)return t.session;return t.session=o.resolveSession(n).then((i)=>{t.sessionID=i.sessionID,t.sessionTitle=i.sessionTitle??t.sessionTitle,t.agent=i.agent,j(e,{"muxcode.agent.name":t.agent,"session.id":t.sessionID})}),t.session},P=await we({directory:n.directory,findFiles:(i)=>n.sdk.find.files({query:i,directory:n.directory}).then((b)=>b.data??[]).catch(()=>[]),agents:[],resources:[],sessionID:t.sessionID,sessionTitle:t.sessionTitle,getSessionID:()=>t.sessionID,first:c.first,history:c.history,agent:t.agent,model:t.model,variant:t.activeVariant,keybinds:I,diffStyle:g,onPermissionReply:async(i)=>{if(t.demo?.permission(i))return;s?.write("send.permission.reply",i),await n.sdk.permission.reply(i)},onQuestionReply:async(i)=>{if(t.demo?.questionReply(i))return;await n.sdk.question.reply(i)},onQuestionReject:async(i)=>{if(t.demo?.questionReject(i))return;await n.sdk.question.reject(i)},onCycleVariant:()=>{if(!t.model||t.variants.length===0)return{status:"no variants available"};return t.activeVariant=zo(t.activeVariant,t.variants),fo(t.model,t.activeVariant),j(e,{"muxcode.model.variant":t.activeVariant}),{status:t.activeVariant?`variant ${t.activeVariant}`:"variant default",modelLabel:W(t.model,t.activeVariant,t.providers),variant:t.activeVariant}},onModelSelect:async(i)=>{if(t.model?.providerID===i.providerID&&t.model.modelID===i.modelID)return;t.model=i,t.activeVariant=void 0,t.variants=Ie(t.providers,i);let b=mo(i).then((h)=>{let S=t.model;if(!S||S.providerID!==i.providerID||S.modelID!==i.modelID)return;t.activeVariant=z(n.variant,void 0,h,t.variants)});if(t.switching=b,await b,t.switching===b)t.switching=void 0;let _=t.model;if(!_||_.providerID!==i.providerID||_.modelID!==i.modelID)return;return j(e,{"muxcode.model.provider":i.providerID,"muxcode.model.id":i.modelID,"muxcode.model.variant":t.activeVariant}),{modelLabel:W(i,t.activeVariant,t.providers),status:`model ${i.modelID}`,variant:t.activeVariant,variants:t.variants}},onVariantSelect:async(i)=>{if(!t.model||t.variants.length===0)return{status:"no variants available"};if(i&&!t.variants.includes(i))return{status:`variant ${i} unavailable`};return t.activeVariant=i,fo(t.model,t.activeVariant),j(e,{"muxcode.model.variant":t.activeVariant}),{status:t.activeVariant?`variant ${t.activeVariant}`:"variant default",modelLabel:W(t.model,t.activeVariant,t.providers),variant:t.activeVariant,variants:t.variants}},onInterrupt:()=>{if(!Do(o,t)||t.aborting)return;t.aborting=!0,n.sdk.session.abort({sessionID:t.sessionID}).catch(()=>{}).finally(()=>{t.aborting=!1})},onSubagentSelect:(i)=>{t.selectSubagent?.(i),s?.write("subagent.select",{sessionID:i})}}),f=P.footer,v=async()=>{if(f.isClosed)return;let[i,b,_]=await Promise.all([n.sdk.app.agents({directory:n.directory}).then((h)=>h.data??[]).catch(()=>[]),n.sdk.experimental.resource.list({directory:n.directory}).then((h)=>Object.values(h.data??{})).catch(()=>[]),n.sdk.command.list({directory:n.directory}).then((h)=>h.data??[]).catch(()=>[])]);if(f.isClosed)return;f.event({type:"catalog",agents:i,resources:b,commands:_})};if(f.idle().then(v).catch(()=>{}),ke.MUXCODE_SHOW_TTFD)f.append({kind:"system",text:`startup ${Math.max(0,Math.round(performance.now()-r))}ms`,phase:"final",source:"system"});if(o.demo)await k(),t.demo=ao({footer:f,sessionID:t.sessionID,thinking:o.thinking,limits:()=>t.limits});if(o.afterPaint)Promise.resolve(o.afterPaint(n)).catch(()=>{});a.then((i)=>{t.providers=i.providers,t.variants=Ie(t.providers,t.model),t.limits=i.limits;let b=z(n.variant,c.variant,u,t.variants);if(b!==t.activeVariant)t.activeVariant=b,j(e,{"muxcode.model.variant":t.activeVariant});if(f.isClosed)return;if(f.event({type:"models",providers:i.providers}),f.event({type:"variants",variants:t.variants,current:t.activeVariant}),!t.model)return;f.event({type:"model",model:W(t.model,t.activeVariant,t.providers)})});let qe=import("./chunk-90s4q279.js"),oo=()=>{if(t.stream)return t.stream;let i=(async()=>{if(await k(),f.isClosed)throw Error("runtime closed");let b=await qe;if(f.isClosed)throw Error("runtime closed");let _=await b.createSessionTransport({sdk:n.sdk,directory:n.directory,sessionID:t.sessionID,thinking:o.thinking,replay:o.replay,replayLimit:o.replayLimit,limits:()=>t.limits,footer:f,trace:s});if(f.isClosed)throw await _.close(),Error("runtime closed");return t.selectSubagent=(h)=>_.selectSubagent(h),{mod:b,handle:_}})();return t.stream=i,i.catch(()=>{if(t.stream===i)t.stream=void 0}),i},Te=async()=>{let i=!0;if(t.demo)await t.demo.start();let b=await import("./chunk-8hnxna4e.js"),_=o.createSession;await b.runPromptQueue({footer:f,initialInput:o.initialInput,trace:s,onSend:(h)=>{t.shown=!0,t.history.push(h)},onNewSession:_?async()=>{try{await t.switching?.catch(()=>{});let h=await _(n,{agent:t.agent,model:t.model,variant:t.activeVariant});await f.idle().catch(()=>{}),await t.stream?.then((S)=>S.handle.close()).catch(()=>{}),t.stream=void 0,t.session=void 0,t.selectSubagent=void 0,t.shown=!1,t.sessionID=h.sessionID,t.sessionTitle=h.sessionTitle,t.agent=h.agent??t.agent,t.history=[],i=!0,t.demo=o.demo?ao({footer:f,sessionID:t.sessionID,thinking:o.thinking,limits:()=>t.limits}):void 0,j(e,{"muxcode.agent.name":t.agent,"muxcode.model.provider":t.model?.providerID,"muxcode.model.id":t.model?.modelID,"muxcode.model.variant":t.activeVariant,"session.id":t.sessionID}),s?.write("session.new",{sessionID:t.sessionID}),f.event({type:"stream.subagent",state:{tabs:[],details:{},permissions:[],questions:[]}}),f.event({type:"stream.view",view:{type:"prompt"}}),f.event({type:"stream.patch",patch:{phase:"idle",duration:"",usage:"",first:!0}}),f.append({kind:"system",text:`new session ${t.sessionID}`,phase:"final",source:"system"}),await t.demo?.start()}catch(h){f.event({type:"stream.patch",patch:{phase:"idle",status:"failed to start new session"}}),f.append({kind:"error",text:h instanceof Error?h.message:String(h),phase:"start",source:"system"})}}:void 0,run:async(h,S)=>{if(t.demo&&await t.demo.prompt(h,S))return;return await t.switching?.catch(()=>{}),R("RunInteractive.turn",{"muxcode.agent.name":t.agent,"muxcode.model.provider":t.model?.providerID,"muxcode.model.id":t.model?.modelID,"muxcode.model.variant":t.activeVariant,"muxcode.prompt.chars":h.text.length,"muxcode.prompt.parts":h.parts.length,"muxcode.prompt.include_files":i,"muxcode.prompt.file_parts":i?o.files.length:0,"session.id":t.sessionID||void 0},async(Io)=>{try{let A=await oo();j(Io,{"muxcode.agent.name":t.agent,"muxcode.model.provider":t.model?.providerID,"muxcode.model.id":t.model?.modelID,"muxcode.model.variant":t.activeVariant,"session.id":t.sessionID||void 0}),await A.handle.runPromptTurn({agent:t.agent,model:t.model,variant:t.activeVariant,prompt:h,files:o.files,includeFiles:i,signal:S}),i=!1}catch(A){if(S.aborted||f.isClosed)return;_e(Io,A);let Ce=(await t.stream?.then((je)=>je.mod).catch(()=>{return}))?.formatUnknownError(A)??(A instanceof Error?A.message:String(A));f.append({kind:"error",text:Ce,phase:"start",source:"system"})}})}})};try{let i=ar(o,n);if(i)await oo();if(!i&&o.resolveSession)queueMicrotask(()=>{if(f.isClosed)return;oo().catch(()=>{})});try{await Te()}finally{await t.stream?.then((b)=>b.handle.close()).catch(()=>{})}}finally{let i=await lr(n,o,t);await P.close({showExit:t.shown&&Do(o,t),sessionTitle:i,sessionID:t.sessionID,history:t.history})}})}async function ot(o){return R("RunInteractive.localMode",{"muxcode.directory":o.directory,"muxcode.initial_input":!!o.initialInput,"muxcode.demo":o.demo},async()=>{let e=ye({baseUrl:"http://muxcode.internal",fetch:o.fetch,directory:o.directory}),r;return Se({files:o.files,initialInput:o.initialInput,thinking:o.thinking,replay:o.replay,replayLimit:o.replayLimit,demo:o.demo,resolveSession:()=>{if(r)return r;return r=Promise.all([o.resolveAgent(),o.session(e)]).then(([s,l])=>{if(!l?.id)throw Error("Session not found");return o.share(e,l.id).catch(()=>{}),{sessionID:l.id,sessionTitle:l.title,agent:s}}),r},createSession:Pe(o.createSession),boot:async()=>{return{sdk:e,directory:o.directory,sessionID:"",sessionTitle:void 0,resume:!1,agent:o.agent,model:o.model,variant:o.variant}}})})}async function et(o){return R("RunInteractive.attachMode",{"muxcode.directory":o.directory,"muxcode.initial_input":!!o.initialInput,"session.id":o.sessionID},async()=>Se({files:o.files,initialInput:o.initialInput,thinking:o.thinking,replay:o.replay,replayLimit:o.replayLimit,demo:o.demo,boot:async()=>({sdk:o.sdk,directory:o.directory,sessionID:o.sessionID,sessionTitle:o.sessionTitle,resume:o.resume,agent:o.agent,model:o.model,variant:o.variant}),createSession:Pe(o.createSession)}))}export{ir as runPromptQueue,et as runInteractiveMode,ot as runInteractiveLocalMode,z as resolveVariant,co as pickVariant};
