@minimax-ai/code 0.4.11 → 0.4.12
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/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,18 @@ This changelog covers important changes that directly affect MCode TUI users. It
|
|
|
7
7
|
|
|
8
8
|
Internal refactors, test-only changes, and changes limited to other product surfaces are excluded.
|
|
9
9
|
|
|
10
|
+
## 0.4.12 · 2026-09-18
|
|
11
|
+
|
|
12
|
+
### Improved
|
|
13
|
+
|
|
14
|
+
- The default status line shows context capacity before usage is available, then switches to the
|
|
15
|
+
remaining percentage as usage updates, avoiding duplicate context indicators.
|
|
16
|
+
|
|
17
|
+
### Fixed
|
|
18
|
+
|
|
19
|
+
- Terminal scrollback is preserved when session status updates trigger a redraw, preventing the
|
|
20
|
+
history from being cleared or Windows Terminal from jumping to the beginning.
|
|
21
|
+
|
|
10
22
|
## 0.4.11 · 2026-09-17
|
|
11
23
|
|
|
12
24
|
### Fixed
|
package/CHANGELOG.zh-CN.md
CHANGED
|
@@ -8,6 +8,16 @@ TUI 正式版中用户能直接感知的重要变化。收录范围以 TUI 用
|
|
|
8
8
|
|
|
9
9
|
仅内部重构、测试调整,或只影响其他产品界面且不改变 TUI 行为的变化不记录。
|
|
10
10
|
|
|
11
|
+
## 0.4.12 · 2026-09-18
|
|
12
|
+
|
|
13
|
+
### 体验改进
|
|
14
|
+
|
|
15
|
+
- 默认状态栏在尚无用量时显示上下文容量,获得用量后自动切换为剩余百分比,避免重复展示上下文信息。
|
|
16
|
+
|
|
17
|
+
### 问题修复
|
|
18
|
+
|
|
19
|
+
- 修复会话状态刷新触发重绘时清空终端滚动历史,或导致 Windows Terminal 跳到历史开头的问题。
|
|
20
|
+
|
|
11
21
|
## 0.4.11 · 2026-09-17
|
|
12
22
|
|
|
13
23
|
### 问题修复
|
|
@@ -119,7 +119,7 @@ Please report this to https://github.com/markedjs/marked.`,n){let i="<p>An error
|
|
|
119
119
|
`)}collectKittyImageIds(e){let t=new Set;for(let i of e)for(let s of Hp(i))t.add(s);return t}deleteKittyImages(e){let t="";for(let i of e)t+=Co(i);return t}getKittyImageReservedRows(e,t,i=e.length-1){let s=Qk(e[t]??"");if(s<=1)return 1;let r=Math.min(s,i-t+1,e.length-t),o=1;for(;o<r;){let a=e[t+o]??"";if(Ue(a)||x(a)>0)break;o++}return o}expandChangedRangeForKittyImages(e,t,i){let s=e,r=t,o=a=>{for(let u=0;u<a.length;u++){if(Hp(a[u]).length===0)continue;let l=u+this.getKittyImageReservedRows(a,u)-1;(u>=e||u<=t&&l>=e)&&(s=Math.min(s,u),r=Math.max(r,l))}};return o(this.previousLines),o(i),{firstChanged:s,lastChanged:r}}deleteChangedKittyImages(e,t){if(e<0||t<e)return"";let i=new Set,s=Math.min(t,this.previousLines.length-1);for(let r=e;r<=s;r++)for(let o of Hp(this.previousLines[r]??""))i.add(o);return this.deleteKittyImages(i)}doRender(){if(this.stopped)return;let e=this.terminal.columns,t=this.terminal.rows,i=this.previousWidth!==0&&this.previousWidth!==e,s=this.previousHeight!==0&&this.previousHeight!==t,r=this.previousHeight>0?this.previousViewportTop+this.previousHeight:t,o=s?Math.max(0,r-t):this.previousViewportTop,a=o,u=this.hardwareCursorRow,l=O=>{let B=u-o;return O-a-B},c=this.render(e).map(O=>O.replace(zk,""));this.hasOverlayEntries&&(c=this.compositeOverlays(c,e,t));let p=this.extractCursorPosition(c,t);c=this.applyLineResets(c);let m=(O,B=!1)=>{this.fullRedrawCount+=1;let z=new Do(ce=>this.terminal.write(ce));z.append("\x1B[?2026h"),O&&(z.append(this.deleteKittyImages(this.previousKittyImageIds)),z.append(B?"\x1B[2J\x1B[H":"\x1B[2J\x1B[H\x1B[3J"));let ae=B?Math.max(0,c.length-t):0;for(let ce=ae;ce<c.length;ce++){ce>ae&&z.append(`\r
|
|
120
120
|
`);let Z=c[ce],et=Ue(Z)?this.getKittyImageReservedRows(c,ce):1;if(et>1&&et<=t){for(let Yi=1;Yi<et;Yi++)z.append(`\r
|
|
121
121
|
`);z.append(`\x1B[${et-1}A`),z.append(Z),z.append(`\x1B[${et-1}B`),ce+=et-1;continue}z.append(Z)}z.append("\x1B[?2026l"),z.flush(),this.cursorRow=Math.max(0,c.length-1),this.hardwareCursorRow=this.cursorRow,O?this.maxLinesRendered=c.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,c.length);let we=Math.max(t,c.length);this.previousViewportTop=Math.max(0,we-t),this.positionHardwareCursor(p,c.length),this.previousLines=c,this.previousKittyImageIds=this.collectKittyImageIds(c),this.previousWidth=e,this.previousHeight=t},f=process.env.PI_DEBUG_REDRAW==="1",y=O=>{if(!f)return;let B=hs.join(this.logDirectory,"pi-debug.log"),z=`[${new Date().toISOString()}] fullRender: ${O} (prev=${this.previousLines.length}, new=${c.length}, height=${t})
|
|
122
|
-
`;Gn.mkdirSync(hs.dirname(B),{recursive:!0}),Gn.appendFileSync(B,z)};if(this.historyReplayPending){let O=this.resizeTimer!==void 0;m(!0,O),O||(this.historyReplayPending=!1);return}if(this.previousLines.length===0&&!i&&!s){y("first render"),m(!1);return}if(i){y(`terminal width changed (${this.previousWidth} -> ${e})`),m(!0);return}if(s&&!sb()){y(`terminal height changed (${this.previousHeight} -> ${t})`),m(!0);return}if(this.getClearOnShrink()&&c.length<this.maxLinesRendered&&!this.hasOverlayEntries){y(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),m(!0);return}let T=-1,b=-1,S=Math.max(c.length,this.previousLines.length);for(let O=0;O<S;O++){let B=O<this.previousLines.length?this.previousLines[O]:"",z=O<c.length?c[O]:"";B!==z&&(T===-1&&(T=O),b=O)}let M=c.length>this.previousLines.length;if(M&&(T===-1&&(T=this.previousLines.length),b=c.length-1),T!==-1){let O=this.expandChangedRangeForKittyImages(T,b,c);T=O.firstChanged,b=O.lastChanged}let R=M&&T===this.previousLines.length&&T>0;if(T===-1){this.positionHardwareCursor(p,c.length),this.previousViewportTop=o,this.previousHeight=t;return}if(T>=c.length){if(this.previousLines.length>c.length){let O=new Do(Z=>this.terminal.write(Z));O.append("\x1B[?2026h"),O.append(this.deleteChangedKittyImages(T,b));let B=Math.max(0,c.length-1);if(B<o){y(`deleted lines moved viewport up (${B} < ${o})`),m(!0);return}let z=l(B);z>0?O.append(`\x1B[${z}B`):z<0&&O.append(`\x1B[${-z}A`),O.append("\r");let ae=this.previousLines.length-c.length;if(ae>t){y(`extraLines > height (${ae} > ${t})`),m(!0);return}let we=c.length===0?0:1;ae>0&&we>0&&O.append(`\x1B[${we}B`);for(let Z=0;Z<ae;Z++)O.append("\r\x1B[2K"),Z<ae-1&&O.append("\x1B[1B");let ce=Math.max(0,ae-1+we);ce>0&&O.append(`\x1B[${ce}A`),O.append("\x1B[?2026l"),O.flush(),this.cursorRow=B,this.hardwareCursorRow=B}this.positionHardwareCursor(p,c.length),this.previousLines=c,this.previousKittyImageIds=this.collectKittyImageIds(c),this.previousWidth=e,this.previousHeight=t,this.previousViewportTop=o;return}if(T<o){y(`firstChanged < viewportTop (${T} < ${o})`),m(!0);return}let _=new Do(O=>this.terminal.write(O));_.append("\x1B[?2026h"),_.append(this.deleteChangedKittyImages(T,b));let F=o+t-1,A=R?T-1:T;if(A>F){let O=Math.max(0,Math.min(t-1,u-o)),B=t-1-O;B>0&&_.append(`\x1B[${B}B`);let z=A-F;_.append(`\r
|
|
122
|
+
`;Gn.mkdirSync(hs.dirname(B),{recursive:!0}),Gn.appendFileSync(B,z)};if(this.historyReplayPending){let O=this.resizeTimer!==void 0;m(!0,O),O||(this.historyReplayPending=!1);return}if(this.previousLines.length===0&&!i&&!s){y("first render"),m(!1);return}if(i){y(`terminal width changed (${this.previousWidth} -> ${e})`),m(!0);return}if(s&&!sb()){y(`terminal height changed (${this.previousHeight} -> ${t})`),m(!0);return}if(this.getClearOnShrink()&&c.length<this.maxLinesRendered&&!this.hasOverlayEntries){y(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),m(!0,!0);return}let T=-1,b=-1,S=Math.max(c.length,this.previousLines.length);for(let O=0;O<S;O++){let B=O<this.previousLines.length?this.previousLines[O]:"",z=O<c.length?c[O]:"";B!==z&&(T===-1&&(T=O),b=O)}let M=c.length>this.previousLines.length;if(M&&(T===-1&&(T=this.previousLines.length),b=c.length-1),T!==-1){let O=this.expandChangedRangeForKittyImages(T,b,c);T=O.firstChanged,b=O.lastChanged}let R=M&&T===this.previousLines.length&&T>0;if(T===-1){this.positionHardwareCursor(p,c.length),this.previousViewportTop=o,this.previousHeight=t;return}if(T>=c.length){if(this.previousLines.length>c.length){let O=new Do(Z=>this.terminal.write(Z));O.append("\x1B[?2026h"),O.append(this.deleteChangedKittyImages(T,b));let B=Math.max(0,c.length-1);if(B<o){y(`deleted lines moved viewport up (${B} < ${o})`),m(!0,!0);return}let z=l(B);z>0?O.append(`\x1B[${z}B`):z<0&&O.append(`\x1B[${-z}A`),O.append("\r");let ae=this.previousLines.length-c.length;if(ae>t){y(`extraLines > height (${ae} > ${t})`),m(!0,!0);return}let we=c.length===0?0:1;ae>0&&we>0&&O.append(`\x1B[${we}B`);for(let Z=0;Z<ae;Z++)O.append("\r\x1B[2K"),Z<ae-1&&O.append("\x1B[1B");let ce=Math.max(0,ae-1+we);ce>0&&O.append(`\x1B[${ce}A`),O.append("\x1B[?2026l"),O.flush(),this.cursorRow=B,this.hardwareCursorRow=B}this.positionHardwareCursor(p,c.length),this.previousLines=c,this.previousKittyImageIds=this.collectKittyImageIds(c),this.previousWidth=e,this.previousHeight=t,this.previousViewportTop=o;return}if(T<o){y(`firstChanged < viewportTop (${T} < ${o})`),m(!0,!0);return}let _=new Do(O=>this.terminal.write(O));_.append("\x1B[?2026h"),_.append(this.deleteChangedKittyImages(T,b));let F=o+t-1,A=R?T-1:T;if(A>F){let O=Math.max(0,Math.min(t-1,u-o)),B=t-1-O;B>0&&_.append(`\x1B[${B}B`);let z=A-F;_.append(`\r
|
|
123
123
|
`.repeat(z)),o+=z,a+=z,u=A}let $=l(A);$>0?_.append(`\x1B[${$}B`):$<0&&_.append(`\x1B[${-$}A`),_.append(R?`\r
|
|
124
124
|
`:"\r");let D=Math.min(b,c.length-1);for(let O=T;O<=D;O++){O>T&&_.append(`\r
|
|
125
125
|
`);let B=c[O],z=Ue(B),ae=z?this.getKittyImageReservedRows(c,O,D):1;if(ae>1){let we=O-a;if(we<0||we+ae>t){y(`kitty image pre-clear would scroll (${we} + ${ae} > ${t})`),m(!0);return}_.append("\x1B[2K");for(let ce=1;ce<ae;ce++)_.append(`\r
|
|
@@ -204,7 +204,7 @@ Provider: ${n.errorProviderId?at(n.errorProviderId):"configured"}`}var Dr=class{
|
|
|
204
204
|
`).trimStart().startsWith("!")}shouldAutoTriggerCompletion(){return!1}shouldTriggerFileCompletion(e,t,i){return this.word(e,t,i)!==void 0}async getSuggestions(e,t,i,s){let r=this.word(e,t,i);if(!r)return null;let o=await this.source.complete(r.value,this.cwd(),r.command,r.directoriesOnly,s.signal);return s.signal.aborted||o.length===0?null:{prefix:`!${r.value}`,applyOnEnter:!1,items:o.map(a=>({value:iw(a.value,this.source.windows),label:C(`${a.value.split("/").filter(Boolean).at(-1)??a.value}${a.directory?"/":""}`),description:r.command?"Command":C(a.value)}))}}applyCompletion(e,t,i,s){let r=this.word(e,t,i);if(!r)return{lines:e,cursorLine:t,cursorCol:i};let o=e[t]??"",a=o.slice(r.end),u=s.label.endsWith("/")||/^\s/u.test(a)?"":" ",l=`${s.value}${u}`,c=[...e];return c[t]=`${o.slice(0,r.start)}${l}${a}`,{lines:c,cursorLine:t,cursorCol:r.start+l.length}}word(e,t,i){if(!this.isShellInput(e)||t!==0)return;let s=e[0]??"",r=/^\s*!!?/u.exec(s);if(!r||i<r[0].length)return;let o=r[0].length,a="",u=!1,l="",c=!0,p="",m=this.source.windows?"`":"\\";for(let y=o;y<i;y+=1){let T=s[y];if(u){l+=T,u=!1;continue}if(T===m&&a!=="'"){if(!this.source.windows&&a==='"'&&!/[\\$`"\n]/u.test(s[y+1]??"")){l+=T;continue}u=!0;continue}if(a){if(T===a)a="";else{if(a==='"'&&/[$`]/u.test(T))return;l+=T}continue}if(T==='"'||T==="'"){a=T;continue}if(/[$`(){}<>]/u.test(T))return;/\s/u.test(T)||/[|;&]/u.test(T)?(l&&c&&(p=l,c=!1),/[|;&]/u.test(T)&&(c=!0,p=""),o=y+1,l=""):l+=T}if(u||c&&l.length===0)return;let f=i;for(;f<s.length;f+=1){let y=s[f];if(u){u=!1;continue}if(y===m&&a!=="'"){u=!0;continue}if(a){if(a==='"'&&/[$`]/u.test(y))return;y===a&&(a="");continue}if(/[$`(){}]/u.test(y))return;if(y==='"'||y==="'"){a=y;continue}if(/[\s|;&<>]/u.test(y))break}return{start:o,end:f,value:l,command:c,directoriesOnly:["cd","Set-Location"].includes(p)}}};var i3=4,s3=6;function rw(n,e,t=Ic){return ow(t,[],n,e)}function ow(n,e,t,i,s){return new Xf(n,e,t,i,s)}function aw(n){let e=new Set([...wc,...Sx].flatMap(i=>[i.name,...i.aliases??[]].map(s=>s.toLocaleLowerCase()))),t=new Set;return(n.skills??[]).flatMap(i=>{let s=i.name.trim().toLocaleLowerCase();return i.enabled===!1||e.has(s)||t.has(s)||!s||s.length>128||s!==C(s)||/[\s/]/u.test(s)?[]:(t.add(s),[{name:s,description:r3(i.displayDescription??i.description),category:"Capability",invocationKind:"skill",argumentHint:"[instructions]",usage:`/${s} [instructions]`,composerTemplate:`/${s} `}])}).sort((i,s)=>i.name.localeCompare(s.name))}function r3(n){let e=n?C(n).trim():"";return e?`[Skill] ${e}`:"[Skill]"}var Gc=class{constructor(e){this.options=e;this.commandCatalog=e.commandCatalog}snapshot;refreshKey;refreshSequence=0;stopped=!1;commandCatalog;autocompleteManagedTokenPresent;autocompleteSessionKey;autocompleteHasLiveRun;autocompleteSignature;pendingAutocomplete;contextInspection;stop(){this.stopped=!0,this.refreshSequence+=1,this.snapshot=void 0,this.pendingAutocomplete=void 0,this.closeContextInspection()}setCommandCatalog(e){this.commandCatalog=e,this.refreshAutocomplete()}schedule(e){if(this.isStopped())return;this.reconcileContextInspection(e.session?.sessionId);let t=e.session?`${e.session.sessionId}:${e.session.parentSessionId??""}`:"";(this.autocompleteManagedTokenPresent!==(e.account?.managedTokenPresent===!0)||this.autocompleteSessionKey!==t||this.autocompleteHasLiveRun!==this.hasLiveRun(e))&&this.refreshAutocomplete();let i=e.session?.sessionId;if(!i){this.snapshot=void 0,this.refreshKey=void 0;return}let s=`${i}:${this.options.liveRunId(e)??"idle"}:${e.status}`;this.refreshKey!==s&&this.refresh().catch(()=>{})}async refresh(e=!1){if(this.isStopped())return;let t=this.options.controller.snapshot(),i=t.session;if(this.reconcileContextInspection(i?.sessionId),!i){this.refreshSequence+=1,this.snapshot=void 0,this.refreshAutocomplete();return}let s=`${i.sessionId}:${this.options.liveRunId()??"idle"}:${t.status}`;if(!e&&this.refreshKey===s)return;this.refreshKey=s;let r=++this.refreshSequence;this.snapshot?.sessionId!==i.sessionId&&(this.snapshot=void 0);let o;try{o=await this.options.runtime.getActiveRun(i.sessionId)}catch{o=void 0}this.isStopped()||r!==this.refreshSequence||this.options.controller.snapshot().session?.sessionId!==i.sessionId||(this.snapshot=o?.sessionId===i.sessionId?{...o,actions:{...o.actions}}:void 0,this.refreshAutocomplete(),this.options.onChanged())}currentSnapshot(){if(this.snapshot)return{...this.snapshot,actions:{...this.snapshot.actions}}}refreshAutocomplete(){let e=this.options.controller.snapshot();this.autocompleteManagedTokenPresent=e.account?.managedTokenPresent===!0,this.autocompleteSessionKey=e.session?`${e.session.sessionId}:${e.session.parentSessionId??""}`:"",this.autocompleteHasLiveRun=this.hasLiveRun(e);let t=[...this.commandCatalog?.searchableCommands??Ic],i=this.options.skillCommands(),s=typeof this.options.workspaceRoots=="function"?this.options.workspaceRoots():this.options.workspaceRoots??this.options.workspaceDir,r=o3(t,i,s);if(r===this.autocompleteSignature){this.pendingAutocomplete=void 0;return}if(r===this.pendingAutocomplete?.signature)return;let o=ow(t,i,s,this.options.runtime,()=>this.options.controller.snapshot().session?.workspaceDir??this.options.workspaceDir);if((this.options.editor.getText?.()??"").length>0){this.pendingAutocomplete={provider:o,signature:r};return}this.applyAutocompleteProvider(o,r)}onEditorChanged(){if((this.options.editor.getText?.()??"").length>0||!this.pendingAutocomplete)return;let{provider:e,signature:t}=this.pendingAutocomplete;this.applyAutocompleteProvider(e,t)}applyAutocompleteProvider(e,t){this.pendingAutocomplete=void 0,this.autocompleteSignature=t,this.options.editor.setAutocompleteProvider(e)}showHelp(){if(this.isStopped())return;let e=new Mc({commands:[...this.commandCatalog?.discoverableCommands??Ic],queueEnabled:this.options.queueEnabled,keybindings:this.options.keybindings,onCancel:()=>this.options.closeInteraction(e),maxRows:()=>{let t=Number.isFinite(this.options.terminal.rows)?this.options.terminal.rows:24;return Math.max(i3,t-s3)}});this.options.showInteraction(e)}async showContext(){if(this.isStopped())return;let e=this.options.requireSession();if(!e)return;let t=new Ur({title:"Context",loadingMessage:"Loading context details\u2026",maxRows:()=>{let i=Number.isFinite(this.options.terminal.rows)?this.options.terminal.rows:24;return Math.max(4,i-4)},requestRender:this.options.onChanged,onCancel:()=>this.closeContextInspection(t),onDispose:()=>{this.contextInspection?.panel===t&&(this.contextInspection=void 0)}});this.showContextInspection(e.sessionId,t);try{let i=await this.options.runtime.getContextSnapshot(e.sessionId);if(this.isStopped())return;if(this.options.controller.snapshot().session?.sessionId!==e.sessionId){this.closeContextInspection(t);return}if(!this.isCurrentContextInspection(t))return;let s=$x(i);t.setResult(Fx(i),s)}catch(i){if(this.isStopped())return;if(this.options.controller.snapshot().session?.sessionId!==e.sessionId){this.closeContextInspection(t);return}if(!this.isCurrentContextInspection(t))return;t.setError(Ac(i)?"Context inspection is not supported by this Runtime.":L(i,{summary:"Couldn't load context details.",nextStep:"Retry /context."}))}}showContextInspection(e,t){this.closeContextInspection(),this.contextInspection={sessionId:e,panel:t},this.options.showInteraction(t)}closeContextInspection(e){let t=this.contextInspection;return!t||e&&t.panel!==e?!1:(this.contextInspection=void 0,this.options.closeInteraction(t.panel))}reconcileContextInspection(e){this.contextInspection?.sessionId!==e&&this.closeContextInspection()}isCurrentContextInspection(e){return this.contextInspection?.panel===e}async handle(e){return h3(e,"/steer")?this.steer(e.slice("/steer".length)):!1}async steer(e,t={}){if(this.isStopped())return!1;let i=this.options.requireSession();if(!i)return!1;let s=e.trim();if(!s)return this.options.append("Usage: /steer <message>"),!1;let r=`run_action_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,10)}`,o=[r,t.displayContent??s,Date.now(),gn(t.transcriptAttachments??[])];t.requireActiveTurn||t.requestedTurnId||this.hasLiveRun(this.options.controller.snapshot())?this.options.controller.projectOptimisticUserMessage(...o,"pending-steer"):this.options.controller.projectOptimisticUserMessage(...o),this.options.onChanged();try{await this.options.controller.requireLoginForAgentAction?.(),await this.refresh(!0)}catch(m){throw this.options.controller.removeOptimisticUserMessage(r),m}if(this.isStopped()||this.options.controller.snapshot().session?.sessionId!==i.sessionId)return this.options.controller.removeOptimisticUserMessage(r),!1;let a=this.snapshot?.sessionId===i.sessionId?this.snapshot:void 0,u=t.requestedTurnId??(t.requireActiveTurn?a?.turnId:void 0),l=!u||a?.turnId===u,c=!u&&!t.requireActiveTurn&&(a?.state==="idle"||a?.state==="terminal");if(!a||!l||!a.actions.steer&&!c)return this.options.controller.removeOptimisticUserMessage(r),this.options.append(a?.state==="decision-blocked"?"Resolve the pending Runtime decision first.":"Steer is not available for the current work.","warning"),!1;let p;try{p=await this.options.runtime.steer({sessionId:i.sessionId,source:"api",message:{content:s,...t.displayContent?{displayContent:t.displayContent}:{},...t.attachments?.length?{attachments:t.attachments}:{}},producerId:"mcode",idempotencyKey:r,...u?{requestedTurnId:u}:{}})}catch(m){return this.options.controller.removeOptimisticUserMessage(r),this.isStopped()||this.options.controller.snapshot().session?.sessionId!==i.sessionId||this.options.append(L(m,{summary:"Couldn't steer current work.",nextStep:"Retry /steer.",preservation:"Your message was not applied."}),"warning"),!1}if(this.isStopped()||this.options.controller.snapshot().session?.sessionId!==i.sessionId)return this.options.controller.removeOptimisticUserMessage(r),!0;this.options.controller.acceptOptimisticUserMessage(r,p.turnId,Date.now(),p.mode==="steered"?"runtime-message":"immediate"),(p.mode==="activated"||p.turnId!==a.turnId)&&this.options.adoptRuntimeTurn?.(i.sessionId,p.turnId,Date.now()),p.mode==="activated"&&p.completion.catch(()=>{});try{await this.refresh(!0)}catch(m){this.options.append(L(m,{summary:"Steer was accepted, but this view could not refresh.",nextStep:"Reopen the session to sync it."}),"warning")}return!0}isStopped(){return this.stopped||!!this.options.isStopped?.()}hasLiveRun(e){return!!(this.options.liveRunId(e)||this.options.controller.hasInProcessRun?.())}};function o3(n,e,t){let i=s=>[s.name,s.description,s.invocationKind??"",s.argumentHint??"",!!s.getArgumentCompletions,s.composerTemplate??"",...s.aliases??[]];return JSON.stringify({builtInCommands:n.map(i),skillCommands:e.map(i),workspace:typeof t=="string"?t:t.map(({path:s,label:r,primary:o})=>[s,r??"",o===!0])})}var Xf=class{constructor(e,t,i,s,r){this.workspaceFiles=s;this.workspaceRoots=l3(i),this.workspaceDir=this.workspaceRoots.find(c=>c.primary)?.path??this.workspaceRoots[0]?.path??"",this.shellProvider=new Vc(r??(()=>this.workspaceDir));let o=[...e,...t],a=[...e.filter(c=>c.discoverability!=="search-only"),...t];this.skillNames=new Set(t.map(c=>c.name));let u=o.map(Yf),l=o.flatMap(c=>{let p=c.aliases??[],m=p.length>0?`${c.name} (${p.join(", ")})`:c.name;for(let f of[c.name,...p])this.commandLabels.set(f,{commandName:c.name,label:m,description:c.description});return p.map(f=>({...Yf(c),name:f}))});this.baseProvider=new Mi([...u,...l],this.workspaceDir),this.defaultProvider=new Mi(a.map(Yf),this.workspaceDir),this.aliasProvider=new Mi([...u,...l],this.workspaceDir)}triggerCharacters=["@"];shellProvider;defaultProvider;baseProvider;aliasProvider;commandLabels=new Map;skillNames;workspaceRoots;workspaceDir;async getSuggestions(e,t,i,s){if(this.shellProvider.isShellInput(e))return this.shellProvider.getSuggestions(e,t,i,s);let r=(e[t]??"").slice(0,i),o=Qf(r);if(o)return this.getWorkspaceFileSuggestions(o,s.signal);if(!r.startsWith("/"))return null;let u=await(r==="/"?this.defaultProvider:/^\/\S+$/u.test(r)?this.aliasProvider:this.baseProvider).getSuggestions(e,t,i,{...s,force:!1});if(!u)return null;if(u.kind==="argument")return u;let l=new Set,c=u.items.map(y=>{let T=this.commandLabels.get(y.value);return T?{...y,label:T.label,description:T.description}:y}).filter(y=>{let T=this.commandLabels.get(y.value)?.commandName??y.value;return l.has(T)?!1:(l.add(T),!0)}),p=/^\/(\S+)$/u.exec(r)?.[1]?.toLocaleLowerCase(),m=p?c.filter(y=>y.value.toLocaleLowerCase().startsWith(p)):[],f=m.length>0?m:c;return{...u,items:r.startsWith("/")&&!r.includes(" ")?[...f.filter(y=>!this.skillNames.has(y.value)),...f.filter(y=>this.skillNames.has(y.value))]:f}}applyCompletion(e,t,i,s,r){return this.shellProvider.isShellInput(e)?this.shellProvider.applyCompletion(e,t,i,s):this.baseProvider.applyCompletion(e,t,i,s,r)}shouldAutoTriggerCompletion(e,t,i){if(this.shellProvider.isShellInput(e))return!1;let s=(e[t]??"").slice(0,i);if(Qf(s)===void 0)return this.baseProvider.shouldAutoTriggerCompletion(e,t,i)}shouldTriggerFileCompletion(e,t,i){if(this.shellProvider.isShellInput(e))return this.shellProvider.shouldTriggerFileCompletion(e,t,i);let s=e[t]??"";return Qf(s.slice(0,i))!==void 0}async getWorkspaceFileSuggestions(e,t){let i=a3(e);if(i===void 0||!wa(i))return null;try{let s=i===""||i.endsWith("/")?await this.listWorkspaceDirectory(i,t):await this.searchWorkspace(i,t);return s.length>0?{items:s,prefix:e}:null}catch{return null}}async listWorkspaceDirectory(e,t){let i=e?e.slice(0,-1):void 0;return this.workspaceFiles?.listWorkspaceFileTreeCandidates?(await this.workspaceFiles.listWorkspaceFileTreeCandidates({roots:this.workspaceRoots,...i?{path:i}:{}},t)).flatMap(o=>this.toMultiRootTreeItem(o)):this.workspaceFiles?.listWorkspaceFileTree?(await this.workspaceFiles.listWorkspaceFileTree(this.workspaceDir,i,t)).flatMap(r=>u3(r)):[]}async searchWorkspace(e,t){if(this.workspaceFiles?.searchWorkspaceFileCandidates){let r=await this.workspaceFiles.searchWorkspaceFileCandidates({roots:this.workspaceRoots,query:e,limit:20},t),o=new Set;return r.flatMap(a=>{let u=Wr(a.path),l=this.workspaceRoots.find(p=>p.path===a.workspaceDir);if(!u||!l||!wa(u))return[];let c=`${l.path}\0${u}`;return o.has(c)?[]:(o.add(c),[sw(l,u,!1)])})}if(!this.workspaceFiles?.searchWorkspaceFiles)return[];let i=await this.workspaceFiles.searchWorkspaceFiles(this.workspaceDir,e,20,t),s=new Set;return i.flatMap(r=>{let o=Wr(r);return!o||!wa(o)||s.has(o)?[]:(s.add(o),[{value:Jf(o,!1),label:o.split("/").at(-1)??o,description:o}])})}toMultiRootTreeItem(e){let t=Wr(e.path),i=this.workspaceRoots.find(s=>s.path===e.workspaceDir);return!t||!i||!wa(t)?[]:[sw(i,t,e.type==="directory",e.name)]}};function Qf(n){return n.match(/(?:^|[\s])(@(?:"[^"]*|[^\s]*))$/u)?.[1]}function a3(n){if(!n.startsWith("@"))return;let e=n.slice(1);return e.startsWith('"')?Wr(e.slice(1,e.endsWith('"')?-1:void 0),!0):Wr(e,!0)}function wa(n){return n.startsWith("/")||/^[A-Za-z]:[\\/]/u.test(n)?!1:!n.split("/").some(e=>e==="..")}function Wr(n,e=!1){let t=n.replaceAll("\\","/").replace(/^\.\/+/u,"");if(!(!t&&!e||t.includes("\0")))return t}function u3(n){let e=Wr(n.path);if(!e||!wa(e))return[];let t=n.type==="directory";return[{value:Jf(e,t),label:`${n.name}${t?"/":""}`}]}function Jf(n,e){let t=`${n}${e&&!n.endsWith("/")?"/":""}`;return/\s/u.test(t)?`@"${t}"`:`@${t}`}function l3(n){let e=typeof n=="string"?[{path:n,primary:!0}]:n,t=new Set,i=e.flatMap(s=>{let r=s.path.trim();return!r||t.has(r)?[]:(t.add(r),[{...s,path:r}])});if(i.length>0&&!i.some(s=>s.primary)){let s=i[0];s&&(i[0]={...s,primary:!0})}return i}function sw(n,e,t,i){let s=n.label?.trim()||c3(n.path),r=n.primary===!0,o=r?e:d3(n.path,e),a=i??e.split("/").at(-1)??e;return{value:Jf(o,t),label:`${a}${t?"/":""}${r?"":` \xB7 ${s}`}`,description:`${s} \xB7 ${e}`}}function c3(n){let e=n.replace(/[\\/]+$/u,"");return e.split(/[\\/]/u).at(-1)||e}function d3(n,e){let t=n.includes("\\")&&!n.includes("/")?"\\":"/";return`${n.replace(/[\\/]+$/u,"")}${t}${e.replaceAll("/",t)}`}function Yf({name:n,description:e,argumentHint:t,getArgumentCompletions:i}){return{name:n,description:e,...t?{argumentHint:t}:{},...i?{getArgumentCompletions:i}:{}}}function h3(n,e){return n===e||n.startsWith(`${e} `)}var p3=80,Zf=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],m3=1500,f3=["guide","details","interrupt"],g3={guide:"run.submit-guidance",details:"composer.toggle-details",interrupt:"app.interrupt"},y3={guide:"steer",details:"details",interrupt:"stop"},Yc=class{state={phase:"idle"};animate;now;requestRender;chalk;keybindings;frameIndex=0;activeStartedAtMs;animationTimer;animationPaused=!1;constructor(e,t={}){this.animate=t.animate??!0,this.now=t.now??Date.now,this.requestRender=t.requestRender??(()=>{}),this.chalk=t.chalk??h,this.keybindings=t.keybindings,this.setState(e)}setState(e){let t=zc(this.state.phase),i=zc(e.phase),s=e.runId!==void 0&&e.runId===this.state.runId,r=uw(e)!==uw(this.state),o=i&&(!t||e.runId!==void 0&&e.runId!==this.state.runId);this.state=e,r&&(this.frameIndex=0),e.startedAtMs!==void 0?this.activeStartedAtMs=e.startedAtMs:o&&!s?(this.activeStartedAtMs=this.now(),this.frameIndex=0):!i&&!s&&(this.activeStartedAtMs=void 0,this.frameIndex=0),i&&this.animate&&!this.animationPaused?this.startAnimation():this.stopAnimation()}setAnimationPaused(e){if(this.animationPaused!==e){if(this.animationPaused=e,e){this.stopAnimation();return}this.animate&&zc(this.state.phase)&&this.startAnimation()}}invalidate(){}render(e){let t=v3(e);if(t===0||this.state.phase==="idle")return[];if(this.state.phase==="error"&&this.state.errorSettled&&!this.state.message?.trim())return[];let i=T3(this.state),s=zc(this.state.phase),r=this.animate&&s?Zf[this.frameIndex]??Zf[0]:i.icon,o=`${this.chalk.hex(d.dim)(" ")}${this.chalk.bold.hex(i.color)(r)} ${this.chalk.bold.hex(i.color)(i.label)}`,a=s?this.now()-(this.activeStartedAtMs??this.now()):0,u=s&&a>=m3?` ${this.chalk.hex(d.muted)(Bi(a/1e3))}`:"",l=this.state.draftLabel?.trim()?`${this.chalk.hex(d.dim)(" \xB7 ")}${this.chalk.hex(d.muted)(Qc(this.state.draftLabel))}`:"",c=b3(this.state.outputTokensPerSecond,this.state.outputTokensPerSecondEstimated===!0,this.chalk),p=`${o}${u}${c}${l}`;return[E(this.fitControls(p,t),t,this.chalk.hex(d.dim)("\u2026"))]}dispose(){this.stopAnimation()}fitControls(e,t){let i=f3.filter(s=>this.state.controls?.includes(s));for(let s=0;s<i.length;s+=1){let r=`${e}${this.renderControls(i.slice(s))}`;if(x(r)<=t)return r}return e}renderControls(e){return e.map(t=>`${this.chalk.hex(d.dim)(" \xB7 ")}${this.chalk.hex(d.muted)(`${ye(g3[t],this.keybindings)} ${y3[t]}`)}`).join("")}startAnimation(){this.animationTimer||(this.animationTimer=setInterval(()=>{this.frameIndex=(this.frameIndex+1)%Zf.length,this.requestRender()},p3),this.animationTimer.unref())}stopAnimation(){this.animationTimer&&(clearInterval(this.animationTimer),this.animationTimer=void 0)}};function T3(n){return n.phase==="loading"?{icon:"\u25C7",label:n.loadingTarget==="session"?"Loading session":"Loading",color:d.signal}:n.phase==="running"?{icon:"\u25C7",label:"Running",color:d.orbit}:n.phase==="retrying"?{icon:"\u25C7",label:n.message?Qc(n.message):"Retrying model request",color:d.orbit}:n.phase==="reconnecting"?{icon:"\u25C7",label:n.message?`Reconnecting \xB7 ${Qc(n.message)}`:"Reconnecting",color:d.signal}:n.phase==="compacting"?{icon:"\u25C7",label:"Compacting context",color:d.orbit}:n.phase==="stopping"?{icon:"!",label:"Stopping response",color:d.error}:{icon:"\xD7",label:n.message?`Error \xB7 ${Qc(n.message)}`:"Runtime error",color:d.error}}function zc(n){return n!=="idle"&&n!=="error"}function b3(n,e,t){return typeof n!="number"||!Number.isFinite(n)||n<=0?"":`${t.hex(d.dim)(" \xB7 ")}${t.bold.hex(d.signal)(`\u26A1 ${e?"~":""}${n.toFixed(1)} tok/s`)}`}function uw(n){return`${n.phase}${n.loadingTarget??""}${n.message??""}`}function Qc(n){return C(n).replace(/\s+/gu," ").trim()}function v3(n){return Number.isFinite(n)?Math.max(0,Math.floor(n)):0}function Xc(n,e=24){let t=lw(n),i=lw(e),s=t<48||i<12,r=!s&&t>=72,o=s?"compact":r?"wide":"standard";return{columns:t,rows:i,density:o,welcome:o==="compact"?"compact":o==="wide"?"split":"stacked",horizontalPadding:o==="compact"?0:o==="wide"?2:1,transcriptOverscanRows:o==="compact"?4:o==="wide"?12:8}}function lw(n){return Number.isFinite(n)?Math.max(1,Math.floor(n)):1}var S3=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,Zc=class{constructor(e,t,i=()=>"document"){this.terminal=e;this.parts=t;this.viewport=i;let s={render:f=>this.renderFullscreenBody(f),handleMouse:f=>this.handleFullscreenBodyMouse(f),invalidate:()=>{this.pendingFullscreenFrame=void 0,this.fullscreenBodyMouseTarget=void 0,this.fullscreenBodyMouseRange=void 0}},r=this.createFullscreenFooterSection(0),o=this.createFullscreenFooterSection(1),a=this.createFullscreenFooterSection(2),u=this.createFullscreenFooterSection(3),l=this.createFullscreenFooterSection(4),c=this.createFullscreenFooterSection(5),p=new wt([{component:r,basis:"auto",shrink:1,minSize:0},{component:o,basis:"auto",shrink:1,minSize:0},{component:a,basis:"auto",shrink:1,minSize:0},{component:u,basis:"auto",shrink:1,minSize:0},{component:l,basis:"auto",shrink:1,minSize:Jc(this.parts.interaction)?1:0,visible:()=>!this.isActiveInteraction()},{component:c,basis:"auto",shrink:1,minSize:1}]),m={render:f=>this.renderFullscreenFooter(f),invalidate:()=>{this.pendingFullscreenFrame=void 0,this.fullscreenFooterFrame=void 0},[Vt]:()=>p[Vt]()};this.fullscreenBodyViewport=new Vn(s,{follow:"end",primary:!0,overscroll:"contain"}),this.fullscreenLayoutRoot=new wt([{component:this.fullscreenBodyViewport,basis:0,grow:1,shrink:1,minSize:1},{component:m,basis:"auto",shrink:1,minSize:1}])}fullscreenLayoutRoot;fullscreenBodyViewport;pendingFullscreenFrame;fullscreenFooterFrame;fullscreenBodyMouseTarget;fullscreenBodyHorizontalPadding=0;fullscreenBodyMouseRange;followBottom(){this.fullscreenBodyViewport.scrollToEnd()}invalidate(){this.parts.welcome.invalidate(),this.parts.notice?.invalidate(),this.parts.transcript.invalidate(),this.parts.interaction.invalidate(),this.parts.activity.invalidate(),this.parts.goal?.invalidate(),this.parts.followUp.invalidate(),this.parts.tasks?.invalidate(),this.parts.composer.invalidate(),this.parts.status.invalidate(),this.pendingFullscreenFrame=void 0,this.fullscreenFooterFrame=void 0,this.fullscreenBodyMouseTarget=void 0,this.fullscreenBodyMouseRange=void 0}getSurface(){return this.parts.surface()}render(e){let t=dw(e,this.terminal.rows),i=this.getSurface(),s=A=>Ki(A.render(t.contentWidth),t.horizontalPadding),r=Jc(this.parts.interaction)?this.parts.interaction.isActive():void 0,o=_s(this.parts.interaction)&&r===!0,a=r===!1||o?[]:s(this.parts.interaction),u=r??a.length>0,l=s(this.parts.activity),c=u?[]:s(this.parts.composer),p=u?[]:s(this.parts.followUp),m=!u&&this.parts.goal?s(this.parts.goal):[],f=i==="welcome"&&this.parts.notice?s(this.parts.notice):[],y=this.renderStatus(t,l.length+c.length+p.length+m.length+f.length+(u?Math.max("fullscreenViewport"in this.parts.interaction&&this.parts.interaction.fullscreenViewport===!0?4:1,a.length):0)+2),T=u&&_s(this.parts.interaction)?Ki(this.parts.interaction.renderViewport(t.contentWidth,Math.max(1,(this.terminal.rows||24)-l.length-y.length-(i==="conversation"?2:0))),t.horizontalPadding):a,b=u?[]:this.renderTasks(t,m.length+p.length+l.length+c.length+y.length,i==="conversation"?2:Math.max(1,f.length+1));if(i==="welcome"){if(u)return this.fitDocumentFrame(this.viewport()==="fixed"?[T,l,c,y]:[T,m,p,b,l,c,y]);let A=[...f.length>0?[f]:[],m,p,b,l,c,y],$=A.reduce((O,B)=>O+B.length,0),D=Math.max(1,this.terminal.rows-$),U=this.viewport()==="fixed"&&_s(this.parts.welcome)?Ki(this.parts.welcome.renderViewport(t.contentWidth,D),t.horizontalPadding):s(this.parts.welcome);return this.fitDocumentFrame([U,...A])}let S=u&&this.viewport()==="fixed"?[T,l,c,y]:[T,m,p,b,l,c,y],M=s(this.parts.transcript),R=s(this.parts.welcome),F=[e1(R,M),M.length>0?[""]:[]];return this.fitDocumentFrame([...F,...S])}renderFullscreenBody(e){let t=this.resolveFullscreenFrame(e);return this.pendingFullscreenFrame=void 0,this.fullscreenBodyMouseTarget=t.bodyMouseTarget,this.fullscreenBodyHorizontalPadding=t.horizontalPadding,this.fullscreenBodyMouseRange=t.bodyMouseRange,[...t.body]}handleFullscreenBodyMouse(e){let t=this.fullscreenBodyMouseTarget,i=this.fullscreenBodyMouseRange;return!t||!i||!C3(t)||e.y<i.start||e.y>=i.end?!1:t.handleMouse({...e,x:Math.max(0,e.x-this.fullscreenBodyHorizontalPadding),y:e.y-i.start})}createFullscreenFooterSection(e){return{render:t=>[...(this.fullscreenFooterFrame?.width===t?this.fullscreenFooterFrame.frame:this.resolveFullscreenFrame(t)).footerSections[e]??[]],invalidate:()=>{this.pendingFullscreenFrame=void 0,this.fullscreenFooterFrame=void 0}}}resolveFullscreenFrame(e){let t=this.pendingFullscreenFrame;if(t?.width===e)return t.frame;let i=this.fullscreenFooterFrame;if(i?.width===e)return i.frame;let s=this.composeFullscreenFrame(e);return this.pendingFullscreenFrame={width:e,frame:s},this.fullscreenFooterFrame={width:e,frame:s},s}renderFullscreenFooter(e){let t=this.composeFullscreenFrame(e);return this.pendingFullscreenFrame={width:e,frame:t},this.fullscreenFooterFrame={width:e,frame:t},t.footerSections.flatMap(i=>i)}isActiveInteraction(){return Jc(this.parts.interaction)&&this.parts.interaction.isActive()}composeFullscreenFrame(e){let t=dw(e,this.terminal.rows),i=this.getSurface(),s=M=>[...Ki(M.render(t.contentWidth),t.horizontalPadding)],r=s(this.parts.activity),o=Jc(this.parts.interaction)?this.parts.interaction.isActive():void 0,a=_s(this.parts.interaction)&&"fullscreenViewport"in this.parts.interaction&&this.parts.interaction.fullscreenViewport===!0?this.parts.interaction:void 0,u=o===!1||a?[]:s(this.parts.interaction);if(o??u.length>0){let M=this.renderStatus(t,r.length+(a?4:Math.max(1,u.length))),R=a?Ki(a.renderViewport(t.contentWidth,Math.max(1,(this.terminal.rows||24)-r.length-M.length)),t.horizontalPadding):u,_=s(this.parts.welcome),F=s(this.parts.transcript),$=[...e1(_,F),...F.length>0&&R.length>0?[""]:[]];return{body:[...$,...R],footerSections:[[],[],[],r,[],M],bodyMouseTarget:this.parts.interaction,bodyMouseRange:{start:$.length,end:$.length+R.length},horizontalPadding:t.horizontalPadding}}let c=this.parts.goal?s(this.parts.goal):[],p=s(this.parts.followUp),m=s(this.parts.composer),f=i==="welcome"&&this.parts.notice?s(this.parts.notice):[],y=this.renderStatus(t,c.length+p.length+r.length+m.length+f.length+1),T=this.renderTasks(t,c.length+p.length+r.length+m.length+y.length,i==="conversation"?1:Math.max(1,f.length+1));if(i==="welcome"){let M=Math.max(1,(this.terminal.rows||24)-c.length-p.length-T.length-r.length-m.length-y.length);return{body:[..._s(this.parts.welcome)?Ki(this.parts.welcome.renderViewport(t.contentWidth,M),t.horizontalPadding):s(this.parts.welcome),...f],footerSections:[c,p,T,r,m,y],horizontalPadding:t.horizontalPadding}}let b=s(this.parts.welcome),S=s(this.parts.transcript);return{body:[...e1(b,S),...S.length>0?[""]:[]],footerSections:[c,p,T,r,m,y],horizontalPadding:t.horizontalPadding}}renderStatus(e,t){let i=this.parts.status,s=_s(i)?i.renderViewport(e.contentWidth,Math.max(0,(this.terminal.rows||24)-t)):i.render(e.contentWidth);return[...Ki(s,e.horizontalPadding)]}renderTasks(e,t,i){let s=this.parts.tasks;if(!s)return[];let r=this.viewport()==="fixed"&&_s(s)?s.renderViewport(e.contentWidth,Math.max(0,(this.terminal.rows||24)-t-i)):s.render(e.contentWidth);return[...Ki(r,e.horizontalPadding)]}fitDocumentFrame(e){let t=e.flatMap(r=>r),i=this.viewport()==="fixed"?Math.max(1,this.terminal.rows||24):Number.POSITIVE_INFINITY,s=Math.max(0,t.length-i);return s>0?t.slice(s):t}};function _s(n){return"renderViewport"in n&&typeof n.renderViewport=="function"}function Jc(n){return"isActive"in n&&typeof n.isActive=="function"}function C3(n){return"handleMouse"in n&&typeof n.handleMouse=="function"}function e1(n,e){if(n.length===0)return[...e];if(e.length===0)return[...n];let t=[...n];for(;t.length>0&&cw(t.at(-1)??"");)t.pop();return[...t,...cw(e[0]??"")?[]:[""],...e]}function cw(n){return ge(n).trim().length===0}function dw(n,e){let t=Xc(n,e||24),i=Math.min(t.horizontalPadding,Math.max(0,Math.floor((t.columns-1)/2)));return{contentWidth:Math.max(1,t.columns-i*2),horizontalPadding:i}}function Ki(n,e){if(e===0)return n;let t=" ".repeat(e);return n.map(i=>{if(i.length===0)return i;let s=i.match(S3)?.[0];return s?`${s}${t}${i.slice(s.length)}`:`${t}${i}`})}var x3=[{id:"goal",command:"goal",text:"Tip: /goal keeps multi-step work focused on a finish line",shortText:"Tip: /goal tracks multi-step work",weight:2},{id:"context",command:"context",text:"Tip: /context shows the current Session context budget",shortText:"Tip: /context shows context",weight:2},{id:"steer",command:"steer",text:"Tip: /steer guides a response without interrupting it",shortText:"Tip: /steer guides a live run",weight:2},{id:"plugins",command:"plugins",text:"Tip: /plugins manages installed capabilities",shortText:"Tip: /plugins manages Plugins",weight:2},{id:"sessions",command:"sessions",text:"Tip: /sessions resumes earlier conversations",shortText:"Tip: /sessions resumes work"},{id:"fork",command:"fork",text:"Tip: /fork branches the current conversation",shortText:"Tip: /fork branches a Session"},{id:"rewind",command:"rewind",text:"Tip: /rewind restores an earlier turn",shortText:"Tip: /rewind restores a turn"},{id:"compact",command:"compact",text:"Tip: /compact frees context in a long conversation",shortText:"Tip: /compact frees context"},{id:"skills",command:"skills",text:"Tip: /skills lists available Skills",shortText:"Tip: /skills lists Skills"},{id:"feedback",command:"feedback",text:"Tip: /feedback previews redacted feedback before upload",shortText:"Tip: /feedback previews reports"}];function w3(){return x3.map(n=>({id:n.id,command:n.command,text:n.text,shortText:n.shortText,...n.weight===void 0?{}:{weight:n.weight}}))}var Ia=w3(),I3=3e4;function hw(n){let e=n.map(s=>({tip:s,weight:Math.max(1,Math.trunc(s.weight??1)),current:0})),t=e.reduce((s,r)=>s+r.weight,0),i=[];for(let s=0;s<t;s+=1){let r=e[0];for(let o of e)o.current+=o.weight,(!r||o.current>r.current)&&(r=o);if(!r)break;r.current-=t,i.push(r.tip)}return i}var M3=hw(Ia);function pw(n,e=Ia){let t=e===Ia?M3:hw(e);if(t.length===0)return;let s=(Math.floor(n/I3)%t.length+t.length)%t.length;return t[s]}var ed=class{constructor(e,t,i={}){this.editor=e;this.state=t;this.options=i}setState(e){this.state=e}invalidate(){this.editor.invalidate(),this.options.imagePreview?.invalidate()}render(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;if(t===0)return[];let i=this.state.placeholder===void 0?void 0:C(this.state.placeholder);if(t<=2)return[...this.editor.render(t,i)];let s=t-2,r=this.editor.render(s,i),o=this.state.headerHidden?[]:[E(`${h.hex(d.dim)(" ")}${E3(this.state,s,this.options.supportsShiftEnter?.()===!0,this.options.showTips!==!1,this.options.now?.()??Date.now(),this.options.tips??Ia,this.options.keybindings)}`,t,h.hex(d.dim)("\u2026"))],a=!1,u=!1,l=!1,c=r.map(m=>{let f=A3(m);f&&(u=!u);let y=f?h.hex(_3(this.state))(ge(m)):m;if(u&&!f&&!l){let b=L3(y,this.state);y=b.line,l=b.highlighted}let T=f?h.hex(d.dim)(" "):a?h.hex(d.dim)(" "):h.bold.hex(td(this.state))("\u203A ");return f||(a=!0),E(`${T}${y}`,t,h.hex(d.dim)("\u2026"))}),p=this.state.contextLabel?.trim();return[...this.options.imagePreview?.render(t)??[],...o,...c,...p?[E(`${h.hex(d.dim)(" ")}${h.bold.hex(d.signal)(C(p))}`,t,h.hex(d.dim)("\u2026"))]:[]]}};function E3(n,e,t,i,s,r,o){let a=R3(n,e,t,o),u=n.contextualTip?[...r,n.contextualTip]:r;if(!i||n.surface!=="conversation"&&!n.contextualTip||n.mode!=="message"||n.hint?.trim()||(n.attachmentCount??0)>0||(n.draftCharacterCount??0)>0)return a;let l=pw(s,u);if(!l)return a;for(let c of[l.text,l.shortText]){let p=C(c),m=e-x(a)-x(p);if(!(m<4))return`${a}${" ".repeat(m)}${h.hex(d.muted)(p)}`}return a}function A3(n){let e=ge(n).trim();if(/^─+$/u.test(e)||/^─── [↑↓] \d+ more ─*$/u.test(e))return!0;if(!e.endsWith("..."))return!1;let t=e.slice(0,-3);return/^─{0,3}$/u.test(t)||/^─── ?$/u.test(t)||/^─── [↑↓](?: \d+(?: m(?:o(?:r(?:e)?)?)?)?)? ?$/u.test(t)}function R3(n,e,t,i){let s=k3(n,t,i),r=s.find(p=>x(p)<=e)??s.at(-1)??"",o=td(n),[a="",...u]=r.split(" \xB7 "),l=u.join(" \xB7 ");return l?`${h.bold.hex(o)(a)}${h.hex(d.dim)(" \xB7 ")}${G(l)}`:h.bold.hex(o)(a)}function k3(n,e,t=zn()){let i=P3(n.attachmentCount),s=n.hint?.trim();if(s)return[C(s)];if(n.mode==="blocked")return n.attention==="question"?["Reply required \xB7 choose an answer","Reply required"]:["Reply required \xB7 choose an action","Reply required"];let r=ye("tui.input.submit",t);if(n.mode==="goal")return i?[`Goal \xB7 ${i} \xB7 ${r} start`,`Goal \xB7 ${r} start`,"Goal"]:[`Goal \xB7 ${r} start \xB7 Esc cancel`,`Goal \xB7 ${r} start`,"Goal"];let o=n.inputIntent;if(n.mode==="follow-up"){let l=ye("run.submit-guidance",t),c=ye("run.queue-draft",t);return o&&o.kind!=="empty"?mw(o,i,e,t,{steer:l,queue:c}):i?[`Message \xB7 ${i} \xB7 ${l} steer \xB7 ${c} queue`,`Message \xB7 ${l} steer \xB7 ${c} queue`,`${l} steer \xB7 ${c} queue`,`${c} queue`,"Message"]:[`Message \xB7 ${l} steer \xB7 ${c} queue`,`${l} steer \xB7 ${c} queue`,`${c} queue`,"Message"]}if(n.mode==="working")return["Working"];if((n.draftLineCount??0)>1||(n.draftCharacterCount??0)>1e3){let l=ye("composer.external-editor",t);return[`Long draft \xB7 ${l} edit \xB7 ${r} send`,`Long draft \xB7 ${l} edit`,"Long draft"]}if(o&&o.kind!=="empty")return mw(o,i,e,t);if(i)return[`${i} \xB7 ${r} send`,i,"Message"];if(n.surface==="welcome")return["Start \xB7 @ file \xB7 / autocomplete","Start below"];let u=fw(e,t);return[`Message \xB7 ${r} send \xB7 ${u} newline`,`Message \xB7 ${r} send`,"Message"]}function fw(n,e){let t=e.keys("tui.input.newLine");return t.length===2&&t[0]==="shift+enter"&&t[1]==="ctrl+j"?e.format(n?"shift+enter":"ctrl+j"):ye("tui.input.newLine",e)}function mw(n,e,t,i,s){let r=n.kind;if(r==="empty")return["Message"];let o=gw[r],a=e?` \xB7 ${e}`:"",l=`${`${o.title}${o.qualifier?` \xB7 ${o.qualifier}`:""}`}${a}`,c=`${o.title}${a}`;if(s&&o.action!=="run")return[`${l} \xB7 ${s.steer} steer \xB7 ${s.queue} queue`,`${o.title} \xB7 ${s.steer} steer \xB7 ${s.queue} queue`,`${s.steer} steer \xB7 ${s.queue} queue`,`${s.queue} queue`,o.title];let p=ye("tui.input.submit",i);if(o.action==="send"){let m=fw(t,i);return[`${l} \xB7 ${p} send \xB7 ${m} newline`,`${c} \xB7 ${p} send`,o.title]}return[`${l} \xB7 ${p} ${o.action}`,`${c} \xB7 ${p} ${o.action}`,o.title]}var gw={prompt:{title:"Prompt",action:"send",color:"signal"},bash:{title:"Shell",action:"run",color:"warning"},command:{title:"Command",action:"run",color:"accent"},"command-arguments":{title:"Command",qualifier:"arguments",action:"run",color:"accent"},skill:{title:"Skill",action:"invoke",color:"orbit"},"skill-instructions":{title:"Skill",qualifier:"instructions",action:"invoke",color:"orbit"}};function P3(n){if(n)return`${n} attachment${n===1?"":"s"}`}function td(n){if(n.hintTone==="danger")return d.error;if(n.hintTone==="warning")return d.warning;if(n.mode==="blocked"&&n.attention==="permission")return d.warning;if(n.mode==="goal")return d.orbit;let e=n.inputIntent;return e&&e.kind!=="empty"?d[gw[e.kind].color]:d.signal}function _3(n){return n.inputIntent?.kind==="empty"||!n.inputIntent?d.line:td(n)}function L3(n,e){let t=e.inputIntent?.token;if(!t)return{line:n,highlighted:!1};let i=ge(n),s=i.indexOf(t);if(s<0)return{line:n,highlighted:!1};let r=x(i.slice(0,s)),o=x(t),a=x(n),u=Se(n,0,r,!0),l=Se(n,r,o,!0),c=Se(n,r+o,Math.max(0,a-r-o),!0);return{line:`${u}${h.bold.hex(td(e))(l)}${c}`,highlighted:!0}}var O3=4,nd=class{constructor(e={}){this.options=e}items=[];summary={paused:!1,pendingCount:0};setItems(e){this.items=e}setQueueSummary(e){this.summary=e}invalidate(){}render(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;if(t<4)return[];let i=this.items.find(r=>r.status==="failed"),s=this.items.filter(r=>r.status==="queued"||r.status==="paused");return!i&&s.length===0&&!this.summary.paused?[]:[...i?N3(i,t):[],...this.summary.paused?[E(h.hex(d.warning)(`Queue paused \xB7 ${this.summary.pendingCount} pending \xB7 /queue to continue`),t)]:[],...D3(s,t,this.options.keybindings,this.summary.paused)]}};function N3(n,e){let t=C(n.failedReason??"").trim(),i=`Couldn't send${t?` \xB7 ${t}`:""}`;return[E(`${h.bold.hex(d.error)("\xD7")} ${h.bold.hex(d.error)(i)}`,e,h.hex(d.muted)("\u2026")),t1(n,h.hex(d.line)("\u2514"),"",e)]}function D3(n,e,t,i=!1){if(n.length===0)return[];let s="/queue manage",r=i?"paused":"after current response",o=`${ye("run.restore-waiting-option",t)} restore latest`;if(n.length===1&&n[0])return[...yw("Next",r,o,s,e),t1(n[0],h.hex(d.line)("\u2514"),"",e)];let a=n.slice(0,O3),u=n.length-a.length,l=yw(`Queue \xB7 ${n.length} next`,r,o,s,e),c=a.map((p,m)=>t1(p,h.hex(d.line)(m===a.length-1&&u===0?"\u2514":"\u2502"),`${m+1}. `,e));return u>0&&c.push(E(`${h.hex(d.line)("\u2514")} ${h.hex(d.muted)(`+${u} more`)}`,e,h.hex(d.muted)("\u2026"))),[...l,...c]}function yw(n,e,t,i,s){let r=`${h.bold.hex(d.signal)("\u25CB")} ${h.bold.hex(d.signal)(n)}${h.hex(d.dim)(" \xB7 ")}${h.hex(d.muted)(e)}`,o=[t,i].join(" \xB7 "),a=`${h.hex(d.dim)(" \xB7 ")}${G(o)}`;return x(r)+x(a)<=s?[`${r}${a}`]:x(o)+2<=s?[E(r,s,h.hex(d.muted)("\u2026")),` ${G(o)}`]:[E(r,s,h.hex(d.muted)("\u2026")),E(` ${G(t)}`,s,h.hex(d.muted)("\u2026")),E(` ${G(i)}`,s,h.hex(d.muted)("\u2026"))]}function F3(n){let e=C(n.content).replace(/\s+/gu," ").trim(),t=n.attachmentNames.map(s=>C(s).replace(/\s+/gu," ").trim()).filter(Boolean),i=t.length>0?` \xB7 ${t.join(", ")}`:"";return`${e||"(attachment-only message)"}${i}`}function t1(n,e,t,i){return E(`${e} ${h.hex(d.text)(`${t}${F3(n)}`)}`,i,h.hex(d.muted)("\u2026"))}var id=class{activeComponent;show(e){this.activeComponent!==e&&(Tt(this.activeComponent),this.activeComponent=e)}close(e){if(!this.activeComponent||e&&e!==this.activeComponent)return!1;let t=this.activeComponent;return this.activeComponent=void 0,Tt(t),!0}dispose(){this.close()}isActive(e){return e?this.activeComponent===e:this.activeComponent!==void 0}current(){return this.activeComponent}get fullscreenViewport(){return!!(this.activeComponent&&"fullscreenViewport"in this.activeComponent&&this.activeComponent.fullscreenViewport===!0)}invalidate(){this.activeComponent?.invalidate()}render(e){return this.activeComponent?[...this.activeComponent.render(e)]:[]}renderViewport(e,t){return this.activeComponent?$3(this.activeComponent)?[...this.activeComponent.renderViewport(e,t)]:B3(this.activeComponent.render(e),t):[]}scrollByRows(e){return Tw(this.activeComponent)?this.activeComponent.scrollByRows(e):void 0}scrollByPage(e){return Tw(this.activeComponent)?this.activeComponent.scrollByPage(e):void 0}handleMouse(e){return q3(this.activeComponent)?this.activeComponent.handleMouse(e):!1}};function $3(n){return"renderViewport"in n&&typeof n.renderViewport=="function"}function B3(n,e){let t=Math.max(1,Math.floor(e));if(n.length<=t)return[...n];let i=new Set,s=Math.min(5,Math.max(1,t-3)),r=Math.min(2,Math.max(0,t-s));for(let a=0;a<s;a+=1)i.add(a);for(let a=Math.max(s,n.length-r);a<n.length;a+=1)i.add(a);let o=n.findIndex(a=>/[›→]/u.test(ge(a)));if(o>=0)for(let a=0;i.size<t;a+=1){let u=o-a,l=o+a;if(u>=s&&u<n.length-r&&i.add(u),l>=s&&l<n.length-r&&i.add(l),u<s&&l>=n.length-r)break}for(let a=s;i.size<t&&a<n.length-r;a+=1)i.add(a);return[...i].sort((a,u)=>a-u).slice(0,t).map(a=>n[a]??"")}function Tw(n){return!!(n&&"scrollByRows"in n&&typeof n.scrollByRows=="function"&&"scrollByPage"in n&&typeof n.scrollByPage=="function")}function q3(n){return!!(n&&"handleMouse"in n&&typeof n.handleMouse=="function")}var sd=class{constructor(e,t,i,s,r){this.host=e;this.surfaces=t;this.requestRender=i;this.onActiveChanged=s;this.followFullscreenBottom=r}layer;show(e){if(this.layer)this.host.show(e),this.layer.setFocus(e);else{this.host.show(e);try{this.layer=this.surfaces.pushChatLayer({id:"interaction",focus:e,priority:100,preemptsFeatures:!0})}catch(t){throw this.host.close(e),t}}this.onActiveChanged?.(!0),this.surfaces.getChatMode()==="fullscreen"&&this.followFullscreenBottom?.(),this.requestRender()}close(e){return!this.host.isActive(e)||this.layer&&!this.layer.close()||(this.layer=void 0,!this.host.close(e))?!1:(this.onActiveChanged?.(!1),this.requestRender(),!0)}closeCurrent(){return this.close(this.host.current())}isActive(e){return this.host.isActive(e)}current(){return this.host.current()}request(){this.requestRender()}};var rd=class{chatComponent;chatLayoutRoot;chatFocus;setFocus;requestRender;switchMode;mode;viewportRows;regularFeaturePresenter;featureStack=[];chatLayers=[];chatMode;chatLayerSequence=0;constructor(e){this.chatComponent=e.chat.component,this.chatLayoutRoot=e.chat.layoutRoot??e.chat.component,this.chatFocus=e.chat.focus,this.setFocus=e.setFocus,this.requestRender=e.requestRender,this.switchMode=e.switchMode,this.mode=e.mode,this.viewportRows=e.viewportRows,this.regularFeaturePresenter=e.regularFeaturePresenter,this.chatMode=e.chatMode??"regular"}getChatMode(){return this.chatMode}setChatMode(e){if(e===this.chatMode)return!0;let t=this.chatMode,i=this.currentMode();this.closeRegularFeaturePresentations(),this.chatMode=e;try{if(!this.reconcileMode())return this.chatMode=t,this.syncRegularFeaturePresentation(),!1;if(this.currentMode()!==e)return this.chatMode=t,this.restoreRendererMode(i),this.syncRegularFeaturePresentation(),!1;this.syncRegularFeaturePresentation()}catch(s){this.chatMode=t;let r=[];try{this.restoreRendererMode(i)}catch(o){r.push(o)}try{this.syncRegularFeaturePresentation()}catch(o){r.push(o)}throw r.length>0?new AggregateError([s,...r],"TUI mode change failed and could not fully restore the feature presentation."):s}return this.activate(this.activeFocus()),!0}getActiveSurface(){let e=this.activeFeature();return e?{kind:"feature",id:e.screen.id}:{kind:"chat",id:"chat"}}pushFeature(e){if(this.featureStack.some(i=>i.screen.id===e.screen.id))throw new Error(`Feature screen "${e.screen.id}" is already mounted.`);let t={screen:e.screen,focus:e.focus??e.screen};this.featureStack.push(t);try{this.syncRegularFeaturePresentation()}catch(i){throw this.featureStack.pop(),this.syncRegularFeaturePresentation(),i}return this.activate(this.activeFocus()),{id:t.screen.id,close:()=>this.closeEntry(t),isActive:()=>this.activeFeature()===t}}pushChatLayer(e){if(this.chatLayers.some(i=>i.id===e.id))throw new Error(`Chat layer "${e.id}" is already mounted.`);let t={...e,sequence:this.chatLayerSequence++,preemptsFeatures:e.preemptsFeatures??!1};this.chatLayers.push(t);try{this.syncRegularFeaturePresentation()}catch(i){throw this.chatLayers.pop(),this.syncRegularFeaturePresentation(),i}return(this.featureStack.length===0||t.preemptsFeatures)&&this.activate(this.activeFocus()),{id:t.id,close:()=>this.closeChatLayer(t),isActive:()=>this.activeFeature()===void 0&&this.activeChatLayer()===t,setFocus:i=>this.setChatLayerFocus(t,i)}}popFeature(){let e=this.featureStack.at(-1);return e?this.closeEntry(e):!1}clearFeatures(){if(this.featureStack.length===0)return!0;let e=this.featureStack.splice(0);this.closeRegularFeaturePresentations(e);for(let t of e)Tt(t.screen,t.focus);return this.activate(this.activeChatFocus()),!0}setChatFocus(e){this.chatFocus=e,this.featureStack.length===0&&this.chatLayers.length===0&&this.setFocus(e)}invalidate(){let e=this.activeFeature();e&&this.currentMode()==="fullscreen"?e.screen.invalidate():this.chatComponent.invalidate()}render(e){let t=this.activeFeature();return!t||this.currentMode()==="regular"?this.chatComponent.render(e):t.screen.renderViewport&&this.viewportRows&&!Ri(t.screen.layoutRoot)?[...t.screen.renderViewport(e,Math.max(1,this.viewportRows()))]:t.screen.render(e)}[Vt](){let e=this.activeFeature();return Ri(e&&this.currentMode()==="fullscreen"?e.screen.layoutRoot:this.chatLayoutRoot)}dispose(){this.closeRegularFeaturePresentations();for(let e of this.featureStack)Tt(e.screen,e.focus);for(let e of this.chatLayers)Tt(e.focus);this.featureStack.length=0,this.chatLayers.length=0}closeEntry(e){if(this.featureStack.at(-1)!==e)return!1;this.featureStack.pop(),this.closeRegularFeaturePresentations([e]);try{this.syncRegularFeaturePresentation()}catch(t){throw this.featureStack.push(e),this.syncRegularFeaturePresentation(),t}return Tt(e.screen,e.focus),this.activate(this.activeFocus()),!0}closeChatLayer(e){let t=this.chatLayers.indexOf(e);if(t<0)return!1;this.chatLayers.splice(t,1);try{this.syncRegularFeaturePresentation()}catch(i){throw this.chatLayers.splice(t,0,e),this.syncRegularFeaturePresentation(),i}return Tt(e.focus),this.activate(this.activeFocus()),!0}setChatLayerFocus(e,t){if(!this.chatLayers.includes(e))throw new Error(`Chat layer "${e.id}" is no longer mounted.`);e.focus=t,this.activeFeature()===void 0&&this.activeChatLayer()===e&&this.activate(t)}activeChatFocus(){return this.activeChatLayer()?.focus??this.chatFocus}activeChatLayer(){return[...this.chatLayers].sort((e,t)=>t.priority-e.priority||t.sequence-e.sequence)[0]}activeFeature(){return this.activePreemptiveChatLayer()?void 0:this.featureStack.at(-1)}activePreemptiveChatLayer(){return[...this.chatLayers].filter(e=>e.preemptsFeatures).sort((e,t)=>t.priority-e.priority||t.sequence-e.sequence)[0]}activeFocus(){let e=this.activeFeature();return e?.regularPresentation?.focus??e?.focus??this.activeChatFocus()}currentMode(){return this.mode?.()??this.chatMode}reconcileMode(){let e=this.chatMode;return e===this.mode?.()?!0:this.switchMode?.(e)!==!1}restoreRendererMode(e){if(this.currentMode()!==e&&(this.switchMode?.(e)===!1||this.currentMode()!==e))throw new Error(`Cannot restore TUI renderer mode to "${e}".`)}syncRegularFeaturePresentation(){let e=this.currentMode()==="regular"?this.activeFeature():void 0;for(let t of this.featureStack)t!==e&&(t.regularPresentation?.close(),t.regularPresentation=void 0);!e||e.regularPresentation||(e.regularPresentation=this.regularFeaturePresenter.show(e.screen,e.focus))}closeRegularFeaturePresentations(e=this.featureStack){for(let t of e)t.regularPresentation?.close(),t.regularPresentation=void 0}activate(e){this.invalidateActiveSurface(),this.setFocus(e),this.requestRender()}invalidateActiveSurface(){let e=this.activeFeature();e?e.screen.invalidate():this.currentMode()==="fullscreen"&&this.chatComponent.invalidate()}};var bw=4,od=class{constructor(e,t,i){this.terminal=e;this.tui=t;this.requestRender=i}show(e,t){let i=new n1(e,t,this.terminal,this.requestRender),s=this.tui.showOverlay(i,{width:"100%",maxHeight:"100%",row:0,col:0});return{focus:i,close:()=>s.hide()}}},n1=class{constructor(e,t,i,s){this.screen=e;this.focusTarget=t;this.terminal=i;this.requestRender=s}layout;focusedValue=!1;get focused(){return this.focusedValue}set focused(e){this.focusedValue=e,wo(this.focusTarget)&&(this.focusTarget.focused=e)}get wantsKeyRelease(){return this.focusTarget.wantsKeyRelease??!1}handleInput(e){this.handleViewportInput(e)||this.focusTarget.handleInput?.(e)}render(e){return this.screen.renderViewport&&!Ri(this.screen.layoutRoot)?(this.layout=void 0,[...this.screen.renderViewport(e,Math.max(1,this.terminal.rows))]):(this.layout=or(this.screen.layoutRoot,e,Math.max(1,this.terminal.rows),this.requestRender),this.layout.lines)}invalidate(){this.screen.invalidate()}handleViewportInput(e){let t=this.layout?.primaryScrollView;if(!t)return!1;let i=ie(),s=ln(e);return i.matches(e,"tui.altScreen.pageUp")?(s||t.scrollBy(-Math.max(1,t.viewportHeight-bw)),!0):i.matches(e,"tui.altScreen.pageDown")?(s||t.scrollBy(Math.max(1,t.viewportHeight-bw)),!0):i.matches(e,"tui.altScreen.halfPageUp")?(s||t.scrollBy(-Math.max(1,Math.floor(t.viewportHeight/2))),!0):i.matches(e,"tui.altScreen.halfPageDown")?(s||t.scrollBy(Math.max(1,Math.floor(t.viewportHeight/2))),!0):i.matches(e,"tui.altScreen.lineUp")?(s||t.scrollBy(-1),!0):i.matches(e,"tui.altScreen.lineDown")?(s||t.scrollBy(1),!0):i.matches(e,"tui.altScreen.top")?(s||t.scrollToStart(),!0):i.matches(e,"tui.altScreen.bottom")?(s||t.scrollToEnd(),!0):!1}};var vw=3,Cw=32,H3=30,xw=52,ad=class{constructor(e){this.keybindings=e}items=[];expanded=!1;setItems(e){let t=e.map(i=>({...i}));(t.length===0||t.every(i=>i.status==="completed")||!V3(this.items,t))&&(this.expanded=!1),this.items=t}toggleExpanded(){return this.items.length===0||this.items.every(e=>e.status==="completed")||!this.expanded&&this.items.length<=vw?"compact":(this.expanded=!this.expanded,this.expanded?"expanded":"compact")}isExpanded(){return this.expanded}invalidate(){}render(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;if(t<4||this.items.length===0)return[];let i=this.items.filter(p=>!Q3(p.status)),s=this.items.filter(p=>p.status==="completed").length,r=this.items.filter(p=>p.status==="cancelled").length;if(s===this.items.length)return[E(` ${h.hex(d.success)(`\u2713 Todo list ${s}/${this.items.length} completed`)}`,t,h.hex(d.muted)("\u2026"))];let o=ye("composer.toggle-tasks",this.keybindings);if(this.expanded)return[U3({completed:s,total:this.items.length,remaining:i.length,cancelled:r,shortcut:o,width:t}),...this.items.map(Sw)].map(m=>j3(m,t));let{rows:a,hidden:u}=W3(this.items,vw),l=this.items.filter(p=>p.status==="pending").length;return[...a.map(Sw),K3({completed:s,total:this.items.length,pending:l,cancelled:r,hidden:u,shortcut:o,width:t})].map(p=>E(p,t,h.hex(d.muted)("\u2026")))}};function U3(n){let e=h.bold.hex(d.text)(`Todo list ${n.completed}/${n.total}`),t=n.width<H3?n.shortcut:`${n.shortcut} ${n.width<Cw?"close":"compact"}`;if(n.width<xw)return` ${e}${G(` \xB7 ${t}`)}`;let i=n.cancelled>0?` \xB7 ${n.cancelled} skipped`:"";return` ${e}${G(` \xB7 ${n.remaining} remaining${i} \xB7 ${t}`)}`}function K3(n){if(n.width<Cw&&n.hidden>0)return` ${G(`\u2026 +${n.hidden} \xB7 ${n.shortcut} expand`)}`;if(n.width<xw&&n.hidden>0)return` ${G(`\u2026 +${n.hidden} \xB7 ${n.completed}/${n.total} \xB7 ${n.shortcut} expand`)}`;let e=n.hidden>0?`\u2026 +${n.hidden} more \xB7 `:"",t=n.cancelled>0?` \xB7 ${n.cancelled} skipped`:"",i=n.hidden>0?` \xB7 ${n.shortcut} expand`:"";return` ${G(`${e}${n.completed}/${n.total} done${t} \xB7 ${n.pending} pending${i}`)}`}function W3(n,e){if(n.length<=e)return{rows:n,hidden:0};let t=[],i=[],s=[];for(let[l,c]of n.entries())c.status==="in_progress"?t.push(l):c.status==="pending"?i.push(l):s.push(l);let r=new Set,o=t[0]??i[0]??n.length-1,a=s.filter(l=>l<o).at(-1)??s.at(-1);a!==void 0&&e>1&&r.add(a);for(let l of t){if(r.size>=e)break;r.add(l)}for(let l of i.filter(c=>c>=o)){if(r.size>=e)break;r.add(l)}for(let l of i){if(r.size>=e)break;r.add(l)}for(let l of[...s].reverse()){if(r.size>=e)break;r.add(l)}let u=[...r].sort((l,c)=>l-c);return{rows:u.map(l=>n[l]),hidden:n.length-u.length}}function j3(n,e){return E(n,e,h.hex(d.muted)("\u2026"))}function V3(n,e){if(n.length===0)return!1;let t=new Set(n.map(i=>i.content));return e.some(i=>t.has(i.content))}function Sw(n){let e=C(n.content).replace(/\s+/gu," ").trim();return` ${G3(n.status)} ${z3(e,n.status)}`}function G3(n){switch(n){case"completed":return h.hex(d.success)("\u2713");case"in_progress":return h.bold.hex(d.signal)("\u25CF");case"cancelled":return h.hex(d.muted)("\u2013");case"pending":return h.hex(d.dim)("\u25CB")}}function z3(n,e){switch(e){case"completed":return h.hex(d.muted).strikethrough(n);case"in_progress":return h.bold.hex(d.text)(n);case"cancelled":return h.hex(d.muted).strikethrough(n);case"pending":return h.hex(d.text)(n)}}function Q3(n){return n==="completed"||n==="cancelled"}var ud=class{todo;agentTeam;backgroundTasks=[];constructor(e){this.todo=new ad(e)}setItems(e){this.todo.setItems(e)}setAgentTeam(e){this.agentTeam=e}setBackgroundTasks(e){this.backgroundTasks=e.map(t=>({...t}))}toggleExpanded(){return this.todo.toggleExpanded()}invalidate(){this.todo.invalidate()}render(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;return t<4?[]:this.renderSections(t).flatMap(i=>i.lines)}renderViewport(e,t){let i=Number.isFinite(e)?Math.max(0,Math.floor(e)):0,s=Number.isFinite(t)?Math.max(0,Math.floor(t)):0;if(i<4||s===0)return[];let r=this.renderSections(i).filter(u=>u.lines.length>0);if(r.reduce((u,l)=>u+l.lines.length,0)<=s)return r.flatMap(u=>u.lines);let a=Y3(r.map(u=>u.lines.length),s);return r.flatMap((u,l)=>X3(u,a[l]??0,this.todo.isExpanded()))}renderSections(e){return[{kind:"todo",lines:this.todo.render(e)},{kind:"work",lines:this.renderWorkSummary(e)}]}renderWorkSummary(e){let t=this.agentTeam,i=t!==void 0&&J3(t)?t:void 0,s=this.backgroundTasks.filter(eN);return!i&&s.length===0?[]:[Z3(i,s,e)]}};function Y3(n,e){let t=n.map(()=>0),i=e;for(let[s,r]of n.entries()){if(i===0)break;r!==0&&(t[s]=1,i-=1)}for(;i>0;){let s=!1;for(let[r,o]of n.entries()){if(i===0)break;(t[r]??0)>=o||(t[r]=(t[r]??0)+1,i-=1,s=!0)}if(!s)break}return t}function X3(n,e,t){if(e<=0)return[];if(n.lines.length<=e)return n.lines;if(n.kind!=="todo"||t)return n.lines.slice(0,e);let i=n.lines.at(-1);return i?e===1?[i]:[...n.lines.slice(0,e-1),i]:[]}function J3(n){return n.members.some(e=>e.status==="queued"||e.status==="running"||e.status==="waiting")}function Z3(n,e,t){let i=(n?.summary.running??0)+(n?.summary.queued??0),s=n?.summary.waiting??0,r=e.filter(p=>ww(p.status)).length,o=(n?.summary.failed??0)+e.filter(p=>p.status==="failed"||p.status==="lost").length,a=e.filter(p=>p.status==="succeeded").length,u=(n?.summary.stopped??0)+e.filter(p=>p.status==="canceled").length,l=[o>0?`${String(o)} failed`:void 0,s>0?`${String(s)} agent${s===1?"":"s"} waiting`:void 0,i>0?`${String(i)} agent${i===1?"":"s"} active`:void 0,r>0?`${String(r)} background active`:void 0,a>0?`${String(a)} result${a===1?"":"s"} ready`:void 0,u>0?`${String(u)} cancelled`:void 0].filter(p=>!!p),c=o>0?h.hex(d.error)("\xD7"):s>0||e.some(p=>p.status==="stopping")?h.hex(d.warning)("\u25C9"):i>0||r>0?h.hex(d.accent)("\u25D0"):u>0&&a===0?h.hex(d.muted)("\u25A0"):h.hex(d.success)("\u2713");return E(`${c} ${h.bold.hex(d.text)("Tasks")}${h.hex(d.muted)(` \xB7 ${l.join(" \xB7 ")} \xB7 /tasks details`)}`,t,"")}function ww(n){return n==="queued"||n==="running"||n==="stopping"}function eN(n){return ww(n.status)||n.deliveredAtMs===void 0}import{spawn as Rw}from"node:child_process";import{win32 as lN}from"node:path";import{spawn as tN}from"node:child_process";import{mkdtemp as nN,readFile as iN,rm as sN,writeFile as rN}from"node:fs/promises";import{tmpdir as oN}from"node:os";import{join as Iw}from"node:path";function Ew(n={}){let e=n.env??process.env,t=[n.configuredCommand,e.MCODE_EDITOR,e.VISUAL,e.EDITOR].find(i=>i?.trim());return t?t.trim():(n.platform??process.platform)==="win32"?"notepad":void 0}function i1(n){let e=[],t="",i,s=!1;for(let a=0;a<n.length;a+=1){let u=n[a]??"";if(i){if(u===i){i=void 0,s=!0;continue}if(u==="\\"&&i==='"'){let l=n[a+1];if(l==='"'||l==="\\"){t+=l,a+=1,s=!0;continue}}t+=u,s=!0;continue}if(u==="'"||u==='"'){i=u,s=!0;continue}if(/\s/u.test(u)){s&&(e.push(t),t="",s=!1);continue}if(u==="\\"){let l=n[a+1];if(l&&(/\s/u.test(l)||l==="'"||l==='"'||l==="\\")){t+=l,a+=1,s=!0;continue}}t+=u,s=!0}if(i)throw new Error("External editor command has an unmatched quote.");s&&e.push(t);let[r,...o]=e;if(!r)throw new Error("External editor command is empty.");return{executable:r,args:o}}async function Aw(n){let e=i1(n.command),t=await nN(Iw(oN(),"mcode-editor-")),i=Iw(t,"prompt.md");try{await rN(i,Mw(n.draft),{encoding:"utf8",mode:384});let s=await(n.runProcess??aN)({executable:e.executable,args:[...e.args,i],cwd:n.cwd,shell:(n.platform??process.platform)==="win32"});return uN(s),Mw(await iN(i,"utf8"))}finally{await sN(t,{recursive:!0,force:!0})}}function aN(n){return new Promise((e,t)=>{let i=tN(n.executable,n.args,{cwd:n.cwd,stdio:"inherit",shell:n.shell});i.once("error",t),i.once("close",(s,r)=>e({exitCode:s,signal:r}))})}function uN(n){if(n.exitCode!==0)throw n.signal?new Error(`External editor exited after signal ${n.signal}`):new Error(`External editor exited with code ${String(n.exitCode)}`)}function Mw(n){return n.replace(/^\uFEFF/u,"").replace(/\r\n?/gu,`
|
|
205
205
|
`)}var cN=1,dN=5e3,hN=500,pN=3e4,mN=10,s1=8*1024,r1=class{constructor(e){this.options=e;this.parsed=fN(e.config.command),this.timeoutMs=TN(e.config.timeoutMs),this.intervalMs=bN(e.config.intervalSeconds),this.shell=(e.platform??process.platform)==="win32",this.runProcess=e.runProcess??vN}parsed;timeoutMs;intervalMs;shell;runProcess;intervalTimer;running=!1;trailing;disposed=!1;paused=!1;contextGeneration=0;start(){this.disposed||this.paused||!this.parsed||(this.trigger("startup"),this.intervalMs>0&&(this.intervalTimer=setInterval(()=>this.trigger("interval"),this.intervalMs),this.intervalTimer.unref?.()))}trigger(e){if(!(this.disposed||this.paused||!this.parsed)){if((e==="session-change"||e==="workspace-change")&&(this.contextGeneration+=1),this.running){this.trailing=e;return}this.run(e)}}dispose(){this.disposed=!0,this.pause()}pause(){this.paused||(this.paused=!0,this.contextGeneration+=1,this.trailing=void 0,this.intervalTimer&&clearInterval(this.intervalTimer),this.intervalTimer=void 0)}resume(){!this.paused||this.disposed||(this.paused=!1,this.start())}async run(e){if(!this.parsed)return;this.running=!0;let t=this.contextGeneration;try{let i=this.options.getContext(),s=await this.runProcess({executable:this.parsed.executable,args:this.parsed.args,cwd:i.workspaceDir,shell:this.shell,stdin:gN(e,i,this.options.version),timeoutMs:this.timeoutMs});if(this.disposed||t!==this.contextGeneration)return;!s.timedOut&&s.exitCode===0&&this.options.onText(yN(s.stdout,this.options.config.display==="block"))}catch{}finally{this.running=!1;let i=this.trailing;this.trailing=void 0,i!==void 0&&!this.disposed&&!this.paused&&this.run(i)}}};function kw(n,e){if(n?.includes("custom-command")&&!n.includes("build-mode")&&e.config.command?.trim())return new r1(e)}function fN(n){if(n?.trim())try{return i1(n)}catch{return}}function gN(n,e,t){return`${JSON.stringify({protocol:cN,event:n,...e.sessionId?{session_id:e.sessionId}:{},workspace_dir:e.workspaceDir,...e.model?{model:e.model}:{},...e.sessionTitle?{session_title:e.sessionTitle}:{},tui_version:t})}
|
|
206
206
|
`}function yN(n,e){let t=n.slice(0,s1);return e?t:(t.split(/\r?\n/u,1)[0]??"").trim()}function TN(n){return typeof n!="number"||!Number.isFinite(n)?dN:Math.min(pN,Math.max(hN,Math.floor(n)))}function bN(n){return typeof n!="number"||!Number.isFinite(n)||n<=0?0:Math.max(mN,Math.floor(n))*1e3}function vN(n){return new Promise(e=>{let t="",i=!1,s=!1,r,o,a=u=>{s||(s=!0,r&&clearTimeout(r),o?.stdin?.destroy(),o?.stdout?.destroy(),e(u))};try{o=Rw(n.executable,[...n.args],{cwd:n.cwd,shell:n.shell,stdio:["pipe","pipe","ignore"],windowsHide:!0,detached:process.platform!=="win32"})}catch{a({exitCode:null,stdout:"",timedOut:!1});return}r=setTimeout(()=>{i=!0,o&&SN(o),a({exitCode:null,stdout:t,timedOut:!0})},n.timeoutMs),r.unref?.(),o.once("error",()=>a({exitCode:null,stdout:"",timedOut:i})),o.stdout?.setEncoding("utf8"),o.stdout?.on("data",u=>{t.length>=s1||(t+=u.slice(0,s1-t.length))}),o.stdin?.on("error",()=>{}),o.stdin?.end(n.stdin),o.once("close",u=>a({exitCode:u,stdout:t,timedOut:i}))})}function SN(n){let e=()=>{try{n.kill("SIGKILL")}catch{}};if(!n.pid)return e();try{if(process.platform!=="win32"){process.kill(-n.pid,"SIGKILL");return}let t=process.env.SystemRoot??process.env.WINDIR,i=t?lN.join(t,"System32","taskkill.exe"):"taskkill.exe",s=Rw(i,["/PID",String(n.pid),"/T","/F"],{windowsHide:!0,stdio:"ignore"});s.once("error",e),s.once("close",r=>{r!==0&&e()}),s.unref()}catch{e()}}function pi(n){return n>=1e6&&n%1e6===0?`${n/1e6}M`:n>=1e3&&n%1e3===0?`${n/1e3}K`:String(n)}function Pw(n,e){let t=Math.max(0,e-x(n)),i=Math.floor(t/2);return`${" ".repeat(i)}${n}${" ".repeat(t-i)}`}function o1(n,e,t){let i=l=>h.hex(d.line)(l),s=`${i("\u256D\u2500")} ${n} `,r=` ${e} ${i("\u2500\u256E")}`;if(x(s)+x(r)<=t)return`${s}${i("\u2500".repeat(Math.max(0,t-x(s)-x(r))))}${r}`;let o=Math.max(1,t-5),a=E(n,o,h.hex(d.muted)("\u2026")),u=`${i("\u256D\u2500")} ${a} `;return`${u}${i("\u2500".repeat(Math.max(0,t-x(u)-1)))}${i("\u256E")}`}function dt(n,e){let t=h.hex(d.line),i=Math.max(0,e-4),s=E(n,i,h.hex(d.muted)("\u2026"));return`${t("\u2502")} ${s}${" ".repeat(Math.max(0,i-x(s)))} ${t("\u2502")}`}function a1(n){let e=h.hex(d.line);return`${e("\u251C")}${e("\u2500".repeat(Math.max(0,n-2)))}${e("\u2524")}`}function ld(n){let e=h.hex(d.line);return`${e("\u2570")}${e("\u2500".repeat(Math.max(0,n-2)))}${e("\u256F")}`}function Ls(n,e){return E(n,e,h.hex(d.muted)("\u2026"))}function u1(n,e){return n.find(t=>x(t)<=e)??Ls(n.at(-1)??"",e)}function Ma(n){return Number.isFinite(n)?Math.max(0,Math.floor(n)):0}function l1(n){let e=n?.trim();if(!e)return"none";let t=2166136261;for(let i=0;i<e.length;i+=1)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return((t>>>0)%2176782336).toString(36).padStart(6,"0")}function Lw(n){let e=_w(n.totalAgents),t=Math.min(_w(n.activeAgents),e);return`[V] seq=${n.seq} state=${n.status} session=${l1(n.sessionId)} turn=${l1(n.turnId)} request=${l1(n.requestId)} agents=${t}/${e}`}function _w(n){return n===void 0||!Number.isFinite(n)?0:Math.min(9999,Math.max(0,Math.trunc(n)))}var c1=["build-mode","current-dir","session-title","git-branch","review-link","plan-mode","approval-mode","model-with-reasoning","model","context-window","subagent","token-quota","cache-read-ratio","context-remaining","custom-command"],CN={"status-protocol":"build-mode",vela:"build-mode",workspace:"current-dir",cwd:"current-dir","project-dir":"current-dir",git:"git-branch",branch:"git-branch",pr:"review-link",mr:"review-link","pull-request":"review-link","merge-request":"review-link",review:"review-link",permissions:"approval-mode","permission-mode":"approval-mode","model-with-thinking":"model-with-reasoning",identity:"model-with-reasoning","sub-agent":"subagent",quota:"token-quota","token-plan":"token-quota","cache-read":"cache-read-ratio",context:"context-remaining","context-left":"context-remaining",custom:"custom-command"},xN=new Set(c1);function wN(n){let e=n.trim().toLowerCase();if(e)return xN.has(e)?e:CN[e]}function Wi(n){let e=new Set,t=[];for(let i of n){let s=wN(i);!s||e.has(s)||(e.add(s),t.push(s))}return t}var ji=["current-dir","session-title","git-branch","review-link","plan-mode","approval-mode","model-with-reasoning","context-window","subagent","token-quota","context-remaining"];var IN=new RegExp([String.raw`(?:\u001b[\]PX^_]|[\u0090\u0098\u009d-\u009f])[\s\S]*?(?:\u0007|\u001b\\|\u009c|$)`,String.raw`(?:\u001b\[|\u009b)[0-?]*[ -/]*(?:[@-~]|$)`,String.raw`\u001b[ -/]*[0-~]`,String.raw`[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]`].join("|"),"gu"),Ow="\x1B[0m";function MN(n){let e=/^(?:\u001b\[|\u009b)([0-9;]*)m$/u.exec(n);if(!e)return"";let t=(e[1]??"").split(";").map(Number);for(let i=0;i<t.length;i+=1){let s=t[i];if(s===void 0)return"";if(s===38||s===48){let r=t[i+1],o=r===5?1:r===2?3:0,a=t.slice(i+2,i+2+o);if(o===0||a.length!==o||a.some(u=>u<0||u>255))return"";i+=o+1}else if(s!==0&&s!==39&&s!==49&&!(s>=30&&s<=37)&&!(s>=40&&s<=47)&&!(s>=90&&s<=97)&&!(s>=100&&s<=107))return""}return`\x1B[${t.join(";")}m`}function d1(n,e,t){let i=t==="ansi"&&h.level>0,r=(t==="ansi"?n.replace(IN,o=>i?MN(o):""):C(n)).replace(/\r\n/gu,`
|
|
207
|
-
`).replace(/[\r\t]/gu," ");return Y(r,Number.POSITIVE_INFINITY).flatMap(o=>{let a=ge(o),u=a.trim();if(!u)return[];let l=x(a)-x(a.trimStart()),c=Se(o,l,x(u)),p=E(c,e,"\u2026");return p?[i?Ow+p+Ow:h.hex(d.muted)(p)]:[]})}var jr="{paste-image-shortcut}",Nw="/checkin claims the daily reward.",ht={sectionTitles:{tips:"Tips for getting started",news:"What's new \xB7 /changelog for history"},tipPool:["Say what you want and how to verify it.",`Use @ for files; ${jr} for images.`,"Run /init to teach MCode this repo.","Use /plan before a change that needs design or investigation.","Use /context to check the current Session context budget.","Use /sessions to resume earlier work.","Use /history to review and branch from earlier prompts.","Use /goal to keep long-running work focused on a finish line.","Use /permission to choose how MCode handles tool approvals.","Use /feedback to preview a redacted report before upload.",Nw],wide:{tips:["Say what you want and how to verify it.",`Use @ for files; ${jr} for images.`,"Run /init to teach MCode this repo.",Nw],news:["Send follow-ups while MCode works.","/context shows read-only session context.","/feedback previews before upload."]},stacked:{tips:["Say what you want and how to verify it.",`@ files \xB7 ${jr} images \xB7 /init guidance`,"/checkin daily reward"],news:["Follow-ups wait while MCode works.","/context budget \xB7 /feedback preview"]},compact:{tips:[`@ files \xB7 ${jr} images`,"/init repo guidance","/checkin reward"],news:["Follow-ups wait","/context \xB7 /feedback"]},hero:{fullMinWidth:91,mediumMinWidth:44,microMinWidth:11,fallbackTitle:"M"}},Dw=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D","\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],Fw=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D","\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],$w=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551","\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551","\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551","\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D"];function cd(n){let{fullMinWidth:e,mediumMinWidth:t,microMinWidth:i,fallbackTitle:s}=ht.hero,r=n>=e?Dw:n>=t?Fw:n>=i?$w:[s],o=r.length>1,a=Math.max(...r.map(l=>x(l))),u=[d.wordmarkHighlight,d.wordmarkHighlight,d.brand,d.brand,d.wordmarkShadow,d.wordmarkShadow];return r.map((l,c)=>{let p=l+" ".repeat(Math.max(0,a-x(l))),m=c%7,f=o?u[m]??d.brand:d.brand;return Pw(h.bold.hex(f)(p),n)})}var Ea=class{constructor(e,t,i={}){this.state=e;this.keybindings=t;this.content=i}setState(e){this.state=e}invalidate(){}render(e){return this.renderViewport(e,Number.POSITIVE_INFINITY)}renderViewport(e,t){let i=Ma(e);if(i===0)return[];if(i<4)return[Ls("M",i)];let s=Xc(i),r=s.welcome==="compact"?Bw(this.state,i,this.keybindings,this.content):s.welcome==="stacked"?RN(this.state,i,this.keybindings,this.content):AN(this.state,i,this.keybindings,this.content);return r.length+2>t&&s.welcome!=="compact"&&(r=Bw(this.state,i,this.keybindings,this.content)),EN(["",...r,""],t)}};function EN(n,e){if(!Number.isFinite(e))return n;let t=Math.max(1,Math.floor(e)),i=[...n];for(;i.length>t;){let s=i.findIndex(r=>r.length===0);if(s<0)break;i.splice(s,1)}return i.slice(0,t)}function AN(n,e,t,i){let s=Vr(i?.tips,ht.wide.tips,3),r=Vr(i?.changelogEntries,ht.wide.news,3);return[...cd(e),"",qw(n,e),...h1(n,e),dt(Gr(ht.sectionTitles.tips),e),...s.map(o=>dt(dd(Aa(o,t)),e)),a1(e),dt(Gr(ht.sectionTitles.news),e),...r.map(o=>dt(dd(Aa(o,t)),e)),ld(e)]}function RN(n,e,t,i){let s=Vr(i?.tips,ht.stacked.tips,2),r=Vr(i?.changelogEntries,ht.stacked.news,3);return[...cd(e),"",qw(n,e),...h1(n,e),a1(e),dt(Gr(ht.sectionTitles.tips),e),...s.map(o=>dt(dd(Aa(o,t)),e)),dt("",e),dt(Gr(ht.sectionTitles.news),e),...r.map(o=>dt(dd(Aa(o,t)),e)),dt("",e),ld(e)]}function Bw(n,e,t,i){let s=Vr(i?.tips,ht.compact.tips,2),r=Vr(i?.changelogEntries,ht.compact.news,3);return[...cd(e),"",o1(`${h.bold.hex(d.brand)("MCode")} ${h.hex(d.muted)(`v${n.version}`)}`,Hw(n),e),...h1(n,e),dt(Gr("Tips"),e),...s.map(o=>dt(h.hex(d.muted)(Aa(o,t)),e)),dt(Gr(ht.sectionTitles.news),e),...r.map(o=>dt(h.hex(d.muted)(o),e)),ld(e)]}function qw(n,e){return o1(h.hex(d.muted)(`v${n.version}`),Hw(n),e)}function Vr(n,e,t){return n?.length?n.slice(0,t):e}function Gr(n){return h.bold.hex(d.brand)(n)}function dd(n){return`${h.bold.hex(d.orbit)("\u203A")} ${h.hex(d.text)(n)}`}function Aa(n,e){return n.replaceAll(jr,ye("composer.paste-image",e))}function h1(n,e){if(n.accountStatus!=="Sign in with /login")return[];let t=`${h.bold.hex(d.warning)("\u25CB")} ${h.bold.hex(d.warning)(n.accountStatus)}`;return[dt(t,e)]}function Hw(n){return n.accountStatus==="Sign in with /login"?h.bold.hex(d.warning)("\u25CB Login required"):n.runtimeStatus==="ready"?h.bold.hex(d.orbit)("\u25CF Ready"):n.runtimeStatus==="starting"?h.bold.hex(d.signal)("\u25CC Starting"):n.runtimeStatus==="offline"?h.bold.hex(d.warning)("\u25CB Login required"):h.bold.hex(d.error)("\xD7 Error")}var pd=class{availableVersion;setAvailableVersion(e){this.availableVersion=e?.trim()||void 0}invalidate(){}render(e){let t=Ma(e);if(!this.availableVersion||t===0)return[];let i=u1([` ${h.bold.hex(d.signal)("\u2726 A new version of MCode is available")} ${h.hex(d.text)("\u2014 update for the latest improvements")}`,` ${h.bold.hex(d.signal)(`\u2726 MCode ${this.availableVersion} is available`)}`,` ${h.bold.hex(d.signal)("\u2726 MCode update available")}`],t),s=u1([` ${h.hex(d.muted)("Run '")}${h.bold.hex(d.signal)("/update")}${h.hex(d.muted)(`' to install MCode ${this.availableVersion}`)}`,` ${h.hex(d.muted)("Run ")}${h.bold.hex(d.signal)("/update")}${h.hex(d.muted)(` to install ${this.availableVersion}`)}`,` ${h.bold.hex(d.signal)("/update")}${h.hex(d.muted)(" \xB7 review and install")}`,` ${h.bold.hex(d.signal)("/update")}${h.hex(d.muted)(" \xB7 install")}`],t);return[Ls(i,t),Ls(s,t)]}},Ra=class{constructor(e,t){this.state=e;this.customStatusConfig=t}setState(e){this.state=e}invalidate(){}render(e){return this.renderViewport(e,Number.POSITIVE_INFINITY)}renderViewport(e,t){let i=Ma(e);if(i===0)return[];let s=kN(this.state);if(s.length===0)return[];let r=this.customStatusConfig?.display==="block"&&s.includes("custom-command"),o=s.filter(c=>!r||c!=="custom-command").map(c=>PN(c,this.state,this.customStatusConfig)).filter(c=>c!==void 0),a=ON(o,i),u=ge(a).trim()?[a]:[],l=r?this.renderCustomBlock(i,t-u.length-1):[];return u.length===0&&l.length===0?[]:this.customStatusConfig?.position==="below"?["",...u,...l]:["",...l,...u]}renderCustomBlock(e,t){let i=this.customStatusConfig?.maxLines,s=typeof i=="number"&&Number.isFinite(i)?Math.min(5,Math.max(1,Math.floor(i))):3,r=Math.min(s,Math.max(0,Math.floor(t)||0));return r===0?[]:d1(this.state.customStatusText??"",e,this.customStatusConfig?.colorMode).slice(0,r)}};function kN(n){let e=n.statusLineItems??ji;if(!e.includes("build-mode")){if(n.statusLineItems!==void 0)return e;let t=Qw(n);return e.filter(i=>i!=="context-remaining"||t!==void 0&&t<=25)}return["build-mode"]}function PN(n,e,t){switch(n){case"build-mode":return vt([_N(e)],{shrinkPriority:70,preserveWhenNarrow:!0});case"current-dir":{let i=FN(e.workspace,e.homeDir),s=$N(i);return vt([s.full,s.medium,s.compact,s.base].map(r=>h.hex(d.muted)(r)),{shrinkPriority:10,dropPriority:30})}case"session-title":return vt([f1(e),f1(e,18),f1(e,10)],{shrinkPriority:15,dropPriority:60});case"git-branch":return vt([y1(e.workspaceGit),y1(e.workspaceGit,"compact"),y1(e.workspaceGit,"minimal")],{shrinkPriority:20,dropPriority:30});case"review-link":return vt([T1(e.workspaceGit),T1(e.workspaceGit,"compact"),T1(e.workspaceGit,"minimal")],{shrinkPriority:25,dropPriority:35});case"plan-mode":return vt([jw(e),jw(e,!0)],{shrinkPriority:55,dropPriority:55});case"approval-mode":return vt([Vw(e),Vw(e,!0)],{shrinkPriority:60});case"model-with-reasoning":return vt([hd(e,"full"),hd(e,"compact"),hd(e,"minimal")],{shrinkPriority:30,dropPriority:65});case"model":return vt([hd(e,"minimal")],{shrinkPriority:30,dropPriority:20});case"context-window":return vt([Uw(e),Uw(e,!0)],{shrinkPriority:35,dropPriority:64});case"subagent":return vt([Kw(e),Kw(e,!0)],{shrinkPriority:40,dropPriority:60});case"token-quota":return vt([b1(e.tokenPlanQuota,e.tokenPlanQuotaState),b1(e.tokenPlanQuota,e.tokenPlanQuotaState,"compact"),b1(e.tokenPlanQuota,e.tokenPlanQuotaState,"minimal")],{shrinkPriority:45,dropPriority:70});case"cache-read-ratio":return vt([m1(e,"full"),m1(e,"compact"),m1(e,"minimal")],{shrinkPriority:48,dropPriority:10});case"context-remaining":return vt([g1(e,"full"),g1(e,"compact"),g1(e,"minimal")],{shrinkPriority:50,dropPriority:80});case"custom-command":return vt([p1(e,60,t?.colorMode),p1(e,24,t?.colorMode),p1(e,12,t?.colorMode)],{shrinkPriority:35,dropPriority:50})}}function p1(n,e,t){let i=(n.customStatusText??"").split(/\r?\n/u,1)[0]??"";return d1(i,e,t)[0]??""}function m1(n,e="full"){let t=n.sessionCacheReadRatio;if(t===void 0||!Number.isFinite(t))return"";let i=Math.round(Math.min(1,Math.max(0,t))*100),s=e==="full"?`Cache ${i}%`:e==="compact"?`C ${i}%`:`${i}%`;return h.hex(d.muted)(s)}function _N(n){return Lw({seq:n.agentSeq??"0",status:LN(n),sessionId:n.agentSessionId,turnId:n.agentRunId,requestId:n.agentRequestId,activeAgents:n.agentActiveCount,totalAgents:n.agentTotalCount})}function LN(n){return n.agentStatus?n.agentStatus:n.runtimeStatus==="error"?"error":n.busy||n.runtimeStatus==="starting"?"run":"ready"}function vt(n,e){let t=n.filter(Boolean).filter((i,s,r)=>{let o=ge(i);return r.findIndex(a=>ge(a)===o)===s});if(t.length!==0)return{variants:t,...e}}function ON(n,e){let t=n.map(s=>({segment:s,variant:0})),i=()=>NN(t.map(({segment:s,variant:r})=>s.variants[r]??""));for(;x(i())>e;){let s=t.filter(({segment:a,variant:u})=>u+1<a.variants.length).sort((a,u)=>a.segment.shrinkPriority-u.segment.shrinkPriority)[0];if(s){s.variant+=1;continue}let r=t.filter(({segment:a})=>a.dropPriority!==void 0).sort((a,u)=>(a.segment.dropPriority??Number.POSITIVE_INFINITY)-(u.segment.dropPriority??Number.POSITIVE_INFINITY))[0];if(r){t.splice(t.indexOf(r),1);continue}if(!t.some(({segment:a})=>a.preserveWhenNarrow))break;let o=t.slice().reverse().find(({segment:a})=>!a.preserveWhenNarrow);if(!o)break;t.splice(t.indexOf(o),1)}return Ls(i(),e)}function f1(n,e){if(n.sessionRole==="subagent")return"";let t=C(n.sessionTitle?.trim()??"");if(!t||t.toLocaleLowerCase()==="new session")return"";let i=e?E(t,e,"\u2026"):t;return`${h.hex(d.signal)("\u25C7")} ${h.hex(d.muted)(i)}`}function hd(n,e){let t=Xw(n.model??"no model"),i=e==="minimal"||!n.thinking||n.effort?void 0:e==="compact"?`Think ${n.thinking==="on"?"On":"Off"}`:`Thinking ${n.thinking==="on"?"On":"Off"}`,s=e==="minimal"||!n.effort?void 0:e==="compact"?`Eff ${n.effort}`:`Effort ${n.effort}`,r=[i,s].filter(o=>!!o).map(o=>`${Yw()}${h.hex(d.muted)(o)}`).join("");return`${h.hex(d.accent)("\u2726")} ${h.hex(d.accent)(t)}${r}`}function zw(n){let e=n.contextUsage?.contextWindowTokens,t=typeof e=="number"&&Number.isFinite(e)&&e>0?e:n.contextWindowTokens;if(!(t===void 0||!Number.isFinite(t)||t<=0))return t}function Uw(n,e=!1){let t=zw(n);return t===void 0?"":h.hex(d.muted)(`${e?"Ctx":"Context"} ${pi(t)}`)}function Qw(n){let e=n.contextUsage;if(!e||!Number.isFinite(e.usedTokens))return;let t=zw(n);if(t===void 0)return;let i=Math.max(0,Math.min(e.usedTokens,t));return Math.round((t-i)/t*100)}function g1(n,e="full"){let t=Qw(n);if(t===void 0)return"";let i=t<=10?d.error:t<=25?d.warning:d.muted,s=e==="full"?`Context ${t}% left`:e==="compact"?`Ctx ${t}%`:`Ctx ${t}%`;return h.hex(i)(s)}function Kw(n,e=!1){if(n.sessionRole!=="subagent")return"";let t=Xw(n.sessionAgentName?.trim()||"sub-agent"),i=e?`Sub:${t}`:`Sub: ${t}`;return h.hex(d.muted)(i)}function y1(n,e="full"){if(!n?.isGitRepo)return"";let t=n.detached?"detached":n.branch||"unborn",i=e==="full"?t:ge(E(t,e==="minimal"?7:12)),s=n.isWorktree?e==="full"?"worktree":"wt":void 0;return`${h.hex(d.accent)("\u2387")} ${h.hex(d.muted)(i)}${s?`${Yw()}${h.hex(d.muted)(s)}`:""}`}function T1(n,e="full"){let t=n?.reviewLink;if(!n?.isGitRepo||!t)return"";let i=t.vendor==="gitlab",s=h.hex(d.muted)(`${i?"!":"#"}${t.number}`),r=e==="full"?`${h.hex(d.accent)(i?"MR":"PR")} ${s}`:s;return gt().hyperlinks?kn(r,t.url):r}function b1(n,e,t="full"){if(e!=="available"||!n)return"";let i=[Ww("5h","5h",n.fiveHour),Ww("Week","W",n.weekly)].filter(u=>u!==void 0);if(i.length===0)return"";let s=Math.min(...i.map(({remaining:u})=>u)),r=s<=10?d.error:s<=30?d.warning:d.success,a=(t==="minimal"?[i.reduce((u,l)=>l.remaining<u.remaining?l:u)]:i).map(({label:u,compactLabel:l,remaining:c})=>t==="full"?`${u} ${c}%`:`${l}${c}%`).join(t==="full"?" \xB7 ":"/");return h.hex(r)(a)}function Ww(n,e,t){if(t.unlimited||typeof t.remainingPercent!="number"||!Number.isFinite(t.remainingPercent))return;let i=Math.round(Math.min(100,Math.max(0,t.remainingPercent)));return i<=30?{label:n,compactLabel:e,remaining:i}:void 0}function NN(n){return n.filter(Boolean).join(h.hex(d.dim)(" \u2502 "))}function Yw(){return h.hex(d.dim)(" \xB7 ")}function jw(n,e=!1){if(n.planMode!=="plan"&&!n.planModeTransition)return"";let t=n.planMode==="plan"?"PLAN":"DEFAULT",i=n.planModeTransition==="next-message"?e?"\u2026":" next":n.planModeTransition==="submitting"?e?"\u2026":" submitting":"";return h.bold.hex(d.accent)(`${t}${i}`)}function DN(n,e=!1){let t=n.permissionMode?e?ru(n.permissionMode):Mn(n.permissionMode):"Permissions",i=n.permissionModeUpdating?"\u2026":"";return h.bold.hex(n.permissionMode&&ou(n.permissionMode)?d.error:d.signal)(`${t}${i}`)}function Vw(n,e=!1){return DN(n,e)}function FN(n,e){return e?n===e?"~":n.startsWith(`${e}/`)||n.startsWith(`${e}\\`)?`~${n.slice(e.length)}`:n:n}function $N(n){let e=n.replaceAll("\\","/").replace(/\/+$/u,"")||n,t=e.split("/").filter(Boolean),i=t.at(-1)||e;return{full:e,medium:Gw(t,3,i),compact:Gw(t,2,i),base:i}}function Gw(n,e,t){return n.length<=e?n.join("/")||t:`\u2026/${n.slice(-e).join("/")}`}function Xw(n){return n.replaceAll("\\","/").replace(/\/+$/u,"").split("/").at(-1)||n}var BN=1e4;function Jw(n,e){let t=n.statusLineItems?Wi(n.statusLineItems):void 0;return new v1({version:n.version,...t?{statusLineItems:t}:{},workspace:n.workspaceDir,homeDir:n.homeDir,runtimeStatus:"starting"},n.runtime,e,{...n.customStatusLine?{customStatusLine:n.customStatusLine}:{},...n.runCustomStatusProcess?{runCustomStatusProcess:n.runCustomStatusProcess}:{}})}var v1=class extends Ra{constructor(t,i,s,r={}){super(t,r.customStatusLine);this.runtime=i;this.requestRender=s;this.customStatus=r;this.statusLineItems=t.statusLineItems,this.shellState=t,this.syncSources()}shellState;statusLineItems;workspaceGit;refreshTimer;refreshSequence=0;disposed=!1;customStatusRunner;customStatusText;getConfiguredItems(){return this.statusLineItems?.slice()}setConfiguredItems(t){if(!this.disposed){if(this.statusLineItems?.includes("build-mode")||t?.includes("build-mode"))throw new Error("build-mode is a startup-only setting");this.statusLineItems=t?.slice(),this.syncSources(),this.pushState(),this.requestRender()}}preview(t,i,s){let r=this.presentationState(),o=a=>new Ra({...r,statusLineItems:a},this.customStatus.customStatusLine);return{lines:o(t).renderViewport(i,s),unavailable:(t??ji).filter(a=>o([a]).render(1e3).length===0)}}syncSources(){let t=this.statusLineItems??ji,i=!t.includes("build-mode")&&(t.includes("git-branch")||t.includes("review-link"));i&&!this.refreshTimer?(this.refresh(),this.refreshTimer=setInterval(()=>void this.refresh(),BN),this.refreshTimer.unref?.()):i||(clearInterval(this.refreshTimer),this.refreshTimer=void 0,this.refreshSequence+=1,this.workspaceGit=void 0),!t.includes("build-mode")&&t.includes("custom-command")?this.customStatusRunner?this.customStatusRunner.resume():this.startCustomCommand():(this.customStatusRunner?.pause(),this.customStatusText=void 0)}startCustomCommand(){this.customStatusRunner=this.customStatus.customStatusLine?kw(this.statusLineItems,{config:this.customStatus.customStatusLine,version:this.shellState.version,getContext:()=>({workspaceDir:this.shellState.workspace,...this.shellState.agentSessionId?{sessionId:this.shellState.agentSessionId}:{},...this.shellState.model?{model:this.shellState.model}:{},...this.shellState.sessionTitle?{sessionTitle:this.shellState.sessionTitle}:{}}),onText:t=>{this.customStatusText=t,this.pushState(),this.requestRender()},...this.customStatus.runCustomStatusProcess?{runProcess:this.customStatus.runCustomStatusProcess}:{}}):void 0,this.customStatusRunner?.start()}setState(t){if(this.disposed)return;let i={...t,statusLineItems:this.statusLineItems},s=this.shellState.busy===!0&&t.busy!==!0,r=this.shellState.workspace!==t.workspace,o=this.shellState.agentSessionId!==t.agentSessionId;r&&(this.workspaceGit=void 0),(r||o)&&(this.customStatusText=void 0),this.shellState=i,this.pushState(),this.refreshTimer&&(r||s)&&this.refresh(),this.customStatusRunner&&(r?this.customStatusRunner.trigger("workspace-change"):o?this.customStatusRunner.trigger("session-change"):s&&this.customStatusRunner.trigger("turn-end"))}dispose(){this.disposed=!0,this.refreshSequence+=1,clearInterval(this.refreshTimer),this.customStatusRunner?.dispose()}pushState(){super.setState(this.presentationState())}presentationState(){return{...this.shellState,statusLineItems:this.statusLineItems,workspaceGit:this.workspaceGit,customStatusText:this.customStatusText}}async refresh(){let t=++this.refreshSequence;try{let i=await this.runtime.getWorkspaceGitMetadata(this.shellState.workspace);if(this.disposed||t!==this.refreshSequence)return;this.workspaceGit=i,this.pushState(),this.requestRender()}catch{}}};import{createHash as C1}from"node:crypto";import{chmod as zr,copyFile as qN,lstat as HN,mkdir as md,open as UN,readFile as Zw,readdir as KN,rename as Os,rm as WN,stat as ka}from"node:fs/promises";import{tmpdir as jN}from"node:os";import{dirname as fd,extname as VN,isAbsolute as Td,join as x1,relative as rI,resolve as yn}from"node:path";var w1=2,I1=2*1024*1024,yd=64,gd=32,GN=250,St=class extends Error{constructor(t,i){super(i instanceof Error?i.message:String(i),{cause:i});this.operation=t;this.name="TuiDraftRecoveryError"}},Pa=class{dataDir;workspaceDir;sessionKey;debounceMs;timer;latest;writeChain=Promise.resolve();writeGeneration=0;disposed=!1;suspended=!1;onError;onPersisted;constructor(e){this.dataDir=e.dataDir,this.workspaceDir=e.workspaceDir,this.sessionKey=e.sessionKey,this.debounceMs=Math.max(0,e.debounceMs??GN),this.onError=e.onError,this.onPersisted=e.onPersisted}get filePath(){return tI(this.dataDir,this.workspaceDir,this.sessionKey)}get assetsDirectory(){return`${this.filePath.slice(0,-5)}.assets`}async switchSession(e,t={}){let i=aI(e);if(i===this.sessionKey)return;this.timer&&(clearTimeout(this.timer),this.timer=void 0),await this.writeChain.catch(()=>{});let s=this.filePath,r=this.assetsDirectory,o=this.sessionKey;if(this.sessionKey=i,!t.migrateCurrent)return;let a=this.filePath;try{await md(fd(a),{recursive:!0,mode:448}),await this.migrateSessionState(s,r,a,this.assetsDirectory)}catch(u){throw this.sessionKey=o,new St("migrate",u)}}async load(){await this.migrateLegacyWorkspaceDraft();let e;try{let r=await ka(this.filePath);if(!r.isFile()||r.size>I1)return;e=await Zw(this.filePath)}catch{return}let t;try{t=JSON.parse(e.toString("utf8"))}catch{return}if(!sI(t))return;let i=[];for(let r of t.attachments){if(i.length>=yd)break;await ka(r.filePath).then(a=>a.isFile()).catch(()=>!1)&&i.push(r)}let s=[];for(let r of t.retrySubmissions??[]){if(s.length>=gd)break;let o=[];for(let u of r.snapshot.attachments)await ka(u.filePath).then(c=>c.isFile()).catch(()=>!1)&&o.push(u);let a=[];for(let u of r.snapshot.transportAttachments??[]){if(u.assetId){a.push(u);continue}if(!u.filePath)continue;await ka(u.filePath).then(c=>c.isFile()).catch(()=>!1)&&a.push(u)}s.push({retryId:r.retryId,failedReason:r.failedReason,...r.failureCode?{failureCode:r.failureCode}:{},snapshot:{...r.snapshot,editor:nI(r.snapshot.editor,o),attachments:o,...r.snapshot.transportAttachments?{transportAttachments:a}:{}}})}return{editor:nI(t.editor,i),attachments:i,...s.length>0?{retrySubmissions:s}:{}}}schedule(e){this.disposed||(this.latest=S1(e),this.timer&&clearTimeout(this.timer),!this.suspended&&(this.timer=setTimeout(()=>{this.timer=void 0;let t=this.latest;t&&this.enqueueWrite(t,!1).catch(i=>this.onError?.(i))},this.debounceMs),this.timer.unref?.()))}async flush(e,t={}){this.suspended=!1,this.timer&&(clearTimeout(this.timer),this.timer=void 0),this.latest=S1(e),await this.enqueueWrite(this.latest,t.materializeVolatileAttachments===!0)}suspend(){this.disposed||(this.suspended=!0,this.timer&&clearTimeout(this.timer),this.timer=void 0)}dispose(){this.disposed=!0,this.timer&&clearTimeout(this.timer),this.timer=void 0,this.latest=void 0,this.suspended=!1}enqueueWrite(e,t){let i=S1(e);return this.writeChain=this.writeChain.catch(()=>{}).then(()=>this.persist(i,t)).then(()=>this.onPersisted?.()).catch(s=>{throw s instanceof St?s:new St(iI(i)?"save":"cleanup",s)}),this.writeChain}async persist(e,t){if(!iI(e)){await Qr(this.filePath),await Qr(this.assetsDirectory,!0);return}let i=Date.now(),s={schemaVersion:w1,updatedAtMs:i,editor:e.editor,attachments:[...e.attachments],retrySubmissions:[...e.retrySubmissions??[]].slice(0,gd)};XN(s);let r=t?await this.materializeEditorAttachments(e.editor,e.attachments):{editor:e.editor,attachments:e.attachments},o=await Promise.all((e.retrySubmissions??[]).slice(0,gd).map(async m=>({retryId:m.retryId,failedReason:m.failedReason,...m.failureCode?{failureCode:m.failureCode}:{},snapshot:await this.materializeSubmission(m.snapshot)}))),a={schemaVersion:w1,updatedAtMs:i,editor:r.editor,attachments:[...r.attachments],retrySubmissions:o},u=`${JSON.stringify(a)}
|
|
207
|
+
`).replace(/[\r\t]/gu," ");return Y(r,Number.POSITIVE_INFINITY).flatMap(o=>{let a=ge(o),u=a.trim();if(!u)return[];let l=x(a)-x(a.trimStart()),c=Se(o,l,x(u)),p=E(c,e,"\u2026");return p?[i?Ow+p+Ow:h.hex(d.muted)(p)]:[]})}var jr="{paste-image-shortcut}",Nw="/checkin claims the daily reward.",ht={sectionTitles:{tips:"Tips for getting started",news:"What's new \xB7 /changelog for history"},tipPool:["Say what you want and how to verify it.",`Use @ for files; ${jr} for images.`,"Run /init to teach MCode this repo.","Use /plan before a change that needs design or investigation.","Use /context to check the current Session context budget.","Use /sessions to resume earlier work.","Use /history to review and branch from earlier prompts.","Use /goal to keep long-running work focused on a finish line.","Use /permission to choose how MCode handles tool approvals.","Use /feedback to preview a redacted report before upload.",Nw],wide:{tips:["Say what you want and how to verify it.",`Use @ for files; ${jr} for images.`,"Run /init to teach MCode this repo.",Nw],news:["Send follow-ups while MCode works.","/context shows read-only session context.","/feedback previews before upload."]},stacked:{tips:["Say what you want and how to verify it.",`@ files \xB7 ${jr} images \xB7 /init guidance`,"/checkin daily reward"],news:["Follow-ups wait while MCode works.","/context budget \xB7 /feedback preview"]},compact:{tips:[`@ files \xB7 ${jr} images`,"/init repo guidance","/checkin reward"],news:["Follow-ups wait","/context \xB7 /feedback"]},hero:{fullMinWidth:91,mediumMinWidth:44,microMinWidth:11,fallbackTitle:"M"}},Dw=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2557\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u255A\u2588\u2588\u2557\u2588\u2588\u2554\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2557\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2551 \u2588\u2588\u2554\u2588\u2588\u2557 \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D","\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2551\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u255D \u2588\u2588\u2557 \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u2550\u2550\u255D\u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],Fw=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D","\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557","\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D","\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557","\u255A\u2550\u255D \u255A\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D"],$w=["\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2557","\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2551","\u2588\u2588\u2554\u2588\u2588\u2588\u2588\u2554\u2588\u2588\u2551","\u2588\u2588\u2551\u255A\u2588\u2588\u2554\u255D\u2588\u2588\u2551","\u2588\u2588\u2551 \u255A\u2550\u255D \u2588\u2588\u2551","\u255A\u2550\u255D \u255A\u2550\u255D"];function cd(n){let{fullMinWidth:e,mediumMinWidth:t,microMinWidth:i,fallbackTitle:s}=ht.hero,r=n>=e?Dw:n>=t?Fw:n>=i?$w:[s],o=r.length>1,a=Math.max(...r.map(l=>x(l))),u=[d.wordmarkHighlight,d.wordmarkHighlight,d.brand,d.brand,d.wordmarkShadow,d.wordmarkShadow];return r.map((l,c)=>{let p=l+" ".repeat(Math.max(0,a-x(l))),m=c%7,f=o?u[m]??d.brand:d.brand;return Pw(h.bold.hex(f)(p),n)})}var Ea=class{constructor(e,t,i={}){this.state=e;this.keybindings=t;this.content=i}setState(e){this.state=e}invalidate(){}render(e){return this.renderViewport(e,Number.POSITIVE_INFINITY)}renderViewport(e,t){let i=Ma(e);if(i===0)return[];if(i<4)return[Ls("M",i)];let s=Xc(i),r=s.welcome==="compact"?Bw(this.state,i,this.keybindings,this.content):s.welcome==="stacked"?RN(this.state,i,this.keybindings,this.content):AN(this.state,i,this.keybindings,this.content);return r.length+2>t&&s.welcome!=="compact"&&(r=Bw(this.state,i,this.keybindings,this.content)),EN(["",...r,""],t)}};function EN(n,e){if(!Number.isFinite(e))return n;let t=Math.max(1,Math.floor(e)),i=[...n];for(;i.length>t;){let s=i.findIndex(r=>r.length===0);if(s<0)break;i.splice(s,1)}return i.slice(0,t)}function AN(n,e,t,i){let s=Vr(i?.tips,ht.wide.tips,3),r=Vr(i?.changelogEntries,ht.wide.news,3);return[...cd(e),"",qw(n,e),...h1(n,e),dt(Gr(ht.sectionTitles.tips),e),...s.map(o=>dt(dd(Aa(o,t)),e)),a1(e),dt(Gr(ht.sectionTitles.news),e),...r.map(o=>dt(dd(Aa(o,t)),e)),ld(e)]}function RN(n,e,t,i){let s=Vr(i?.tips,ht.stacked.tips,2),r=Vr(i?.changelogEntries,ht.stacked.news,3);return[...cd(e),"",qw(n,e),...h1(n,e),a1(e),dt(Gr(ht.sectionTitles.tips),e),...s.map(o=>dt(dd(Aa(o,t)),e)),dt("",e),dt(Gr(ht.sectionTitles.news),e),...r.map(o=>dt(dd(Aa(o,t)),e)),dt("",e),ld(e)]}function Bw(n,e,t,i){let s=Vr(i?.tips,ht.compact.tips,2),r=Vr(i?.changelogEntries,ht.compact.news,3);return[...cd(e),"",o1(`${h.bold.hex(d.brand)("MCode")} ${h.hex(d.muted)(`v${n.version}`)}`,Hw(n),e),...h1(n,e),dt(Gr("Tips"),e),...s.map(o=>dt(h.hex(d.muted)(Aa(o,t)),e)),dt(Gr(ht.sectionTitles.news),e),...r.map(o=>dt(h.hex(d.muted)(o),e)),ld(e)]}function qw(n,e){return o1(h.hex(d.muted)(`v${n.version}`),Hw(n),e)}function Vr(n,e,t){return n?.length?n.slice(0,t):e}function Gr(n){return h.bold.hex(d.brand)(n)}function dd(n){return`${h.bold.hex(d.orbit)("\u203A")} ${h.hex(d.text)(n)}`}function Aa(n,e){return n.replaceAll(jr,ye("composer.paste-image",e))}function h1(n,e){if(n.accountStatus!=="Sign in with /login")return[];let t=`${h.bold.hex(d.warning)("\u25CB")} ${h.bold.hex(d.warning)(n.accountStatus)}`;return[dt(t,e)]}function Hw(n){return n.accountStatus==="Sign in with /login"?h.bold.hex(d.warning)("\u25CB Login required"):n.runtimeStatus==="ready"?h.bold.hex(d.orbit)("\u25CF Ready"):n.runtimeStatus==="starting"?h.bold.hex(d.signal)("\u25CC Starting"):n.runtimeStatus==="offline"?h.bold.hex(d.warning)("\u25CB Login required"):h.bold.hex(d.error)("\xD7 Error")}var pd=class{availableVersion;setAvailableVersion(e){this.availableVersion=e?.trim()||void 0}invalidate(){}render(e){let t=Ma(e);if(!this.availableVersion||t===0)return[];let i=u1([` ${h.bold.hex(d.signal)("\u2726 A new version of MCode is available")} ${h.hex(d.text)("\u2014 update for the latest improvements")}`,` ${h.bold.hex(d.signal)(`\u2726 MCode ${this.availableVersion} is available`)}`,` ${h.bold.hex(d.signal)("\u2726 MCode update available")}`],t),s=u1([` ${h.hex(d.muted)("Run '")}${h.bold.hex(d.signal)("/update")}${h.hex(d.muted)(`' to install MCode ${this.availableVersion}`)}`,` ${h.hex(d.muted)("Run ")}${h.bold.hex(d.signal)("/update")}${h.hex(d.muted)(` to install ${this.availableVersion}`)}`,` ${h.bold.hex(d.signal)("/update")}${h.hex(d.muted)(" \xB7 review and install")}`,` ${h.bold.hex(d.signal)("/update")}${h.hex(d.muted)(" \xB7 install")}`],t);return[Ls(i,t),Ls(s,t)]}},Ra=class{constructor(e,t){this.state=e;this.customStatusConfig=t}setState(e){this.state=e}invalidate(){}render(e){return this.renderViewport(e,Number.POSITIVE_INFINITY)}renderViewport(e,t){let i=Ma(e);if(i===0)return[];let s=kN(this.state);if(s.length===0)return[];let r=this.customStatusConfig?.display==="block"&&s.includes("custom-command"),o=s.filter(c=>!r||c!=="custom-command").map(c=>PN(c,this.state,this.customStatusConfig)).filter(c=>c!==void 0),a=ON(o,i),u=ge(a).trim()?[a]:[],l=r?this.renderCustomBlock(i,t-u.length-1):[];return u.length===0&&l.length===0?[]:this.customStatusConfig?.position==="below"?["",...u,...l]:["",...l,...u]}renderCustomBlock(e,t){let i=this.customStatusConfig?.maxLines,s=typeof i=="number"&&Number.isFinite(i)?Math.min(5,Math.max(1,Math.floor(i))):3,r=Math.min(s,Math.max(0,Math.floor(t)||0));return r===0?[]:d1(this.state.customStatusText??"",e,this.customStatusConfig?.colorMode).slice(0,r)}};function kN(n){let e=n.statusLineItems??ji;if(!e.includes("build-mode")){if(n.statusLineItems!==void 0)return e;let t=Qw(n);return e.filter(i=>t===void 0?i!=="context-remaining":i!=="context-window")}return["build-mode"]}function PN(n,e,t){switch(n){case"build-mode":return vt([_N(e)],{shrinkPriority:70,preserveWhenNarrow:!0});case"current-dir":{let i=FN(e.workspace,e.homeDir),s=$N(i);return vt([s.full,s.medium,s.compact,s.base].map(r=>h.hex(d.muted)(r)),{shrinkPriority:10,dropPriority:30})}case"session-title":return vt([f1(e),f1(e,18),f1(e,10)],{shrinkPriority:15,dropPriority:60});case"git-branch":return vt([y1(e.workspaceGit),y1(e.workspaceGit,"compact"),y1(e.workspaceGit,"minimal")],{shrinkPriority:20,dropPriority:30});case"review-link":return vt([T1(e.workspaceGit),T1(e.workspaceGit,"compact"),T1(e.workspaceGit,"minimal")],{shrinkPriority:25,dropPriority:35});case"plan-mode":return vt([jw(e),jw(e,!0)],{shrinkPriority:55,dropPriority:55});case"approval-mode":return vt([Vw(e),Vw(e,!0)],{shrinkPriority:60});case"model-with-reasoning":return vt([hd(e,"full"),hd(e,"compact"),hd(e,"minimal")],{shrinkPriority:30,dropPriority:65});case"model":return vt([hd(e,"minimal")],{shrinkPriority:30,dropPriority:20});case"context-window":return vt([Uw(e),Uw(e,!0)],{shrinkPriority:35,dropPriority:64});case"subagent":return vt([Kw(e),Kw(e,!0)],{shrinkPriority:40,dropPriority:60});case"token-quota":return vt([b1(e.tokenPlanQuota,e.tokenPlanQuotaState),b1(e.tokenPlanQuota,e.tokenPlanQuotaState,"compact"),b1(e.tokenPlanQuota,e.tokenPlanQuotaState,"minimal")],{shrinkPriority:45,dropPriority:70});case"cache-read-ratio":return vt([m1(e,"full"),m1(e,"compact"),m1(e,"minimal")],{shrinkPriority:48,dropPriority:10});case"context-remaining":return vt([g1(e,"full"),g1(e,"compact"),g1(e,"minimal")],{shrinkPriority:50,dropPriority:80});case"custom-command":return vt([p1(e,60,t?.colorMode),p1(e,24,t?.colorMode),p1(e,12,t?.colorMode)],{shrinkPriority:35,dropPriority:50})}}function p1(n,e,t){let i=(n.customStatusText??"").split(/\r?\n/u,1)[0]??"";return d1(i,e,t)[0]??""}function m1(n,e="full"){let t=n.sessionCacheReadRatio;if(t===void 0||!Number.isFinite(t))return"";let i=Math.round(Math.min(1,Math.max(0,t))*100),s=e==="full"?`Cache ${i}%`:e==="compact"?`C ${i}%`:`${i}%`;return h.hex(d.muted)(s)}function _N(n){return Lw({seq:n.agentSeq??"0",status:LN(n),sessionId:n.agentSessionId,turnId:n.agentRunId,requestId:n.agentRequestId,activeAgents:n.agentActiveCount,totalAgents:n.agentTotalCount})}function LN(n){return n.agentStatus?n.agentStatus:n.runtimeStatus==="error"?"error":n.busy||n.runtimeStatus==="starting"?"run":"ready"}function vt(n,e){let t=n.filter(Boolean).filter((i,s,r)=>{let o=ge(i);return r.findIndex(a=>ge(a)===o)===s});if(t.length!==0)return{variants:t,...e}}function ON(n,e){let t=n.map(s=>({segment:s,variant:0})),i=()=>NN(t.map(({segment:s,variant:r})=>s.variants[r]??""));for(;x(i())>e;){let s=t.filter(({segment:a,variant:u})=>u+1<a.variants.length).sort((a,u)=>a.segment.shrinkPriority-u.segment.shrinkPriority)[0];if(s){s.variant+=1;continue}let r=t.filter(({segment:a})=>a.dropPriority!==void 0).sort((a,u)=>(a.segment.dropPriority??Number.POSITIVE_INFINITY)-(u.segment.dropPriority??Number.POSITIVE_INFINITY))[0];if(r){t.splice(t.indexOf(r),1);continue}if(!t.some(({segment:a})=>a.preserveWhenNarrow))break;let o=t.slice().reverse().find(({segment:a})=>!a.preserveWhenNarrow);if(!o)break;t.splice(t.indexOf(o),1)}return Ls(i(),e)}function f1(n,e){if(n.sessionRole==="subagent")return"";let t=C(n.sessionTitle?.trim()??"");if(!t||t.toLocaleLowerCase()==="new session")return"";let i=e?E(t,e,"\u2026"):t;return`${h.hex(d.signal)("\u25C7")} ${h.hex(d.muted)(i)}`}function hd(n,e){let t=Xw(n.model??"no model"),i=e==="minimal"||!n.thinking||n.effort?void 0:e==="compact"?`Think ${n.thinking==="on"?"On":"Off"}`:`Thinking ${n.thinking==="on"?"On":"Off"}`,s=e==="minimal"||!n.effort?void 0:e==="compact"?`Eff ${n.effort}`:`Effort ${n.effort}`,r=[i,s].filter(o=>!!o).map(o=>`${Yw()}${h.hex(d.muted)(o)}`).join("");return`${h.hex(d.accent)("\u2726")} ${h.hex(d.accent)(t)}${r}`}function zw(n){let e=n.contextUsage?.contextWindowTokens,t=typeof e=="number"&&Number.isFinite(e)&&e>0?e:n.contextWindowTokens;if(!(t===void 0||!Number.isFinite(t)||t<=0))return t}function Uw(n,e=!1){let t=zw(n);return t===void 0?"":h.hex(d.muted)(`${e?"Ctx":"Context"} ${pi(t)}`)}function Qw(n){let e=n.contextUsage;if(!e||!Number.isFinite(e.usedTokens))return;let t=zw(n);if(t===void 0)return;let i=Math.max(0,Math.min(e.usedTokens,t));return Math.round((t-i)/t*100)}function g1(n,e="full"){let t=Qw(n);if(t===void 0)return"";let i=t<=10?d.error:t<=25?d.warning:d.muted,s=e==="full"?`Context ${t}% left`:e==="compact"?`Ctx ${t}%`:`Ctx ${t}%`;return h.hex(i)(s)}function Kw(n,e=!1){if(n.sessionRole!=="subagent")return"";let t=Xw(n.sessionAgentName?.trim()||"sub-agent"),i=e?`Sub:${t}`:`Sub: ${t}`;return h.hex(d.muted)(i)}function y1(n,e="full"){if(!n?.isGitRepo)return"";let t=n.detached?"detached":n.branch||"unborn",i=e==="full"?t:ge(E(t,e==="minimal"?7:12)),s=n.isWorktree?e==="full"?"worktree":"wt":void 0;return`${h.hex(d.accent)("\u2387")} ${h.hex(d.muted)(i)}${s?`${Yw()}${h.hex(d.muted)(s)}`:""}`}function T1(n,e="full"){let t=n?.reviewLink;if(!n?.isGitRepo||!t)return"";let i=t.vendor==="gitlab",s=h.hex(d.muted)(`${i?"!":"#"}${t.number}`),r=e==="full"?`${h.hex(d.accent)(i?"MR":"PR")} ${s}`:s;return gt().hyperlinks?kn(r,t.url):r}function b1(n,e,t="full"){if(e!=="available"||!n)return"";let i=[Ww("5h","5h",n.fiveHour),Ww("Week","W",n.weekly)].filter(u=>u!==void 0);if(i.length===0)return"";let s=Math.min(...i.map(({remaining:u})=>u)),r=s<=10?d.error:s<=30?d.warning:d.success,a=(t==="minimal"?[i.reduce((u,l)=>l.remaining<u.remaining?l:u)]:i).map(({label:u,compactLabel:l,remaining:c})=>t==="full"?`${u} ${c}%`:`${l}${c}%`).join(t==="full"?" \xB7 ":"/");return h.hex(r)(a)}function Ww(n,e,t){if(t.unlimited||typeof t.remainingPercent!="number"||!Number.isFinite(t.remainingPercent))return;let i=Math.round(Math.min(100,Math.max(0,t.remainingPercent)));return i<=30?{label:n,compactLabel:e,remaining:i}:void 0}function NN(n){return n.filter(Boolean).join(h.hex(d.dim)(" \u2502 "))}function Yw(){return h.hex(d.dim)(" \xB7 ")}function jw(n,e=!1){if(n.planMode!=="plan"&&!n.planModeTransition)return"";let t=n.planMode==="plan"?"PLAN":"DEFAULT",i=n.planModeTransition==="next-message"?e?"\u2026":" next":n.planModeTransition==="submitting"?e?"\u2026":" submitting":"";return h.bold.hex(d.accent)(`${t}${i}`)}function DN(n,e=!1){let t=n.permissionMode?e?ru(n.permissionMode):Mn(n.permissionMode):"Permissions",i=n.permissionModeUpdating?"\u2026":"";return h.bold.hex(n.permissionMode&&ou(n.permissionMode)?d.error:d.signal)(`${t}${i}`)}function Vw(n,e=!1){return DN(n,e)}function FN(n,e){return e?n===e?"~":n.startsWith(`${e}/`)||n.startsWith(`${e}\\`)?`~${n.slice(e.length)}`:n:n}function $N(n){let e=n.replaceAll("\\","/").replace(/\/+$/u,"")||n,t=e.split("/").filter(Boolean),i=t.at(-1)||e;return{full:e,medium:Gw(t,3,i),compact:Gw(t,2,i),base:i}}function Gw(n,e,t){return n.length<=e?n.join("/")||t:`\u2026/${n.slice(-e).join("/")}`}function Xw(n){return n.replaceAll("\\","/").replace(/\/+$/u,"").split("/").at(-1)||n}var BN=1e4;function Jw(n,e){let t=n.statusLineItems?Wi(n.statusLineItems):void 0;return new v1({version:n.version,...t?{statusLineItems:t}:{},workspace:n.workspaceDir,homeDir:n.homeDir,runtimeStatus:"starting"},n.runtime,e,{...n.customStatusLine?{customStatusLine:n.customStatusLine}:{},...n.runCustomStatusProcess?{runCustomStatusProcess:n.runCustomStatusProcess}:{}})}var v1=class extends Ra{constructor(t,i,s,r={}){super(t,r.customStatusLine);this.runtime=i;this.requestRender=s;this.customStatus=r;this.statusLineItems=t.statusLineItems,this.shellState=t,this.syncSources()}shellState;statusLineItems;workspaceGit;refreshTimer;refreshSequence=0;disposed=!1;customStatusRunner;customStatusText;getConfiguredItems(){return this.statusLineItems?.slice()}setConfiguredItems(t){if(!this.disposed){if(this.statusLineItems?.includes("build-mode")||t?.includes("build-mode"))throw new Error("build-mode is a startup-only setting");this.statusLineItems=t?.slice(),this.syncSources(),this.pushState(),this.requestRender()}}preview(t,i,s){let r=this.presentationState(),o=a=>new Ra({...r,statusLineItems:a},this.customStatus.customStatusLine);return{lines:o(t).renderViewport(i,s),unavailable:(t??ji).filter(a=>o([a]).render(1e3).length===0)}}syncSources(){let t=this.statusLineItems??ji,i=!t.includes("build-mode")&&(t.includes("git-branch")||t.includes("review-link"));i&&!this.refreshTimer?(this.refresh(),this.refreshTimer=setInterval(()=>void this.refresh(),BN),this.refreshTimer.unref?.()):i||(clearInterval(this.refreshTimer),this.refreshTimer=void 0,this.refreshSequence+=1,this.workspaceGit=void 0),!t.includes("build-mode")&&t.includes("custom-command")?this.customStatusRunner?this.customStatusRunner.resume():this.startCustomCommand():(this.customStatusRunner?.pause(),this.customStatusText=void 0)}startCustomCommand(){this.customStatusRunner=this.customStatus.customStatusLine?kw(this.statusLineItems,{config:this.customStatus.customStatusLine,version:this.shellState.version,getContext:()=>({workspaceDir:this.shellState.workspace,...this.shellState.agentSessionId?{sessionId:this.shellState.agentSessionId}:{},...this.shellState.model?{model:this.shellState.model}:{},...this.shellState.sessionTitle?{sessionTitle:this.shellState.sessionTitle}:{}}),onText:t=>{this.customStatusText=t,this.pushState(),this.requestRender()},...this.customStatus.runCustomStatusProcess?{runProcess:this.customStatus.runCustomStatusProcess}:{}}):void 0,this.customStatusRunner?.start()}setState(t){if(this.disposed)return;let i={...t,statusLineItems:this.statusLineItems},s=this.shellState.busy===!0&&t.busy!==!0,r=this.shellState.workspace!==t.workspace,o=this.shellState.agentSessionId!==t.agentSessionId;r&&(this.workspaceGit=void 0),(r||o)&&(this.customStatusText=void 0),this.shellState=i,this.pushState(),this.refreshTimer&&(r||s)&&this.refresh(),this.customStatusRunner&&(r?this.customStatusRunner.trigger("workspace-change"):o?this.customStatusRunner.trigger("session-change"):s&&this.customStatusRunner.trigger("turn-end"))}dispose(){this.disposed=!0,this.refreshSequence+=1,clearInterval(this.refreshTimer),this.customStatusRunner?.dispose()}pushState(){super.setState(this.presentationState())}presentationState(){return{...this.shellState,statusLineItems:this.statusLineItems,workspaceGit:this.workspaceGit,customStatusText:this.customStatusText}}async refresh(){let t=++this.refreshSequence;try{let i=await this.runtime.getWorkspaceGitMetadata(this.shellState.workspace);if(this.disposed||t!==this.refreshSequence)return;this.workspaceGit=i,this.pushState(),this.requestRender()}catch{}}};import{createHash as C1}from"node:crypto";import{chmod as zr,copyFile as qN,lstat as HN,mkdir as md,open as UN,readFile as Zw,readdir as KN,rename as Os,rm as WN,stat as ka}from"node:fs/promises";import{tmpdir as jN}from"node:os";import{dirname as fd,extname as VN,isAbsolute as Td,join as x1,relative as rI,resolve as yn}from"node:path";var w1=2,I1=2*1024*1024,yd=64,gd=32,GN=250,St=class extends Error{constructor(t,i){super(i instanceof Error?i.message:String(i),{cause:i});this.operation=t;this.name="TuiDraftRecoveryError"}},Pa=class{dataDir;workspaceDir;sessionKey;debounceMs;timer;latest;writeChain=Promise.resolve();writeGeneration=0;disposed=!1;suspended=!1;onError;onPersisted;constructor(e){this.dataDir=e.dataDir,this.workspaceDir=e.workspaceDir,this.sessionKey=e.sessionKey,this.debounceMs=Math.max(0,e.debounceMs??GN),this.onError=e.onError,this.onPersisted=e.onPersisted}get filePath(){return tI(this.dataDir,this.workspaceDir,this.sessionKey)}get assetsDirectory(){return`${this.filePath.slice(0,-5)}.assets`}async switchSession(e,t={}){let i=aI(e);if(i===this.sessionKey)return;this.timer&&(clearTimeout(this.timer),this.timer=void 0),await this.writeChain.catch(()=>{});let s=this.filePath,r=this.assetsDirectory,o=this.sessionKey;if(this.sessionKey=i,!t.migrateCurrent)return;let a=this.filePath;try{await md(fd(a),{recursive:!0,mode:448}),await this.migrateSessionState(s,r,a,this.assetsDirectory)}catch(u){throw this.sessionKey=o,new St("migrate",u)}}async load(){await this.migrateLegacyWorkspaceDraft();let e;try{let r=await ka(this.filePath);if(!r.isFile()||r.size>I1)return;e=await Zw(this.filePath)}catch{return}let t;try{t=JSON.parse(e.toString("utf8"))}catch{return}if(!sI(t))return;let i=[];for(let r of t.attachments){if(i.length>=yd)break;await ka(r.filePath).then(a=>a.isFile()).catch(()=>!1)&&i.push(r)}let s=[];for(let r of t.retrySubmissions??[]){if(s.length>=gd)break;let o=[];for(let u of r.snapshot.attachments)await ka(u.filePath).then(c=>c.isFile()).catch(()=>!1)&&o.push(u);let a=[];for(let u of r.snapshot.transportAttachments??[]){if(u.assetId){a.push(u);continue}if(!u.filePath)continue;await ka(u.filePath).then(c=>c.isFile()).catch(()=>!1)&&a.push(u)}s.push({retryId:r.retryId,failedReason:r.failedReason,...r.failureCode?{failureCode:r.failureCode}:{},snapshot:{...r.snapshot,editor:nI(r.snapshot.editor,o),attachments:o,...r.snapshot.transportAttachments?{transportAttachments:a}:{}}})}return{editor:nI(t.editor,i),attachments:i,...s.length>0?{retrySubmissions:s}:{}}}schedule(e){this.disposed||(this.latest=S1(e),this.timer&&clearTimeout(this.timer),!this.suspended&&(this.timer=setTimeout(()=>{this.timer=void 0;let t=this.latest;t&&this.enqueueWrite(t,!1).catch(i=>this.onError?.(i))},this.debounceMs),this.timer.unref?.()))}async flush(e,t={}){this.suspended=!1,this.timer&&(clearTimeout(this.timer),this.timer=void 0),this.latest=S1(e),await this.enqueueWrite(this.latest,t.materializeVolatileAttachments===!0)}suspend(){this.disposed||(this.suspended=!0,this.timer&&clearTimeout(this.timer),this.timer=void 0)}dispose(){this.disposed=!0,this.timer&&clearTimeout(this.timer),this.timer=void 0,this.latest=void 0,this.suspended=!1}enqueueWrite(e,t){let i=S1(e);return this.writeChain=this.writeChain.catch(()=>{}).then(()=>this.persist(i,t)).then(()=>this.onPersisted?.()).catch(s=>{throw s instanceof St?s:new St(iI(i)?"save":"cleanup",s)}),this.writeChain}async persist(e,t){if(!iI(e)){await Qr(this.filePath),await Qr(this.assetsDirectory,!0);return}let i=Date.now(),s={schemaVersion:w1,updatedAtMs:i,editor:e.editor,attachments:[...e.attachments],retrySubmissions:[...e.retrySubmissions??[]].slice(0,gd)};XN(s);let r=t?await this.materializeEditorAttachments(e.editor,e.attachments):{editor:e.editor,attachments:e.attachments},o=await Promise.all((e.retrySubmissions??[]).slice(0,gd).map(async m=>({retryId:m.retryId,failedReason:m.failedReason,...m.failureCode?{failureCode:m.failureCode}:{},snapshot:await this.materializeSubmission(m.snapshot)}))),a={schemaVersion:w1,updatedAtMs:i,editor:r.editor,attachments:[...r.attachments],retrySubmissions:o},u=`${JSON.stringify(a)}
|
|
208
208
|
`;if(Buffer.byteLength(u)>I1)throw oI();let l=fd(this.filePath);await md(l,{recursive:!0,mode:448}),await zr(l,448);let c=`${this.filePath}.${process.pid}.${++this.writeGeneration}.tmp`,p=!1;try{await eI(c,u),p=!0,await Os(c,this.filePath),p=!1,await zr(this.filePath,384),await this.pruneMaterializedAssets(a)}finally{p&&await Qr(c).catch(()=>{})}}async migrateSessionState(e,t,i,s){let r;try{r=await Zw(e)}catch(p){if(E1(p))return;throw p}let o;try{o=JSON.parse(r.toString("utf8"))}catch{o=void 0}if(!sI(o)){await zr(e,384),await Os(e,i);return}let a=!1;try{await Os(t,s),a=!0}catch(p){if(!E1(p))throw p}let u=`${i}.${process.pid}.${++this.writeGeneration}.tmp`,l=!1,c=!1;try{if(await zr(e,384),a){let p=YN(o,t,s);await eI(u,`${JSON.stringify(p)}
|
|
209
209
|
`),l=!0}await Os(e,i),c=!0,l&&(await Os(u,i),l=!1)}catch(p){throw c&&await Os(i,e).catch(()=>{}),a&&await Os(s,t).catch(()=>{}),p}finally{l&&await Qr(u).catch(()=>{})}}async migrateLegacyWorkspaceDraft(){if(this.sessionKey!=="new-session"||await ka(this.filePath).then(s=>s.isFile()).catch(()=>!1))return;let t=tI(this.dataDir,this.workspaceDir),i=`${t.slice(0,-5)}.assets`;await md(fd(this.filePath),{recursive:!0,mode:448}),await this.migrateSessionState(t,i,this.filePath,this.assetsDirectory)}async materializeEditorAttachments(e,t){let i=[],s=new Map;for(let r of t){if(!t7(r)){i.push(r);continue}let o=VN(r.fileName).slice(0,16),a=C1("sha256").update(r.filePath).digest("hex").slice(0,16),u=x1(this.assetsDirectory,`${a}${o}`);try{await md(this.assetsDirectory,{recursive:!0,mode:448}),await zr(this.assetsDirectory,448),await qN(r.filePath,u),await zr(u,384),i.push({...r,filePath:u}),s.set(r.filePath,u)}catch(l){throw new Error(`Unable to preserve clipboard media Draft: ${n7(l)}`)}}return{editor:M1(e,s),attachments:i}}async materializeSubmission(e){let t=await this.materializeEditorAttachments(e.editor,e.attachments),i=new Map;return e.attachments.forEach((s,r)=>{let o=t.attachments[r];o&&o.filePath!==s.filePath&&i.set(s.filePath,o.filePath)}),{submissionId:e.submissionId,...e.sessionId?{sessionId:e.sessionId}:{},editor:t.editor,content:e.content,...e.transportContent?{transportContent:e.transportContent}:{},attachments:t.attachments,...e.transportAttachments?{transportAttachments:e.transportAttachments.map(s=>{let r=s.filePath?i.get(s.filePath):void 0;return{...s,...r?{filePath:r}:{}}})}:{},createdAtMs:e.createdAtMs,...e.clientIntent?{clientIntent:e.clientIntent}:{}}}async pruneMaterializedAssets(e){let t=new Set([...e.attachments,...(e.retrySubmissions??[]).flatMap(s=>s.snapshot.attachments)].map(s=>yn(s.filePath)).filter(s=>fd(s)===yn(this.assetsDirectory))),i=await KN(this.assetsDirectory,{withFileTypes:!0}).catch(()=>[]);await Promise.all(i.map(async s=>{if(!s.isFile())return;let r=yn(this.assetsDirectory,s.name);t.has(r)||await Qr(r)}))}};async function eI(n,e){let t=await UN(n,"wx",384);try{try{await t.writeFile(e,"utf8")}finally{await t.close()}}catch(i){throw await Qr(n).catch(()=>{}),i}}async function Qr(n,e=!1){try{try{await HN(n)}catch(t){if(E1(t))return;throw t}await WN(n,{recursive:e,force:!0})}catch(t){throw new St("cleanup",t)}}function tI(n,e,t){let i=C1("sha256").update(yn(e)).digest("hex").slice(0,24);if(!t)return x1(yn(n),"v2","mcode","drafts",`${i}.json`);let s=C1("sha256").update(aI(t)).digest("hex").slice(0,24);return x1(yn(n),"v2","mcode","drafts",i,`${s}.json`)}function S1(n){return{editor:{...n.editor,pastes:n.editor.pastes.map(e=>({...e})),...n.editor.attachmentPlaceholders?{attachmentPlaceholders:n.editor.attachmentPlaceholders.map(e=>({...e}))}:{}},attachments:n.attachments.map(e=>({...e})),...n.retrySubmissions?{retrySubmissions:n.retrySubmissions.map(zN)}:{}}}function zN(n){return{retryId:n.retryId,failedReason:n.failedReason,...n.failureCode?{failureCode:n.failureCode}:{},snapshot:{submissionId:n.snapshot.submissionId,...n.snapshot.sessionId?{sessionId:n.snapshot.sessionId}:{},editor:QN(n.snapshot.editor),content:n.snapshot.content,...n.snapshot.transportContent?{transportContent:n.snapshot.transportContent}:{},attachments:n.snapshot.attachments.map(e=>({...e})),...n.snapshot.transportAttachments?{transportAttachments:n.snapshot.transportAttachments.map(e=>({...e}))}:{},createdAtMs:n.snapshot.createdAtMs,...n.snapshot.clientIntent?{clientIntent:n.snapshot.clientIntent}:{}}}}function QN(n){return{...n,pastes:n.pastes.map(e=>({...e})),...n.attachmentPlaceholders?{attachmentPlaceholders:n.attachmentPlaceholders.map(e=>({...e}))}:{}}}function M1(n,e){return e.size===0||!n.attachmentPlaceholders?n:{...n,attachmentPlaceholders:n.attachmentPlaceholders.map(t=>({...t,id:e.get(t.id)??t.id}))}}function nI(n,e){if(!n.attachmentPlaceholders)return n;let t=new Set(e.map(i=>i.filePath));return{...n,attachmentPlaceholders:n.attachmentPlaceholders.filter(i=>t.has(i.id))}}function YN(n,e,t){let i=new Map,s=a=>a.map(u=>{let l=rI(yn(e),yn(u.filePath));if(!l||l.startsWith("..")||Td(l))return{...u};let c=yn(t,l);return i.set(u.filePath,c),{...u,filePath:c}}),r=s(n.attachments),o=(n.retrySubmissions??[]).map(a=>{let u=s(a.snapshot.attachments);return{retryId:a.retryId,failedReason:a.failedReason,...a.failureCode?{failureCode:a.failureCode}:{},snapshot:{...a.snapshot,attachments:u,editor:M1(a.snapshot.editor,i)}}});return{...n,attachments:r,editor:M1(n.editor,i),retrySubmissions:o}}function iI(n){return n.editor.text.length>0||n.attachments.length>0||(n.retrySubmissions?.length??0)>0}function XN(n){if(Buffer.byteLength(`${JSON.stringify(n)}
|
|
210
210
|
`)>I1)throw oI()}function oI(){return new Error("Draft recovery exceeds the 2 MiB safety limit.")}function sI(n){if(!mi(n)||n.schemaVersion!==1&&n.schemaVersion!==w1||!Number.isFinite(n.updatedAtMs)||!uI(n.editor)||!Array.isArray(n.attachments)||n.attachments.length>yd||!n.attachments.every(lI)||n.retrySubmissions!==void 0&&(!Array.isArray(n.retrySubmissions)||n.retrySubmissions.length>gd||!n.retrySubmissions.every(JN)))return!1;n.retrySubmissions===void 0&&(n.retrySubmissions=[]);let e=new Set(n.attachments.map(t=>t.filePath));return(n.editor.attachmentPlaceholders??[]).every(t=>e.has(t.id))}function JN(n){return mi(n)&&typeof n.retryId=="string"&&n.retryId.startsWith("retry:")&&typeof n.failedReason=="string"&&n.failedReason.length>0&&(n.failureCode===void 0||typeof n.failureCode=="string"&&n.failureCode.length>0)&&ZN(n.snapshot)}function ZN(n){if(!mi(n)||typeof n.submissionId!="string"||n.submissionId.length===0||n.sessionId!==void 0&&typeof n.sessionId!="string"||!uI(n.editor)||typeof n.content!="string"||n.transportContent!==void 0&&typeof n.transportContent!="string"||!Array.isArray(n.attachments)||n.attachments.length>yd||!n.attachments.every(lI)||n.transportAttachments!==void 0&&(!Array.isArray(n.transportAttachments)||n.transportAttachments.length>yd||!n.transportAttachments.every(e7))||n.clientIntent!==void 0&&n.clientIntent!=="plan-entry"&&n.clientIntent!=="plan-exit"||!Number.isFinite(n.createdAtMs))return!1;let e=new Set(n.attachments.map(t=>t.filePath));return(n.editor.attachmentPlaceholders??[]).every(t=>e.has(t.id))}function aI(n){return n.trim()||"new-session"}function E1(n){return mi(n)&&n.code==="ENOENT"}function uI(n){if(!mi(n)||n.schemaVersion!==1||typeof n.text!="string"||!Number.isInteger(n.cursor)||n.cursor<0||n.cursor>n.text.length||!Number.isInteger(n.pasteCounter)||n.pasteCounter<0||!Array.isArray(n.pastes)||n.attachmentPlaceholders!==void 0&&!Array.isArray(n.attachmentPlaceholders))return!1;let e=n.text,t=new Set;if(!n.pastes.every(o=>!mi(o)||!Number.isInteger(o.id)||o.id<=0||o.id>n.pasteCounter||t.has(o.id)||typeof o.content!="string"?!1:(t.add(o.id),!0)))return!1;let s=new Set,r=[];return(n.attachmentPlaceholders??[]).every(o=>{if(!mi(o)||typeof o.id!="string"||!o.id||s.has(o.id)||typeof o.label!="string"||!o.label||!Number.isInteger(o.start)||!Number.isInteger(o.end)||o.leadingSpace!==void 0&&typeof o.leadingSpace!="boolean")return!1;let a=o.start,u=o.end,l=o.leadingSpace===!0?a-1:a;return a<0||u<=a||u>e.length||e.slice(a,u)!==o.label||o.leadingSpace===!0&&e[a-1]!==" "||r.some(c=>l<c.end&&u>c.start)?!1:(s.add(o.id),r.push({start:l,end:u}),!0)})}function lI(n){return mi(n)&&(n.type==="file"||n.type==="image")&&typeof n.filePath=="string"&&Td(n.filePath)&&typeof n.fileName=="string"&&n.fileName.length>0&&typeof n.mimeType=="string"&&Number.isFinite(n.sizeBytes)&&n.sizeBytes>=0}function e7(n){return mi(n)&&(n.type==="file"||n.type==="image")&&typeof n.fileName=="string"&&n.fileName.length>0&&typeof n.mimeType=="string"&&(n.sizeBytes===void 0||Number.isFinite(n.sizeBytes)&&n.sizeBytes>=0)&&(typeof n.filePath=="string"&&Td(n.filePath)||typeof n.assetId=="string"&&n.assetId.length>0)}function t7(n){let e=rI(yn(jN()),yn(n.filePath));return!e||e.startsWith("..")||Td(e)?!1:e.split(/[\\/]/u)[0]?.startsWith("minimax-code-clipboard-")===!0}function mi(n){return typeof n=="object"&&n!==null}function n7(n){return n instanceof Error?n.message:String(n)}function _a(n){return{submissionId:n.submissionId,...n.sessionId?{sessionId:n.sessionId}:{},editor:i7(n.editor),content:n.content,...n.transportContent?{transportContent:n.transportContent}:{},attachments:n.resources.attachments.map(e=>({...e})),transportAttachments:(n.transportAttachments??n.resources.attachments).map(e=>({...e})),createdAtMs:n.createdAtMs??Date.now(),...n.clientIntent?{clientIntent:n.clientIntent}:{},...n.reviewRequest?{reviewRequest:n.reviewRequest}:{}}}function i7(n){return{...n,pastes:n.pastes.map(e=>({...e})),...n.attachmentPlaceholders?{attachmentPlaceholders:n.attachmentPlaceholders.map(e=>({...e}))}:{}}}var s7=3e4,bd=class{constructor(e){this.options=e;this.recovery=this.createRecovery(this.sessionKey)}recovery;sessionKey="new-session";transitionTail=Promise.resolve();pendingSubmissions=new Map;pendingSubmissionCounter=0;stopped=!1;adoptionAttempt;reportedErrors=new Map;unsavedDrafts=new Map;async hydrate(){let e=await this.loadRecovery();if(!e||this.stopped||!this.restore(e)&&e.attachments.length===0)return;let i=[e.editor.text?"text":void 0,e.attachments.length>0?`${e.attachments.length} attachment${e.attachments.length===1?"":"s"}`:void 0].filter(s=>!!s);this.options.onRestored(`Draft restored \xB7 ${i.join(" + ")}`)}schedule(){this.stopped||this.recovery?.schedule(this.capture())}suspendForSubmission(e,t){if(this.recovery?.suspend(),!t)return;let i=this.sessionKey==="new-session"?this.sessionKey:t.sessionId??this.sessionKey;for(let[a,u]of this.pendingSubmissions)u.sessionKey===i&&this.pendingSubmissions.delete(a);this.pendingSubmissionCounter+=1;let s=`pending-${String(Date.now())}-${String(this.pendingSubmissionCounter)}`,r=_a({submissionId:s,sessionId:t.sessionId??i,editor:t.editor,content:e?.trim()??"",resources:t.resources,...t.transportContent?{transportContent:t.transportContent}:{},...t.transportAttachments?{transportAttachments:t.transportAttachments}:{}}),o=`retry:${s}`;return this.pendingSubmissions.set(o,{sessionKey:i,retry:{retryId:o,snapshot:r,failedReason:"MCode stopped before Runtime admission completed.",failureCode:"submission.interrupted"}}),o}updatePendingSubmission(e,t){if(!e)return;let i=this.pendingSubmissions.get(e);i&&this.pendingSubmissions.set(e,{...i,retry:{...i.retry,snapshot:t}})}settleSubmission(e){if(this.stopped)return;let t=e?this.pendingSubmissions.get(e):void 0;if(!(e&&!t)&&(e&&this.pendingSubmissions.delete(e),!!this.recovery)){if(t&&t.sessionKey!==this.sessionKey){this.persistDetachedSession(t.sessionKey);return}this.recovery.flush(this.capture()).catch(i=>this.report(i))}}switchSession(e){return this.enqueueTransition(async()=>{if(this.stopped||e===this.sessionKey)return;if(!this.recovery){await this.discardComposer(),this.options.editor.restoreDraft(A1()),this.sessionKey=e;return}let t=this.capture();try{await this.recovery.flush(t,{materializeVolatileAttachments:!0})}catch(s){this.unsavedDrafts.set(this.sessionKey,t),this.options.composerDraft.reserveSubmission(t),this.report(s)}await this.discardComposer(),this.options.editor.restoreDraft(A1());try{await this.recovery.switchSession(e)}catch(s){this.report(new St("migrate",s)),this.recovery.dispose(),this.recovery=this.createRecovery(e)}this.sessionKey=e,this.adoptionAttempt=void 0;let i=this.unsavedDrafts.get(e)??await this.loadRecovery();i&&(this.unsavedDrafts.delete(e),this.restore(i))})}adoptCreatedSession(e){!this.recovery||this.sessionKey!=="new-session"||this.stopped||this.adoptionAttempt?.sessionId===e&&Date.now()<this.adoptionAttempt.retryAtMs||(this.adoptionAttempt={sessionId:e,retryAtMs:Number.POSITIVE_INFINITY},this.enqueueTransition(async()=>{this.stopped||this.sessionKey!=="new-session"||(await this.recovery?.switchSession(e,{migrateCurrent:!0}),this.migratePendingSession("new-session",e),this.sessionKey=e,this.adoptionAttempt=void 0,this.reportedErrors.delete("migrate"),await this.recovery?.flush(this.capture()))}).catch(t=>{this.adoptionAttempt={sessionId:e,retryAtMs:Date.now()+s7},this.report(t instanceof St?t:new St("migrate",t))}))}async suspend(){!this.recovery||this.stopped||(await this.transitionTail.catch(()=>{}),await this.recovery.flush(this.capture(),{materializeVolatileAttachments:!0}).catch(e=>this.report(e)),this.recovery.suspend())}resume(){!this.recovery||this.stopped||this.recovery.flush(this.capture()).catch(e=>this.report(e))}async stop(){if(this.stopped)return;this.stopped=!0,await this.transitionTail.catch(()=>{});let e=!0;if(this.recovery){try{await this.recovery.flush(this.capture(),{materializeVolatileAttachments:!0})}catch(t){e=!1,this.report(t)}this.recovery.dispose()}e&&await this.discardComposer()}createRecovery(e){if(this.options.dataDir)return new Pa({dataDir:this.options.dataDir,workspaceDir:this.options.workspaceDir,sessionKey:e,onError:t=>this.report(t),onPersisted:()=>{this.reportedErrors.delete("save"),this.reportedErrors.delete("cleanup")}})}async loadRecovery(){try{let e=await this.recovery?.load();return this.reportedErrors.delete("load"),e}catch(e){this.report(new St("load",e));return}}async discardComposer(){await this.options.composerDraft.discard().catch(e=>this.report(new St("cleanup",e)))}capture(){let e=this.options.composerDraft.snapshot();return{editor:this.options.editor.captureDraft(),attachments:[...e.attachments],retrySubmissions:this.captureRetrySubmissions(this.sessionKey)}}restore(e){let t=this.options.editor.restoreDraft(e.editor);this.options.composerDraft.restoreAttachments(e.attachments);for(let i of e.retrySubmissions??[])i.failureCode==="submission.interrupted"&&(t=this.options.editor.restoreSubmittedDraft(i.snapshot.editor)||t,this.options.composerDraft.restoreAttachments(i.snapshot.attachments),this.options.onRetryRestored?.(i.snapshot));return t}captureRetrySubmissions(e){return[...this.pendingSubmissions.values()].filter(t=>t.sessionKey===e).map(t=>t.retry)}persistDetachedSession(e){let t=this.options.dataDir;!t||this.stopped||this.enqueueTransition(async()=>{let i=new Pa({dataDir:t,workspaceDir:this.options.workspaceDir,sessionKey:e});try{let s=this.unsavedDrafts.get(e),o={...s??await i.load()??r7(),retrySubmissions:this.captureRetrySubmissions(e)};s&&this.unsavedDrafts.set(e,o),await i.flush(o)}finally{i.dispose()}}).catch(i=>this.report(i))}migratePendingSession(e,t){for(let[i,s]of this.pendingSubmissions)s.sessionKey===e&&this.pendingSubmissions.set(i,{sessionKey:t,retry:{...s.retry,snapshot:{...s.retry.snapshot,sessionId:t}}})}enqueueTransition(e){let t=this.transitionTail.catch(()=>{}).then(e);return this.transitionTail=t.catch(()=>{}),t}report(e){let t=e instanceof St?e.operation:"save",i=e instanceof Error?e.message:String(e);this.reportedErrors.get(t)!==i&&(this.reportedErrors.set(t,i),this.options.onError?.(e))}};function A1(){return{schemaVersion:1,text:"",cursor:0,pastes:[],pasteCounter:0}}function r7(){return{editor:A1(),attachments:[],retrySubmissions:[]}}import{realpath as o7,stat as a7}from"node:fs/promises";import{homedir as u7}from"node:os";import{basename as l7,isAbsolute as c7,parse as d7,resolve as Yr}from"node:path";function cI(n){return new k1(n.workspaceDir,n.workspaceRoots,n.homeDir)}var k1=class{constructor(e,t=[],i=u7()){this.homeDir=i;let s=Yr(e),r=[{path:s,label:R1(s),primary:!0},...t],o=new Set;this.roots=r.flatMap(a=>{let u=Yr(a.path),l=La(u);return o.has(l)?[]:(o.add(l),[{path:u,label:a.label?.trim()||R1(u),primary:u===s}])})}roots;list(){return this.roots.map(e=>({...e}))}additionalDirectories(){return this.roots.filter(e=>e.primary!==!0).map(e=>e.path)}async add(e){let t=h7(e.trim());if(!t)throw new Error("Usage: /add-dir <path>");if(/[\u0000\r\n]/u.test(t))throw new Error("Directory path contains unsupported control characters.");let i=t==="~"?this.homeDir:t.startsWith("~/")||t.startsWith("~\\")?Yr(this.homeDir,t.slice(2)):t,s=this.roots.find(c=>c.primary)?.path??process.cwd(),r=c7(i)?Yr(i):Yr(s,i),o;try{o=await o7(r)}catch(c){let p=c.code;throw new Error(p==="ENOENT"?`Directory does not exist: ${r}`:`Unable to inspect directory ${r}: ${p7(c)}`)}if(!(await a7(o)).isDirectory())throw new Error(`Path is not a directory: ${o}`);if(o===d7(o).root)throw new Error("Refusing to add a filesystem root; choose a narrower directory.");if(La(o)===La(Yr(this.homeDir)))throw new Error("Refusing to add the whole home directory; choose a narrower directory.");let u=this.roots.find(c=>La(c.path)===La(o));if(u)return{...u};if(this.additionalDirectories().length>=16)throw new Error("A CLI process can use at most 16 additional directories.");let l={path:o,label:R1(o),primary:!1};return this.roots=[...this.roots,l],{...l}}};function La(n){return process.platform==="win32"?n.toLocaleLowerCase():n}function R1(n){return l7(n)||n}function h7(n){if(n.length<2)return n;let e=n[0],t=n.at(-1);return e==='"'&&t==='"'||e==="'"&&t==="'"?n.slice(1,-1):n}function p7(n){return n instanceof Error?n.message:String(n)}var m7=1e3,vd=class{goal;baselineSeconds=0;baselineAtMs=0;timer;animationPaused=!1;animate;now;requestRender;chalk;constructor(e={}){this.animate=e.animate??!0,this.now=e.now??Date.now,this.requestRender=e.requestRender??(()=>{}),this.chalk=e.chalk??h}setGoal(e){let t=this.now(),i=e!==void 0&&this.goal!==void 0&&e.goalId===this.goal.goalId&&e.status==="active"&&this.goal.status==="active",s=i?this.elapsedSeconds(t):0;this.goal=e,this.baselineSeconds=e?Math.max(e.timeUsedSeconds,i?s:0):0,this.baselineAtMs=t,e?.status==="active"&&this.animate&&!this.animationPaused?this.startTimer():this.stopTimer(),this.requestRender()}setAnimationPaused(e){if(this.animationPaused!==e){if(this.animationPaused=e,e){this.stopTimer();return}this.animate&&this.goal?.status==="active"&&this.startTimer()}}getGoal(){return this.goal}invalidate(){}render(e){let t=v7(e),i=this.goal;if(!i||i.status==="complete"||t===0)return[];let s=fI(i),r=P1(this.elapsedSeconds(this.now())),o=i.hasKickoffAttachments?" \xB7 Attachment":"",a=this.chalk.hex(d.dim)(" ")+this.chalk.bold.hex(s.color)("\u25CE Goal")+this.chalk.hex(d.dim)(" \xB7 ")+this.chalk.bold.hex(s.color)(s.label)+this.chalk.hex(d.muted)(` \xB7 ${r} active${o}`);x(a)>t&&(a=this.chalk.bold.hex(s.color)("\u25CE Goal")+this.chalk.hex(d.dim)(" \xB7 ")+this.chalk.bold.hex(s.color)(s.label)+this.chalk.hex(d.muted)(` \xB7 ${r}`));let u=y7(i),l=gI(i.lastVerification),c=_1(i.objective)||"Untitled Goal",p=mI(i.status),m=[Xr(a,t,this.chalk),Xr(u,t,this.chalk)];return l&&m.push(Xr(l,t,this.chalk)),x(`${c} \xB7 ${p}`)<=t?(m.push(Xr(`${c} \xB7 ${p}`,t,this.chalk)),m):(m.push(Xr(c,t,this.chalk),Xr(p,t,this.chalk)),m)}dispose(){this.stopTimer()}elapsedSeconds(e){if(this.goal?.status!=="active")return Math.max(0,Math.floor(this.baselineSeconds));let t=Math.max(0,Math.floor((e-this.baselineAtMs)/1e3));return Math.max(0,Math.floor(this.baselineSeconds+t))}startTimer(){this.timer||(this.timer=setInterval(this.requestRender,m7),this.timer.unref())}stopTimer(){this.timer&&(clearInterval(this.timer),this.timer=void 0)}};function P1(n){return Bi(n)}function hI(n){return["\u2713 Goal complete",P1(n.timeUsedSeconds),`${Jr(n.tokensUsed)} tokens`,`${Jr(n.turnsUsed)} turns`].join(" \xB7 ")}function pI(n){let e=[`Goal \xB7 ${fI(n).label}`,`Objective: ${_1(n.objective)||"Untitled Goal"}`,`Time used: ${P1(n.timeUsedSeconds)}`,`${Jr(n.tokensUsed)} tokens \xB7 ${Jr(n.turnsUsed)} turns`],t=gI(n.lastVerification);return t&&e.push(t),e.push(mI(n.status)),e.join(`
|
|
@@ -27,4 +27,4 @@ Expecting one of '${n.join("', '")}'`);let i=`${e}Help`;return this.on(i,r=>{let
|
|
|
27
27
|
`),i="natural"},runPlugin:async(s,l)=>{let a=o.runPlugin??wt;e.stdout.write(`${await a(s,w,l)}
|
|
28
28
|
`),i="natural"}}).parseAsync(e.argv,{from:"node"}),i){let s=typeof e.exitCode=="number"?e.exitCode:0;await Promise.all([Re(e.stdout,o.outputDrainTimeoutMs??Me),Re(e.stderr,o.outputDrainTimeoutMs??Me)]),(o.platform??process.platform)==="win32"&&i==="natural"?e.exitCode=s:e.exit(s)}}catch(r){e.stderr.write(`${await ct(r)}
|
|
29
29
|
`),e.exitCode=1}}async function ct(o){let e=ie(o);if(!/better[-_]sqlite3/iu.test(e)||!/Could not locate the bindings file|Cannot find (?:module|package)|NODE_MODULE_VERSION|Module did not self-register/iu.test(e))return e;let{buildMcodePackageManagerCommand:t}=await import("./install-source-GWYHWTTG.js");return["MCode could not load its native SQLite dependency.","If npm reported blocked install scripts, the installation needs explicit script approval.","Reinstall with the original installer. For npm installations, run:",` ${t("npm-global",w).display} --foreground-scripts`,"",`Original error: ${e}`].join(`
|
|
30
|
-
`)}function Re(o,e){return o.destroyed||o.writableEnded?Promise.resolve():new Promise(t=>{let n=!1,i,r=()=>s(!0),s=(l=!1)=>{n||(n=!0,i&&clearTimeout(i),l||o.off?.("error",r),t())};i=setTimeout(s,e),i.unref?.(),o.once?.("error",r);try{o.write("",l=>s(!!l))}catch{s()}})}async function dt(o){let{launchTui:e}=await import("./launcher-
|
|
30
|
+
`)}function Re(o,e){return o.destroyed||o.writableEnded?Promise.resolve():new Promise(t=>{let n=!1,i,r=()=>s(!0),s=(l=!1)=>{n||(n=!0,i&&clearTimeout(i),l||o.off?.("error",r),t())};i=setTimeout(s,e),i.unref?.(),o.once?.("error",r);try{o.write("",l=>s(!!l))}catch{s()}})}async function dt(o){let{launchTui:e}=await import("./launcher-TAS3WAUC.js");await e(o)}async function ht(o,e,t){let{runTuiExecCommand:n}=await import("./run-exec-command-BQ2G5OY7.js");await n(o,e,t)}async function pt(o,e){let{runTuiAcpCommand:t}=await import("./run-acp-command-2SHKZJNF.js");await t(o,{},e)}async function mt(o,e=!0,t){let{runTuiLogin:n}=await import("./auth-command-T5DRRUNT.js");return n({region:o,openBrowser:e,lane:t})}async function ft(o){let{runTuiLogout:e}=await import("./auth-command-T5DRRUNT.js");return e({region:o})}async function gt(o){let{runMcodeUpdate:e}=await import("./update-CG3K6TMW.js");await e(o)}async function _t(o,e,t){let{runMcodeProviderCommand:n}=await import("./provider-command-TITVCVLJ.js");return n({request:o,version:e,lane:t})}async function wt(o,e,t){let{runMcodePluginCommand:n}=await import("./plugin-command-XCLCU4X3.js");return n({request:o,version:e,lane:t})}export{Re as drainTuiOutput,Xt as runTuiCli};
|
package/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __mavis_cR } from "module"; import { basename as __mavis_basename, dirname as __mavis_dirname, join as __mavis_join } from "path"; import { fileURLToPath as __mavis_fileURLToPath, pathToFileURL as __mavis_pathToFileURL } from "url"; const __mavis_tuiCurrentModuleDir = __mavis_dirname(__mavis_fileURLToPath(import.meta.url)); const __mavis_tuiPackageRoot = __mavis_basename(__mavis_tuiCurrentModuleDir) === "chunks" ? __mavis_dirname(__mavis_tuiCurrentModuleDir) : __mavis_tuiCurrentModuleDir; const __mavis_tuiPackageEntryUrl = __mavis_pathToFileURL(__mavis_join(__mavis_tuiPackageRoot, "cli.js")).href; const require = __mavis_cR(__mavis_tuiPackageEntryUrl); const __dirname = __mavis_tuiPackageRoot;
|
|
3
3
|
import{f as s}from"./chunks/chunk-ZCP4JGO4.js";import{u as n,v as a}from"./chunks/chunk-VCJI7AJO.js";import"./chunks/chunk-O6RIRKRN.js";import"./chunks/chunk-HQ2U4QVQ.js";import{n as o,p as i}from"./chunks/chunk-WAVNKSSE.js";import"./chunks/chunk-DV5WIEGS.js";import"./chunks/chunk-ZITT4GJK.js";import"./chunks/chunk-2ZG44JU6.js";import"./chunks/chunk-Z44TXDGK.js";import"./chunks/chunk-CWWDVX6C.js";import"./chunks/chunk-D76SO2ME.js";import{fileURLToPath as u}from"node:url";async function l(){let c=n(u(__mavis_tuiPackageEntryUrl)),t=a(c),r;try{r=i(process.argv.slice(2),t)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}
|
|
4
|
-
`),process.exitCode=1;return}let{getTuiDataDirPath:m}=await import("./chunks/data-dir-YVQZ5MXP.js");o({dataDir:m(),...r?{startupBuildEnvironment:r}:{}});let p=await s();try{let{runTuiCli:e}=await import("./chunks/main-
|
|
4
|
+
`),process.exitCode=1;return}let{getTuiDataDirPath:m}=await import("./chunks/data-dir-YVQZ5MXP.js");o({dataDir:m(),...r?{startupBuildEnvironment:r}:{}});let p=await s();try{let{runTuiCli:e}=await import("./chunks/main-6DJBGFQV.js");await e({allowStartupEnvironmentSelection:t})}finally{p.remove()}}await l();
|