@x-otto/tui 0.0.1-alpha.3 → 0.0.1-alpha.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{Tabable-DDNOHe29.d.ts → Tabable-mihaW36p.d.ts} +21 -2
- package/dist/{Tabable-DDNOHe29.d.ts.map → Tabable-mihaW36p.d.ts.map} +1 -1
- package/dist/WizardDialog-sc1iSYHB.js +10 -0
- package/dist/WizardDialog-sc1iSYHB.js.map +1 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/standalone.d.ts +1 -1
- package/dist/standalone.js +1 -1
- package/package.json +2 -2
- package/dist/WizardDialog-CaEQFFUA.js +0 -10
- package/dist/WizardDialog-CaEQFFUA.js.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Command, CommandContext, CommandRegistry, CommandResult, RenderOptions, createBuiltinCommands, showCommandPalette } from "./compat.js";
|
|
2
|
-
import { $ as ExtensionMenuContribution, $n as ToolMessage, $t as subagentEntryStatus, A as RemoteSessionSnapshot, An as ThemeRegistry, At as SigilPrefix, B as createSelectState, Bn as THEME, Bt as navigateSuggestions, C as TuiHandle, Cn as Risk, Ct as formatProviderUsageLimitTypeFull, Dn as ThemePresetInput, Dt as SubmitMode, E as TuiStreamEvent, En as ThemePreset, Et as PromptInput, F as MessageStore, Fn as PANEL_BORDER, Ft as TypeaheadState, G as MemoryDialog, Gn as MessageContent, Gt as PasteStoreResidencySource, H as NotifyScheduler, Hn as A2uiContent, Ht as PasteSnapshot, In as FIGURES, It as applySlashCompletion, J as MemoryEntrySource, Jn as StreamEvent, Jt as ObservationLike, K as MemoryDialogProps, Kn as PulseSurveyItem, Kt as createPasteStore, L as SelectOption, Ln as FiguresMap, Lt as createCommandRegistry, M as SessionDataTarget, Mn as LAYOUT, Mt as CommandEntry, N as SessionTransport, Nn as SPACING, Nt as CommandRegistry$1, O as AttachDataSourceDeps, On as ThemePresetSelection, Ot as SigilEntry, P as createAttachSessionDataSource, Pn as DIALOG_BORDER, Pt as SlashNavigateAction, Q as ExtensionListEntry, Qn as ToolCompletionMessage, Qt as observationRow, R as SelectOptions, Rn as PALETTE, Rt as extractSlashPrefix, S as SubagentContext, Sn as LangMode, St as ProviderUsageBadgeItem, T as TuiPanelRegistration, Tn as ThemeAppearance, Tt as QueuedCommands, U as NotifyStats, Un as AssistantMessage, Ut as PasteSnapshotEntry, V as A2uiButtonInfo, Vn as ThemeColors, Vt as CreatePasteStoreOptions, W as makeNotifyScheduler, Wn as ChatMessage, Wt as PasteStore, Xn as ThinkingContent, Xt as formatTurnTimeline, Yn as TextContent, Yt as formatAgentDiagnosticsText, Zn as ToolCall, Zt as observationLiveFields, _ as ModalRequestInput, _n as detectLanguage, _t as createBudgetStore, an as RateLimitType, at as ButtonProps, b as PluginRegistration, bn as t, bt as HomeProps, c as TabableRegistry, cn as KeyBindingPredicate, ct as RegisteredRenderer, dn as DataListProps, dt as NotificationStore, en as subagentRestoreFields, er as UserMessage, et as ExtensionsListRequest, f as ConfirmDialog, fn as DataListRow, ft as ProxyStore, g as DraftItemView, gn as useAppState, gt as BudgetView, h as ConfirmRequest, hn as Store, ht as BudgetStore, i as Tabable, in as ErrorRetryItem, it as ButtonColor, j as SessionDataSource, jn as createBuiltinThemeRegistry, jt as SigilSearchRegistry, k as RemoteSessionEvent, kn as ThemePresetSource, kt as SigilKind, l as UseTabableOptions, ln as DataList, lt as clearPluginRenderers, m as AlertRequest, mn as PerfStore, mt as BudgetState, nn as ErrorRetryAction, nt as ExtensionDetailRequest, on as ContextStore, ot as ButtonVariant, p as ConfirmDialogProps, pn as DataListTone, pt as CacheStore, q as MemoryEntry, qn as StopReason, qt as Completer, rn as ErrorRetryActionKind, rt as Button, s as TabableProps, sn as OnboardingResult, st as PluginMessageRenderer, t as FocusStyle, tn as EditedFileEntry, tt as ExtensionDetailAction, u as useTabable, un as DataListEntry, ut as registerPluginRenderers, v as ModalRequestVoid, vn as i18next, vt as TaskStore, w as TuiOptions, wn as MarkdownThemeOverrides, wt as isUsingOverage, x as PromptRequest, xn as Lang, xt as SessionListItem, y as PermissionDecision, yn as initI18n, yt as Home, z as SelectState, zn as STATUS, zt as getCommandSuggestions } from "./Tabable-
|
|
2
|
+
import { $ as ExtensionMenuContribution, $n as ToolMessage, $t as subagentEntryStatus, A as RemoteSessionSnapshot, An as ThemeRegistry, At as SigilPrefix, B as createSelectState, Bn as THEME, Bt as navigateSuggestions, C as TuiHandle, Cn as Risk, Ct as formatProviderUsageLimitTypeFull, Dn as ThemePresetInput, Dt as SubmitMode, E as TuiStreamEvent, En as ThemePreset, Et as PromptInput, F as MessageStore, Fn as PANEL_BORDER, Ft as TypeaheadState, G as MemoryDialog, Gn as MessageContent, Gt as PasteStoreResidencySource, H as NotifyScheduler, Hn as A2uiContent, Ht as PasteSnapshot, In as FIGURES, It as applySlashCompletion, J as MemoryEntrySource, Jn as StreamEvent, Jt as ObservationLike, K as MemoryDialogProps, Kn as PulseSurveyItem, Kt as createPasteStore, L as SelectOption, Ln as FiguresMap, Lt as createCommandRegistry, M as SessionDataTarget, Mn as LAYOUT, Mt as CommandEntry, N as SessionTransport, Nn as SPACING, Nt as CommandRegistry$1, O as AttachDataSourceDeps, On as ThemePresetSelection, Ot as SigilEntry, P as createAttachSessionDataSource, Pn as DIALOG_BORDER, Pt as SlashNavigateAction, Q as ExtensionListEntry, Qn as ToolCompletionMessage, Qt as observationRow, R as SelectOptions, Rn as PALETTE, Rt as extractSlashPrefix, S as SubagentContext, Sn as LangMode, St as ProviderUsageBadgeItem, T as TuiPanelRegistration, Tn as ThemeAppearance, Tt as QueuedCommands, U as NotifyStats, Un as AssistantMessage, Ut as PasteSnapshotEntry, V as A2uiButtonInfo, Vn as ThemeColors, Vt as CreatePasteStoreOptions, W as makeNotifyScheduler, Wn as ChatMessage, Wt as PasteStore, Xn as ThinkingContent, Xt as formatTurnTimeline, Yn as TextContent, Yt as formatAgentDiagnosticsText, Zn as ToolCall, Zt as observationLiveFields, _ as ModalRequestInput, _n as detectLanguage, _t as createBudgetStore, an as RateLimitType, at as ButtonProps, b as PluginRegistration, bn as t, bt as HomeProps, c as TabableRegistry, cn as KeyBindingPredicate, ct as RegisteredRenderer, dn as DataListProps, dt as NotificationStore, en as subagentRestoreFields, er as UserMessage, et as ExtensionsListRequest, f as ConfirmDialog, fn as DataListRow, ft as ProxyStore, g as DraftItemView, gn as useAppState, gt as BudgetView, h as ConfirmRequest, hn as Store, ht as BudgetStore, i as Tabable, in as ErrorRetryItem, it as ButtonColor, j as SessionDataSource, jn as createBuiltinThemeRegistry, jt as SigilSearchRegistry, k as RemoteSessionEvent, kn as ThemePresetSource, kt as SigilKind, l as UseTabableOptions, ln as DataList, lt as clearPluginRenderers, m as AlertRequest, mn as PerfStore, mt as BudgetState, nn as ErrorRetryAction, nt as ExtensionDetailRequest, on as ContextStore, ot as ButtonVariant, p as ConfirmDialogProps, pn as DataListTone, pt as CacheStore, q as MemoryEntry, qn as StopReason, qt as Completer, rn as ErrorRetryActionKind, rt as Button, s as TabableProps, sn as OnboardingResult, st as PluginMessageRenderer, t as FocusStyle, tn as EditedFileEntry, tt as ExtensionDetailAction, u as useTabable, un as DataListEntry, ut as registerPluginRenderers, v as ModalRequestVoid, vn as i18next, vt as TaskStore, w as TuiOptions, wn as MarkdownThemeOverrides, wt as isUsingOverage, x as PromptRequest, xn as Lang, xt as SessionListItem, y as PermissionDecision, yn as initI18n, yt as Home, z as SelectState, zn as STATUS, zt as getCommandSuggestions } from "./Tabable-mihaW36p.js";
|
|
3
3
|
import React from "react";
|
|
4
4
|
import { DOMElement, Key } from "ink";
|
|
5
5
|
import { FuzzySearchOptions, HighlightRange, RankedMatch, SearchableItem, SubsequenceResult, matchSubsequence, positionsToHighlightRanges, rankCandidates, rankLabeledItems, rankNamedItems, scoreSubsequence } from "@x-otto/shared";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as l,E as u,Et as d,F as f,Ft as p,G as m,Gt as h,H as g,Ht as _,I as v,It as y,J as b,Jt as x,K as S,Kt as C,L as w,Lt as T,M as E,Mt as ee,N as D,O as te,Ot as ne,P as O,Pt as k,Q as re,Qt as A,R as ie,Rt as j,S as ae,St as oe,T as M,Tt as se,U as ce,Ut as N,V as le,Vt as ue,W as P,Wt as F,X as de,Xt as fe,Y as pe,Yt as me,Z as he,Zt as ge,_ as _e,a as ve,an as ye,at as be,b as xe,c as Se,cn as Ce,ct as we,d as I,dn as Te,dt as Ee,en as De,et as Oe,f as ke,fn as Ae,ft as je,g as Me,gn as Ne,gt as Pe,h as Fe,hn as Ie,ht as Le,i as Re,in as ze,it as Be,j as Ve,jt as He,k as Ue,kt as We,l as Ge,ln as Ke,lt as qe,m as Je,mn as L,mt as Ye,n as Xe,nn as R,nt as Ze,o as Qe,on as $e,ot as et,p as tt,pn as nt,pt as rt,q as it,qt as at,r as ot,rn as st,rt as ct,s as lt,sn as ut,st as dt,t as ft,tn as pt,tt as mt,u as z,un as ht,ut as gt,v as _t,vt,w as yt,wt as bt,x as xt,y as St,zt as Ct}from"./WizardDialog-CaEQFFUA.js";import{i as wt,n as B,r as Tt,t as Et}from"./i18n-Dju4J1Q-.js";import{CommandRegistry as Dt,createBuiltinCommands as Ot,showCommandPalette as kt}from"./compat.js";import{createRequire as At}from"node:module";import jt from"wrap-ansi";import V,{createContext as Mt,createElement as H,useCallback as Nt,useContext as Pt,useEffect as U,useMemo as W,useRef as G,useState as K}from"react";import{Fragment as Ft,jsx as q,jsxs as J}from"react/jsx-runtime";import*as It from"ink";import{Box as Y,Static as Lt,Text as X,render as Rt,useBoxMetrics as zt,useInput as Bt,usePaste as Vt,useStdin as Ht,useStdout as Ut}from"ink";import{I18nextProvider as Wt}from"react-i18next";import{createStore as Gt}from"zustand/vanilla";import{useStore as Kt}from"zustand";import{LARGE_FILE_BYTE_THRESHOLD as qt,matchSubsequence as Jt,matchesGlobPattern as Yt,positionsToHighlightRanges as Xt,rankCandidates as Zt,rankLabeledItems as Qt,rankNamedItems as $t,readFileCapped as en,scoreSubsequence as tn}from"@x-otto/shared";import{readdirSync as nn,statSync as rn}from"node:fs";import{adjustDismissedSigil as an,applySigilCompletion as on,applySigilReplacement as sn,evaluateSigilTrigger as cn,extractSigilPrefix as ln}from"@x-otto/interchange";import{basename as un,dirname as dn,join as fn,resolve as pn}from"node:path";import{execSync as mn,spawn as hn}from"node:child_process";import gn from"chalk";import{DEFAULT_DELEGATION_TOOLS as _n,SESSION_MAX_PER_SESSION_BYTES as vn,SESSION_RESUME_WINDOW_MESSAGES as yn}from"@x-otto/session-contract";import{marked as bn}from"marked";import{PassThrough as xn}from"node:stream";const Sn=[`trust`,`readonly`,`exit`];function Cn({root:e,onChoice:t}){let n=[{key:`trust`,label:B.t(`trust.optTrust`),color:L.success},{key:`readonly`,label:B.t(`trust.optReadonly`),color:L.accent},{key:`exit`,label:B.t(`trust.optExit`),color:L.inactive}];return J(T,{header:q(y,{color:L.warning,children:B.t(`trust.title`)}),footer:q(k,{items:[[`${j.up}${j.down}`,B.t(`hint.select`)],[`1/2/3`,B.t(`hint.quick`)],[j.enter,B.t(`hint.confirm`)],[j.esc,B.t(`hint.exit`)]]}),children:[q(Y,{marginTop:A.tight,children:q(X,{wrap:`truncate-end`,children:B.t(`trust.body`,{path:e})})}),q(Y,{marginTop:A.tight,children:q(Pe.Root,{id:`trust-prompt-dialog`,onPick:e=>t(Sn[e]??`exit`),escapeIndex:Sn.indexOf(`exit`),children:n.map(e=>q(Pe.Item,{label:e.label,color:e.color},e.key))})})]})}function wn(e){return Tt(e.language===`zh`?`zh`:e.language===`en`?`en`:Et()),new Promise(t=>{let n=!1,r=Rt(V.createElement(Cn,{root:e.root,onChoice:e=>{n||(n=!0,r.clear(),r.unmount(),N(),t(e))}}),{exitOnCtrlC:!1})})}const Tn=[`use_parent`,`create_new`,`exit`];function En({parentRoot:e,currentRoot:t,onChoice:n}){let r=[{key:`use_parent`,label:B.t(`parent.optUseParent`),color:L.success},{key:`create_new`,label:B.t(`parent.optCreateNew`),color:L.accent},{key:`exit`,label:B.t(`parent.optExit`),color:L.inactive}];return J(T,{header:q(y,{color:L.warning,children:B.t(`parent.title`)}),footer:q(k,{items:[[`${j.up}${j.down}`,B.t(`hint.select`)],[`1/2/3`,B.t(`hint.quick`)],[j.enter,B.t(`hint.confirm`)],[j.esc,B.t(`hint.exit`)]]}),children:[q(Y,{marginTop:A.tight,children:q(X,{wrap:`truncate-end`,children:B.t(`parent.body`,{parentRoot:e,currentRoot:t})})}),q(Y,{marginTop:A.tight,children:q(Pe.Root,{id:`parent-workspace-dialog`,onPick:e=>n(Tn[e]??`exit`),escapeIndex:Tn.indexOf(`exit`),children:r.map(e=>q(Pe.Item,{label:e.label,color:e.color},e.key))})})]})}function Dn(e){return Tt(e.language===`zh`?`zh`:e.language===`en`?`en`:Et()),new Promise(t=>{let n=!1,r=Rt(V.createElement(En,{parentRoot:e.parentRoot,currentRoot:e.currentRoot,onChoice:e=>{n||(n=!0,r.clear(),r.unmount(),N(),t(e))}}),{exitOnCtrlC:!1})})}const On={five_hour:`5h`,seven_day:`7d`,seven_day_opus:`7d-opus`,seven_day_sonnet:`7d-sonnet`,seven_day_overage_included:`7d`},kn={five_hour:`5-hour`,seven_day:`7-day`,seven_day_opus:`7-day (Opus)`,seven_day_sonnet:`7-day (Sonnet)`,seven_day_overage_included:`7-day`};function An(e){return kn[e]??e}function jn(e,t){let n=Math.max(0,Math.round(e-t/1e3)),r=Math.floor(n/3600),i=Math.floor(n%3600/60);return r>0?`${r}h${i>0?`${i}m`:``}`:i>0?`${i}m`:`<1m`}function Mn(e,t){return e===`rejected`&&(t===`allowed`||t===`allowed_warning`)}function Nn(e,t){let n=e.limitType?On[e.limitType]??e.limitType:``,r=e.usedPercent===void 0?``:` ${Math.round(e.usedPercent)}%`,i=!!(n||r);if(Mn(e.status,e.overageStatus)&&e.overageResetsAt!==void 0)return`${n}${r} +${jn(e.overageResetsAt,t)}`.trim();let a=i?` → `:``;return`${n}${r}${e.resetsAt===void 0?``:`${a}${jn(e.resetsAt,t)}`}`.trim()}const Pn={five_hour:300*60,seven_day:10080*60,seven_day_opus:10080*60,seven_day_sonnet:10080*60,seven_day_overage_included:10080*60};function Fn(e,t,n,r){if(!e||t===void 0||n===void 0)return null;let i=Pn[e];if(!i)return null;let a=r/1e3,o=n-i,s=Math.max(0,Math.min(100,Math.round((a-o)/i*100)));return(e===`five_hour`?[[90,72]]:[[75,60],[50,35],[25,15]]).some(([e,n])=>t>=e&&s<=n)?{usedPct:t,timePct:s}:null}function In(e,t,n,r,i,a){return Mn(e,a)||e===`allowed_warning`||e===`allowed`&&i!==void 0&&Fn(t,n,r,i)?`warning`:`inactive`}function Z(e,t){return Kt(e.zustand,t)}function Ln(e){let t=Gt()(()=>e);return{getState:()=>t.getState(),setState:e=>{let n=t.getState(),r=typeof e==`function`?e(n):e,i=!1;for(let e of Object.keys(r))if(!Object.is(n[e],r[e])){i=!0;break}i&&t.setState(r)},subscribe:e=>t.subscribe(()=>e()),zustand:t}}var Rn=class{buffer=``;active=!1;timer=null;timeoutMs;onEmptyPaste;constructor(e={}){this.timeoutMs=e.timeoutMs??100,this.onEmptyPaste=e.onEmptyPaste}get isPasting(){return this.active}get currentBuffer(){return this.active?this.buffer:``}feed(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(`\x1B[200~`,n),i=e.indexOf(`\x1B[201~`,n),a=r>=0&&i>=0&&i<r;if(this.active){if(r>=0&&!a){this.buffer+=e.slice(n,r),this.clearTimer(),t.push(this.flushPasteEnd()),n=r+6,this.active=!0,this.resetTimer(),t.push({type:`paste_start`});continue}if(i>=0){this.buffer+=e.slice(n,i),this.clearTimer(),t.push(this.flushPasteEnd()),n=i+6;continue}this.buffer+=e.slice(n),this.resetTimer();break}if(r>=0){this.active=!0,this.resetTimer(),t.push({type:`paste_start`}),n=r+6;continue}if(i>=0){n=i+6;continue}break}return t}forceEnd(){if(!this.active)return null;this.clearTimer();let e=this.buffer;return this.buffer=``,this.active=!1,{type:`paste_timeout`,partialText:e}}reset(){this.clearTimer(),this.buffer=``,this.active=!1}destroy(){this.reset()}resetTimer(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.forceEnd(),this.timeoutMs)}clearTimer(){this.timer&&=(clearTimeout(this.timer),null)}flushPasteEnd(){let e=this.buffer,t=e.length===0;return this.buffer=``,this.active=!1,t&&this.onEmptyPaste?.(),{type:`paste_end`,text:e,isEmpty:t}}};const zn=/^\x1b\[(\d+)(?:;(\d+))?u$/,Bn=/^\x1b\[27;(\d+);(\d+)~$/,Vn=/^\x1b\[(\d+)~$/;function Hn(e){if(!e.startsWith(`\x1B[`)&&!e.startsWith(`\x1BO`))return null;let t=e.match(zn);if(t){let n=parseInt(t[1],10),r=t[2]?parseInt(t[2],10):1,i=r>0?r-1:0;return{name:Un(n),ctrl:!!(i&4),alt:!!(i&2),shift:!!(i&1),meta:!!(i&8),sequence:e}}let n=e.match(Bn);if(n){let t=parseInt(n[1],10),r=parseInt(n[2],10),i=!!(t&8);return{name:Un(r),ctrl:!!(t&4),alt:i,shift:!!(t&2),meta:i,sequence:e}}if(e.startsWith(`\x1BO`)){let t=e[2],n={A:`up`,B:`down`,C:`right`,D:`left`,H:`home`,F:`end`,P:`f1`,Q:`f2`,R:`f3`,S:`f4`};return t&&t in n?{name:n[t],shift:!1,alt:!1,ctrl:!1,meta:!1,sequence:e}:null}let r=e.match(/^\x1b\[(?:\d+;)?(\d+)?([ABCD])$/);if(r){let t={A:`up`,B:`down`,C:`right`,D:`left`},n=r[1]?parseInt(r[1],10):1;return{name:t[r[2]],ctrl:!!(n&4),alt:!!(n&8),shift:!!(n&2),meta:!!(n&8),sequence:e}}let i=e.match(Vn);return i?{name:Wn(parseInt(i[1],10)),shift:!1,alt:!1,ctrl:!1,meta:!1,sequence:e}:null}function Un(e){return e>=97&&e<=122?String.fromCharCode(e):e>=65&&e<=90?String.fromCharCode(e+32):e===13?`return`:e===9?`tab`:e===27?`escape`:e===32?`space`:e===127||e===8?`backspace`:String.fromCharCode(e)}function Wn(e){switch(e){case 1:case 7:return`home`;case 2:return`insert`;case 3:return`delete`;case 4:case 8:return`end`;case 5:return`pageup`;case 6:return`pagedown`;case 11:return`f1`;case 12:return`f2`;case 13:return`f3`;case 14:return`f4`;case 15:return`f5`;case 17:return`f6`;case 18:return`f7`;case 19:return`f8`;case 20:return`f9`;case 21:return`f10`;case 23:return`f11`;case 24:return`f12`;default:return`f${e}`}}function Gn(e){if(!process.stdout.isTTY)return;let t=Kn(e);t&&process.stdout.write(`\x1b]0;${t}\x07`)}function Kn(e){let t=e.replace(/[\x00-\x1f\x7f-\x9f]/g,``).replace(/[\u200b\u200c\u200e\u200f\u202a-\u202e\u2060-\u206f\ufeff]/g,``).replace(/\s+/g,` `).trim();return t.length>240?t.slice(0,240):t}function qn(e,t,n){return t?`\x1b]8;${n?`id=${encodeURIComponent(n)}`:``};${encodeURIComponent(t)}\x1b\\${e}\x1b]8;;\x1b\\`:e}function Jn(e,t,n,r){let i=t.startsWith(`file://`)?t:`file://${t}`;return n!==void 0&&(i+=`#L${n}`),r!==void 0&&(i+=`:${r}`),qn(e,i)}function Yn(e,t=`c`){let n=Buffer.from(e,`utf-8`).toString(`base64`);process.stdout.write(`\x1b]52;${t};${n}\x07`)}function Xn(e=`c`){return`\x1b]52;${e};?\x07`}function Zn(){process.stdout.write(`\x1BP=1s\x1B\\`)}function Qn(){process.stdout.write(`\x1BP=2s\x1B\\`)}function $n(e){Zn();try{return e()}finally{Qn()}}const er=RegExp(`\x1B\\[\\?2026[hl]`,`g`);function tr(e){return e.includes(`\x1B[?2026`)?e.replace(er,``):e}function nr(e){return new Proxy(e,{get(e,t){if(t===`write`)return(t,...n)=>e.write(typeof t==`string`?tr(t):t,...n);let n=Reflect.get(e,t);return typeof n==`function`?n.bind(e):n}})}function rr(e=process.env){return!!e.TMUX&&e.OTTO_TUI_SYNC!==`1`}const ir=RegExp(`\x1B\\[3J`,`g`);function ar(e){return e.includes(`\x1B[3J`)?e.replace(ir,``):e}function or(e){return new Proxy(e,{get(e,t){if(t===`write`)return(t,...n)=>e.write(typeof t==`string`?ar(t):t,...n);let n=Reflect.get(e,t);return typeof n==`function`?n.bind(e):n}})}function sr(e=50){let t=[],n=0;return{snapshot(r){let i=Date.now();if(i-n<1e3)return;n=i;let a=t[t.length-1];a&&a.text===r.text&&a.offset===r.offset||(t.push({text:r.text,offset:r.offset,timestamp:i}),t.length>e&&t.splice(0,t.length-e))},undo(){return t.length===0?null:(n=0,t.pop())},get depth(){return t.length},reset(){t.length=0,n=0}}}function cr(e,t){if(!e)return[];let n=[];for(let r=t.length-1;r>=0;r--){let i=t[r],a=Jt(e,i);a&&n.push({entry:i,index:r,score:a.score,highlightRanges:Xt(a.positions)})}return n.sort((e,t)=>t.score-e.score||t.index-e.index),n.map(({entry:e,highlightRanges:t})=>{let n=t[0],r=t.at(-1);return{entry:e,matchStart:n?.start??0,matchEnd:r?.end??0,highlightRanges:t}})}function lr(e={}){let t=e.maxSize??100,n=e.initialEntries?[...e.initialEntries]:[];n.length>t&&n.splice(0,n.length-t);let r=-1,i=``,a=!1,o=[],s=``;return{push(e){e.length!==0&&(n.length>0&&n[n.length-1]===e||(n.push(e),n.length>t&&n.shift()))},navigateUp(e){return n.length===0?null:r===-1?(i=e,r=n.length-1,n[r]):r<=0?null:(r--,n[r])},navigateDown(){return r===-1?null:(r++,r>=n.length?(r=-1,i):n[r])},resetNavigation(){r=-1,i=``},beginSearch(e){s=e,a=!0,o=[],r===-1&&(i=e)},search(e){return!a||!e?[]:(o=cr(e,n),o)},acceptSearch(e){if(e<0||e>=o.length)return null;let t=o[e].entry;return a=!1,r=n.indexOf(t),t},cancelSearch(){return a=!1,o=[],s},get size(){return n.length},get navState(){return r===-1?null:{position:n.length-r,total:n.length}},getAll(){return n},clear(){n.length=0,r=-1,i=``,a=!1,o=[]}}}function ur(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}const dr=ur(`OTTO_PASTE_STORE_MAX_ENTRIES`,64),fr=ur(`OTTO_PASTE_STORE_MAX_BYTES`,33554432),pr=ur(`OTTO_PASTE_STORE_PERSIST_MAX_BYTES`,8388608),mr={healthy:1,warning:2,critical:4},hr=/\[@paste:#(\d+)(?:\s+\+(\d+)\s+lines)?\]/g;function gr(e){let t=[];hr.lastIndex=0;let n;for(;(n=hr.exec(e))!==null;)t.push({start:n.index,end:n.index+n[0].length,id:Number.parseInt(n[1],10)});return t}function _r(e){return Buffer.byteLength(e,`utf-8`)}function vr(e){if(!(typeof e!=`number`||!Number.isFinite(e)))return Math.floor(e)}function yr(e={}){let{residencyGovernor:t}=e,n=new Map,r=1,i=0,a=0;function o(){return t?.currentLevel??`healthy`}function s(){return Math.max(1,Math.floor(dr/mr[o()]))}function c(){return Math.max(1,Math.floor(fr/mr[o()]))}function l(e){let t=s(),r=c();for(;n.size>0&&(n.size>=t||i+e>r);){let e=n.keys().next().value;if(e===void 0)break;let t=n.get(e);t&&(i-=t.byteLength),n.delete(e),a++}}return{foldIfLarge(e){let t=e.split(`
|
|
1
|
+
import{$ as e,$t as t,A as n,At as r,B as i,Bt as a,C as o,Ct as s,D as c,Dt as l,E as u,Et as d,F as f,Ft as p,G as m,Gt as h,H as g,Ht as _,I as v,It as y,J as b,Jt as x,K as S,Kt as C,L as w,Lt as T,M as E,Mt as ee,N as D,O as te,Ot as ne,P as O,Pt as k,Q as re,Qt as A,R as ie,Rt as j,S as ae,St as oe,T as M,Tt as se,U as ce,Ut as N,V as le,Vt as ue,W as P,Wt as F,X as de,Xt as fe,Y as pe,Yt as me,Z as he,Zt as ge,_ as _e,a as ve,an as ye,at as be,b as xe,c as Se,cn as Ce,ct as we,d as I,dn as Te,dt as Ee,en as De,et as Oe,f as ke,fn as Ae,ft as je,g as Me,gn as Ne,gt as Pe,h as Fe,hn as Ie,ht as Le,i as Re,in as ze,it as Be,j as Ve,jt as He,k as Ue,kt as We,l as Ge,ln as Ke,lt as qe,m as Je,mn as L,mt as Ye,n as Xe,nn as R,nt as Ze,o as Qe,on as $e,ot as et,p as tt,pn as nt,pt as rt,q as it,qt as at,r as ot,rn as st,rt as ct,s as lt,sn as ut,st as dt,t as ft,tn as pt,tt as mt,u as z,un as ht,ut as gt,v as _t,vt,w as yt,wt as bt,x as xt,y as St,zt as Ct}from"./WizardDialog-sc1iSYHB.js";import{i as wt,n as B,r as Tt,t as Et}from"./i18n-Dju4J1Q-.js";import{CommandRegistry as Dt,createBuiltinCommands as Ot,showCommandPalette as kt}from"./compat.js";import{createRequire as At}from"node:module";import jt from"wrap-ansi";import V,{createContext as Mt,createElement as H,useCallback as Nt,useContext as Pt,useEffect as U,useMemo as W,useRef as G,useState as K}from"react";import{Fragment as Ft,jsx as q,jsxs as J}from"react/jsx-runtime";import*as It from"ink";import{Box as Y,Static as Lt,Text as X,render as Rt,useBoxMetrics as zt,useInput as Bt,usePaste as Vt,useStdin as Ht,useStdout as Ut}from"ink";import{I18nextProvider as Wt}from"react-i18next";import{createStore as Gt}from"zustand/vanilla";import{useStore as Kt}from"zustand";import{LARGE_FILE_BYTE_THRESHOLD as qt,matchSubsequence as Jt,matchesGlobPattern as Yt,positionsToHighlightRanges as Xt,rankCandidates as Zt,rankLabeledItems as Qt,rankNamedItems as $t,readFileCapped as en,scoreSubsequence as tn}from"@x-otto/shared";import{readdirSync as nn,statSync as rn}from"node:fs";import{adjustDismissedSigil as an,applySigilCompletion as on,applySigilReplacement as sn,evaluateSigilTrigger as cn,extractSigilPrefix as ln}from"@x-otto/interchange";import{basename as un,dirname as dn,join as fn,resolve as pn}from"node:path";import{execSync as mn,spawn as hn}from"node:child_process";import gn from"chalk";import{DEFAULT_DELEGATION_TOOLS as _n,SESSION_MAX_PER_SESSION_BYTES as vn,SESSION_RESUME_WINDOW_MESSAGES as yn}from"@x-otto/session-contract";import{marked as bn}from"marked";import{PassThrough as xn}from"node:stream";const Sn=[`trust`,`readonly`,`exit`];function Cn({root:e,onChoice:t}){let n=[{key:`trust`,label:B.t(`trust.optTrust`),color:L.success},{key:`readonly`,label:B.t(`trust.optReadonly`),color:L.accent},{key:`exit`,label:B.t(`trust.optExit`),color:L.inactive}];return J(T,{header:q(y,{color:L.warning,children:B.t(`trust.title`)}),footer:q(k,{items:[[`${j.up}${j.down}`,B.t(`hint.select`)],[`1/2/3`,B.t(`hint.quick`)],[j.enter,B.t(`hint.confirm`)],[j.esc,B.t(`hint.exit`)]]}),children:[q(Y,{marginTop:A.tight,children:q(X,{wrap:`truncate-end`,children:B.t(`trust.body`,{path:e})})}),q(Y,{marginTop:A.tight,children:q(Pe.Root,{id:`trust-prompt-dialog`,onPick:e=>t(Sn[e]??`exit`),escapeIndex:Sn.indexOf(`exit`),children:n.map(e=>q(Pe.Item,{label:e.label,color:e.color},e.key))})})]})}function wn(e){return Tt(e.language===`zh`?`zh`:e.language===`en`?`en`:Et()),new Promise(t=>{let n=!1,r=Rt(V.createElement(Cn,{root:e.root,onChoice:e=>{n||(n=!0,r.clear(),r.unmount(),N(),t(e))}}),{exitOnCtrlC:!1})})}const Tn=[`use_parent`,`create_new`,`exit`];function En({parentRoot:e,currentRoot:t,onChoice:n}){let r=[{key:`use_parent`,label:B.t(`parent.optUseParent`),color:L.success},{key:`create_new`,label:B.t(`parent.optCreateNew`),color:L.accent},{key:`exit`,label:B.t(`parent.optExit`),color:L.inactive}];return J(T,{header:q(y,{color:L.warning,children:B.t(`parent.title`)}),footer:q(k,{items:[[`${j.up}${j.down}`,B.t(`hint.select`)],[`1/2/3`,B.t(`hint.quick`)],[j.enter,B.t(`hint.confirm`)],[j.esc,B.t(`hint.exit`)]]}),children:[q(Y,{marginTop:A.tight,children:q(X,{wrap:`truncate-end`,children:B.t(`parent.body`,{parentRoot:e,currentRoot:t})})}),q(Y,{marginTop:A.tight,children:q(Pe.Root,{id:`parent-workspace-dialog`,onPick:e=>n(Tn[e]??`exit`),escapeIndex:Tn.indexOf(`exit`),children:r.map(e=>q(Pe.Item,{label:e.label,color:e.color},e.key))})})]})}function Dn(e){return Tt(e.language===`zh`?`zh`:e.language===`en`?`en`:Et()),new Promise(t=>{let n=!1,r=Rt(V.createElement(En,{parentRoot:e.parentRoot,currentRoot:e.currentRoot,onChoice:e=>{n||(n=!0,r.clear(),r.unmount(),N(),t(e))}}),{exitOnCtrlC:!1})})}const On={five_hour:`5h`,seven_day:`7d`,seven_day_opus:`7d-opus`,seven_day_sonnet:`7d-sonnet`,seven_day_overage_included:`7d`},kn={five_hour:`5-hour`,seven_day:`7-day`,seven_day_opus:`7-day (Opus)`,seven_day_sonnet:`7-day (Sonnet)`,seven_day_overage_included:`7-day`};function An(e){return kn[e]??e}function jn(e,t){let n=Math.max(0,Math.round(e-t/1e3)),r=Math.floor(n/3600),i=Math.floor(n%3600/60);return r>0?`${r}h${i>0?`${i}m`:``}`:i>0?`${i}m`:`<1m`}function Mn(e,t){return e===`rejected`&&(t===`allowed`||t===`allowed_warning`)}function Nn(e,t){let n=e.limitType?On[e.limitType]??e.limitType:``,r=e.usedPercent===void 0?``:` ${Math.round(e.usedPercent)}%`,i=!!(n||r);if(Mn(e.status,e.overageStatus)&&e.overageResetsAt!==void 0)return`${n}${r} +${jn(e.overageResetsAt,t)}`.trim();let a=i?` → `:``;return`${n}${r}${e.resetsAt===void 0?``:`${a}${jn(e.resetsAt,t)}`}`.trim()}const Pn={five_hour:300*60,seven_day:10080*60,seven_day_opus:10080*60,seven_day_sonnet:10080*60,seven_day_overage_included:10080*60};function Fn(e,t,n,r){if(!e||t===void 0||n===void 0)return null;let i=Pn[e];if(!i)return null;let a=r/1e3,o=n-i,s=Math.max(0,Math.min(100,Math.round((a-o)/i*100)));return(e===`five_hour`?[[90,72]]:[[75,60],[50,35],[25,15]]).some(([e,n])=>t>=e&&s<=n)?{usedPct:t,timePct:s}:null}function In(e,t,n,r,i,a){return Mn(e,a)||e===`allowed_warning`||e===`allowed`&&i!==void 0&&Fn(t,n,r,i)?`warning`:`inactive`}function Z(e,t){return Kt(e.zustand,t)}function Ln(e){let t=Gt()(()=>e);return{getState:()=>t.getState(),setState:e=>{let n=t.getState(),r=typeof e==`function`?e(n):e,i=!1;for(let e of Object.keys(r))if(!Object.is(n[e],r[e])){i=!0;break}i&&t.setState(r)},subscribe:e=>t.subscribe(()=>e()),zustand:t}}var Rn=class{buffer=``;active=!1;timer=null;timeoutMs;onEmptyPaste;constructor(e={}){this.timeoutMs=e.timeoutMs??100,this.onEmptyPaste=e.onEmptyPaste}get isPasting(){return this.active}get currentBuffer(){return this.active?this.buffer:``}feed(e){let t=[],n=0;for(;n<e.length;){let r=e.indexOf(`\x1B[200~`,n),i=e.indexOf(`\x1B[201~`,n),a=r>=0&&i>=0&&i<r;if(this.active){if(r>=0&&!a){this.buffer+=e.slice(n,r),this.clearTimer(),t.push(this.flushPasteEnd()),n=r+6,this.active=!0,this.resetTimer(),t.push({type:`paste_start`});continue}if(i>=0){this.buffer+=e.slice(n,i),this.clearTimer(),t.push(this.flushPasteEnd()),n=i+6;continue}this.buffer+=e.slice(n),this.resetTimer();break}if(r>=0){this.active=!0,this.resetTimer(),t.push({type:`paste_start`}),n=r+6;continue}if(i>=0){n=i+6;continue}break}return t}forceEnd(){if(!this.active)return null;this.clearTimer();let e=this.buffer;return this.buffer=``,this.active=!1,{type:`paste_timeout`,partialText:e}}reset(){this.clearTimer(),this.buffer=``,this.active=!1}destroy(){this.reset()}resetTimer(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.forceEnd(),this.timeoutMs)}clearTimer(){this.timer&&=(clearTimeout(this.timer),null)}flushPasteEnd(){let e=this.buffer,t=e.length===0;return this.buffer=``,this.active=!1,t&&this.onEmptyPaste?.(),{type:`paste_end`,text:e,isEmpty:t}}};const zn=/^\x1b\[(\d+)(?:;(\d+))?u$/,Bn=/^\x1b\[27;(\d+);(\d+)~$/,Vn=/^\x1b\[(\d+)~$/;function Hn(e){if(!e.startsWith(`\x1B[`)&&!e.startsWith(`\x1BO`))return null;let t=e.match(zn);if(t){let n=parseInt(t[1],10),r=t[2]?parseInt(t[2],10):1,i=r>0?r-1:0;return{name:Un(n),ctrl:!!(i&4),alt:!!(i&2),shift:!!(i&1),meta:!!(i&8),sequence:e}}let n=e.match(Bn);if(n){let t=parseInt(n[1],10),r=parseInt(n[2],10),i=!!(t&8);return{name:Un(r),ctrl:!!(t&4),alt:i,shift:!!(t&2),meta:i,sequence:e}}if(e.startsWith(`\x1BO`)){let t=e[2],n={A:`up`,B:`down`,C:`right`,D:`left`,H:`home`,F:`end`,P:`f1`,Q:`f2`,R:`f3`,S:`f4`};return t&&t in n?{name:n[t],shift:!1,alt:!1,ctrl:!1,meta:!1,sequence:e}:null}let r=e.match(/^\x1b\[(?:\d+;)?(\d+)?([ABCD])$/);if(r){let t={A:`up`,B:`down`,C:`right`,D:`left`},n=r[1]?parseInt(r[1],10):1;return{name:t[r[2]],ctrl:!!(n&4),alt:!!(n&8),shift:!!(n&2),meta:!!(n&8),sequence:e}}let i=e.match(Vn);return i?{name:Wn(parseInt(i[1],10)),shift:!1,alt:!1,ctrl:!1,meta:!1,sequence:e}:null}function Un(e){return e>=97&&e<=122?String.fromCharCode(e):e>=65&&e<=90?String.fromCharCode(e+32):e===13?`return`:e===9?`tab`:e===27?`escape`:e===32?`space`:e===127||e===8?`backspace`:String.fromCharCode(e)}function Wn(e){switch(e){case 1:case 7:return`home`;case 2:return`insert`;case 3:return`delete`;case 4:case 8:return`end`;case 5:return`pageup`;case 6:return`pagedown`;case 11:return`f1`;case 12:return`f2`;case 13:return`f3`;case 14:return`f4`;case 15:return`f5`;case 17:return`f6`;case 18:return`f7`;case 19:return`f8`;case 20:return`f9`;case 21:return`f10`;case 23:return`f11`;case 24:return`f12`;default:return`f${e}`}}function Gn(e){if(!process.stdout.isTTY)return;let t=Kn(e);t&&process.stdout.write(`\x1b]0;${t}\x07`)}function Kn(e){let t=e.replace(/[\x00-\x1f\x7f-\x9f]/g,``).replace(/[\u200b\u200c\u200e\u200f\u202a-\u202e\u2060-\u206f\ufeff]/g,``).replace(/\s+/g,` `).trim();return t.length>240?t.slice(0,240):t}function qn(e,t,n){return t?`\x1b]8;${n?`id=${encodeURIComponent(n)}`:``};${encodeURIComponent(t)}\x1b\\${e}\x1b]8;;\x1b\\`:e}function Jn(e,t,n,r){let i=t.startsWith(`file://`)?t:`file://${t}`;return n!==void 0&&(i+=`#L${n}`),r!==void 0&&(i+=`:${r}`),qn(e,i)}function Yn(e,t=`c`){let n=Buffer.from(e,`utf-8`).toString(`base64`);process.stdout.write(`\x1b]52;${t};${n}\x07`)}function Xn(e=`c`){return`\x1b]52;${e};?\x07`}function Zn(){process.stdout.write(`\x1BP=1s\x1B\\`)}function Qn(){process.stdout.write(`\x1BP=2s\x1B\\`)}function $n(e){Zn();try{return e()}finally{Qn()}}const er=RegExp(`\x1B\\[\\?2026[hl]`,`g`);function tr(e){return e.includes(`\x1B[?2026`)?e.replace(er,``):e}function nr(e){return new Proxy(e,{get(e,t){if(t===`write`)return(t,...n)=>e.write(typeof t==`string`?tr(t):t,...n);let n=Reflect.get(e,t);return typeof n==`function`?n.bind(e):n}})}function rr(e=process.env){return!!e.TMUX&&e.OTTO_TUI_SYNC!==`1`}const ir=RegExp(`\x1B\\[3J`,`g`);function ar(e){return e.includes(`\x1B[3J`)?e.replace(ir,``):e}function or(e){return new Proxy(e,{get(e,t){if(t===`write`)return(t,...n)=>e.write(typeof t==`string`?ar(t):t,...n);let n=Reflect.get(e,t);return typeof n==`function`?n.bind(e):n}})}function sr(e=50){let t=[],n=0;return{snapshot(r){let i=Date.now();if(i-n<1e3)return;n=i;let a=t[t.length-1];a&&a.text===r.text&&a.offset===r.offset||(t.push({text:r.text,offset:r.offset,timestamp:i}),t.length>e&&t.splice(0,t.length-e))},undo(){return t.length===0?null:(n=0,t.pop())},get depth(){return t.length},reset(){t.length=0,n=0}}}function cr(e,t){if(!e)return[];let n=[];for(let r=t.length-1;r>=0;r--){let i=t[r],a=Jt(e,i);a&&n.push({entry:i,index:r,score:a.score,highlightRanges:Xt(a.positions)})}return n.sort((e,t)=>t.score-e.score||t.index-e.index),n.map(({entry:e,highlightRanges:t})=>{let n=t[0],r=t.at(-1);return{entry:e,matchStart:n?.start??0,matchEnd:r?.end??0,highlightRanges:t}})}function lr(e={}){let t=e.maxSize??100,n=e.initialEntries?[...e.initialEntries]:[];n.length>t&&n.splice(0,n.length-t);let r=-1,i=``,a=!1,o=[],s=``;return{push(e){e.length!==0&&(n.length>0&&n[n.length-1]===e||(n.push(e),n.length>t&&n.shift()))},navigateUp(e){return n.length===0?null:r===-1?(i=e,r=n.length-1,n[r]):r<=0?null:(r--,n[r])},navigateDown(){return r===-1?null:(r++,r>=n.length?(r=-1,i):n[r])},resetNavigation(){r=-1,i=``},beginSearch(e){s=e,a=!0,o=[],r===-1&&(i=e)},search(e){return!a||!e?[]:(o=cr(e,n),o)},acceptSearch(e){if(e<0||e>=o.length)return null;let t=o[e].entry;return a=!1,r=n.indexOf(t),t},cancelSearch(){return a=!1,o=[],s},get size(){return n.length},get navState(){return r===-1?null:{position:n.length-r,total:n.length}},getAll(){return n},clear(){n.length=0,r=-1,i=``,a=!1,o=[]}}}function ur(e,t){let n=process.env[e];if(!n)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:t}const dr=ur(`OTTO_PASTE_STORE_MAX_ENTRIES`,64),fr=ur(`OTTO_PASTE_STORE_MAX_BYTES`,33554432),pr=ur(`OTTO_PASTE_STORE_PERSIST_MAX_BYTES`,8388608),mr={healthy:1,warning:2,critical:4},hr=/\[@paste:#(\d+)(?:\s+\+(\d+)\s+lines)?\]/g;function gr(e){let t=[];hr.lastIndex=0;let n;for(;(n=hr.exec(e))!==null;)t.push({start:n.index,end:n.index+n[0].length,id:Number.parseInt(n[1],10)});return t}function _r(e){return Buffer.byteLength(e,`utf-8`)}function vr(e){if(!(typeof e!=`number`||!Number.isFinite(e)))return Math.floor(e)}function yr(e={}){let{residencyGovernor:t}=e,n=new Map,r=1,i=0,a=0;function o(){return t?.currentLevel??`healthy`}function s(){return Math.max(1,Math.floor(dr/mr[o()]))}function c(){return Math.max(1,Math.floor(fr/mr[o()]))}function l(e){let t=s(),r=c();for(;n.size>0&&(n.size>=t||i+e>r);){let e=n.keys().next().value;if(e===void 0)break;let t=n.get(e);t&&(i-=t.byteLength),n.delete(e),a++}}return{foldIfLarge(e){let t=e.split(`
|
|
2
2
|
`);if(e.length<=800&&t.length<=20)return e;let a=_r(e);l(a);let o=r++;return n.set(o,{text:e,byteLength:a}),i+=a,t.length>1?`[@paste:#${o} +${t.length} lines]`:`[@paste:#${o}]`},expandAll(e){let t=gr(e);if(t.length===0)return{text:e,missingIds:[]};let r=[],s=o(),c=[...t].sort((e,t)=>t.start-e.start),l=e;for(let e of c){let t=n.get(e.id);if(t===void 0){r.push(e.id);continue}l=l.slice(0,e.start)+t.text+l.slice(e.end),s===`healthy`?(n.delete(e.id),n.set(e.id,t)):(n.delete(e.id),i-=t.byteLength,a++)}return{text:l,missingIds:r.sort((e,t)=>e-t)}},findMissingIds(e){let t=gr(e),r=[];for(let e of t)n.has(e.id)||r.push(e.id);return[...new Set(r)].sort((e,t)=>e-t)},peek(e){return n.get(e)?.text},truncateIfNeeded(e){return e.length<=1e4?e:e.slice(0,500)+`\n[...Truncated ${e.length-500-500} chars...]\n`+e.slice(e.length-500)},addImageRef(){return`[@paste:image #${r++}]`},afterSubmit(e){if(o()!==`healthy`)for(let t of gr(e)){let e=n.get(t.id);e!==void 0&&(n.delete(t.id),i-=e.byteLength,a++)}},toSnapshot(){let e=[...n.entries()].map(([e,t])=>({id:e,text:t.text,byteLength:t.byteLength})),t=e.reduce((e,t)=>e+t.byteLength,0),i=0;for(;i<e.length&&t>pr;)t-=e[i].byteLength,i++;return{entries:i>0?e.slice(i):e,nextId:r}},hydrate(e){n.clear(),i=0;let t=Math.max(1,Math.floor(vr(e?.nextId)??0));for(let n of e?.entries??[]){let e=vr(n?.id);e!==void 0&&(t=Math.max(t,e+1))}r=Math.max(r,t);for(let t of e?.entries??[]){let e=vr(t?.id);if(e===void 0||typeof t?.text!=`string`||n.has(e))continue;let r=_r(t.text);n.set(e,{text:t.text,byteLength:r}),i+=r}},get size(){return n.size},get bytesUsed(){return i},get evictionCount(){return a},clear(){n.clear(),i=0}}}function br(e){let t=e?[...e]:[],n=new Map;return{register(e){for(let n of e)t.some(e=>e.name===n.name)||t.push(n);t.sort((e,t)=>(e.sortKey??e.name).localeCompare(t.sortKey??t.name))},search(e,n=50){return Zt(t.map(e=>({text:e.name,aliases:[...e.aliases??[],...e.description?[e.description]:[]],payload:e,sortKey:e.sortKey})),e,{maxResults:n}).map(e=>e.item.payload)},getAll:()=>t,find:e=>t.find(t=>t.name===e),registerArgumentSuggester(e,t){n.set(e,t)},getArgumentSuggester(e){return n.get(e)}}}function xr(e,t){let n=e.slice(0,t).trimStart();if(!n.startsWith(`/`))return null;let r=n.match(/^\/(.*)$/);return r?r[1]??``:null}function Sr(e,t,n){let r=xr(e,t);if(r===null)return null;let i=r.indexOf(` `);if(i>0){let e=r.slice(0,i),t=r.slice(i+1),a=n.getArgumentSuggester(e);if(a){let n=$t(a(t),t);if(n.length>0)return{suggestions:n,selectedIndex:0,prefix:`/${r}`,panelOpen:!0,argCommand:e}}return null}let a=n.search(r);return a.length===0?null:{suggestions:a,selectedIndex:0,prefix:`/${r}`,panelOpen:!0}}function Cr(e,t){switch(t){case`prev`:return{...e,selectedIndex:(e.selectedIndex-1+e.suggestions.length)%e.suggestions.length};case`next`:return{...e,selectedIndex:(e.selectedIndex+1)%e.suggestions.length};case`accept`:return`accept`;case`dismiss`:return`dismiss`}}function wr(e,t,n){let r=e.slice(0,t),i=r.lastIndexOf(`/`);if(i<0)return{text:e,offset:t};let a=r.slice(i+1),o=a.indexOf(` `),s=o>=0?a.slice(o):` `,c=`/${n.name}${s}`;return{text:e.slice(0,i)+c+e.slice(t),offset:i+c.length}}function Tr(e){return{text:e,offset:e.length}}function Er(e,t,n,r){if(!e)return null;let i=t.slice(0,n),a=i.lastIndexOf(`
|
|
3
3
|
`)+1;return Le(i.slice(a)+(t.slice(n).split(`
|
|
4
4
|
`)[0]??``))+Le(e)>r?null:e}function Dr(e){return e.startsWith(`!!`)?{prefix:`!!`,body:e.slice(2)}:e.startsWith(`!`)?{prefix:`!`,body:e.slice(1)}:{prefix:``,body:e}}function Or(e){return e.startsWith(`!!`)?e.slice(2):e.startsWith(`!`)?e.slice(1):e}function kr(e,t,n){let{prefix:r,body:i}=Dr(e);if(r.length>0){if(i.length===0)return null;let e=i.toLowerCase();for(let a=n.length-1;a>=0;a--){let o=Or(n[a]);if(o.length<=i.length||!o.toLowerCase().startsWith(e))continue;let s=r+o;return{fullText:s,suffix:s.slice(t),kind:`history`}}return null}let a=e.toLowerCase();for(let r=n.length-1;r>=0;r--){let i=n[r];if(!(i.length<=e.length)&&i.toLowerCase().startsWith(a))return{fullText:i,suffix:i.slice(t),kind:`history`}}return null}function Ar(e,t,n){let r=xr(e,t);if(r===null||r.length===0)return null;let i=r.indexOf(` `);if(i>0){let a=r.slice(0,i),o=r.slice(i+1),s=n.getArgumentSuggester(a);if(!s)return null;let c=$t(s(o),o,{maxResults:1});if(c.length===0)return null;let l=Mr(e,t,a,c[0].name);return{fullText:l.text,suffix:l.text.slice(t),kind:`slash-arg`}}let a=n.search(r,1);if(a.length===0)return null;let o=wr(e,t,a[0]);return{fullText:o.text,suffix:o.text.slice(t),kind:`slash-command`}}function jr(e){let{text:t,offset:n,dismissedPrefix:r,history:i,registry:a}=e;if(n!==t.length||t.length===0||r!==void 0&&r===t)return null;if(a&&t.trimStart().startsWith(`/`)){let e=xr(t,n);if(e!==null&&e.length===0)return null;let r=Ar(t,n,a);if(r)return r}return kr(t,n,i)}function Mr(e,t,n,r){let i=e.slice(0,t),a=i.lastIndexOf(`/`);if(a<0)return{text:e,offset:t};let o=i.slice(a+1).indexOf(` `);if(o<0)return{text:e,offset:t};let s=a+1+o+1;return{text:e.slice(0,s)+r+e.slice(t),offset:s+r.length}}function Nr(e){return(e.VISUAL||e.EDITOR||``).trim()||(process.platform===`win32`?`notepad`:`vi`)}function Pr(e,t){let n=Nr(t.env),r=null;try{r=t.mkdtempSync(t.join(t.tmpdir(),`otto-edit-`));let i=t.join(r,`prompt.md`);t.writeFileSync(i,e);let a=n.split(/\s+/).filter(Boolean),o=a[0],s=[...a.slice(1),i],c=t.spawnSync(o,s,{stdio:`inherit`});return c.error?{ok:!1,error:`cannot launch editor "${n}": ${c.error.message}`}:c.status!=null&&c.status!==0?{ok:!1,error:`editor exited with code ${c.status}`}:{ok:!0,text:t.readFileSync(i).replace(/\n$/,``)}}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}finally{if(r)try{t.rmSync(r,{recursive:!0,force:!0})}catch{}}}function Fr(){let e=Ne(`fs`),t=Ne(`os`),n=Ne(`path`),r=Ne(`child_process`);return{env:process.env,tmpdir:()=>t.tmpdir(),join:(...e)=>n.join(...e),mkdtempSync:t=>e.mkdtempSync(t),writeFileSync:(t,n)=>e.writeFileSync(t,n),readFileSync:t=>e.readFileSync(t,`utf8`),rmSync:(t,n)=>e.rmSync(t,n),spawnSync:(e,t,n)=>{let i=r.spawnSync(e,t,n);return{status:i.status,error:i.error}}}}const Ir=`/overlay/toast`,Lr=`/overlay/pause`,Rr=`/overlay/retry`,zr=`/overlay/error-retry`,Br=`/overlay/pulse-survey`,Vr=`/overlay/forced-upgrade`,Hr=`/overlay/paste-confirm`,Ur=`/overlay/services`,Wr=`/overlay/chip-viewer`,Gr=[Ir,Lr,Rr,zr,Br,Vr,Hr,Ur,Wr];function Kr(e){return e.startsWith(`/overlay/`)}function qr(e,t,n){e&&(n?e.ensure(t):e.dismiss(t))}const Jr=[/\bpassword\s*=/i,/\btoken\s*=/i,/export\s+\w*key\w*\s*=/i,/\bsecret\s*=/i];function Yr(e,t=Jr){return t.some(t=>t.test(e))}const Xr=`zsh-histfile`,Zr=/^: (\d+):(\d+);(.*)$/s;function Qr(e){let t=[],n;for(let r of e){let e=n===void 0?r:`${n}\n${r}`;if($r(r)){n=e.slice(0,-1);continue}t.push(e),n=void 0}return n!==void 0&&t.push(n),t}function $r(e){let t=0;for(let n=e.length-1;n>=0&&e[n]===`\\`;n--)t++;return t%2==1}function ei(e,t={}){let{source:n=Xr,sensitivePatterns:r,filterSensitive:i=!0}=t,a=[],o=0;for(let t of Qr(e.split(`
|
|
@@ -95,7 +95,7 @@ line three`,onDismiss:$},rows:24,columns:80})}]},{id:`A2uiFormDialog`,category:`
|
|
|
95
95
|
\r`);let r=o-n;r>0?s+=`[${r}B`:r<0&&(s+=`[${-r}A`),s+=`\r`}let c=e.bottom>=e.top&&n-this.lastRedrawAt<this.burstQuietMs();e.bottom>=e.top&&(this.lastRedrawAt=n);let l=t!==void 0&&this.prevCursor!==void 0&&t.x===this.prevCursor.x&&t.y===this.prevCursor.y,u=e.bottom>=e.top&&t!==void 0&&t.y>=e.top&&t.y<=e.bottom;if(l&&!u&&e.bottom>=e.top){let n=`\x1B7`,a=t.y-e.top;a>0?n+=`[${a}A`:a<0&&(n+=`[${-a}B`),n+=`\r`;let o=Math.min(e.bottom,i-1);for(let t=e.top;t<=o;t++)n+=`\x1B[2K`,t<this.rows.length&&(n+=this.renderLine(t)),t<o&&(n+=`
|
|
96
96
|
\r`);return n+=`\x1B8`,this.prevLineCount=r,n}if(t){let e=o-Math.max(0,Math.min(t.y,o));e>0&&(s+=`[${e}A`),t.x>0?s+=`[${t.x+1}G`:s+=`\r`,c||(s+=`\x1B[?25h`)}return this.prevLineCount=r,this.prevCursor=t?{...t}:void 0,this.cursorShown=t!==void 0&&!c,s}clampToMaxWidth(e){let t=this.maxLineWidth;if(t<=0)return e;let n=0;for(let r=0;r<e.length;r++){let i=e[r].width;if(n+i>t)return e.slice(0,r);n+=i}return e}renderLine(e){let t=this.rows[e];if(!t)return``;let n=this.selectionQuery,r=``,i=``,a=!1;for(let o=0;o<t.length;o++){let s=t[o];if(s.width===0)continue;s.style!==i&&(i&&(r+=`\x1B[0m`),r+=s.style,i=s.style,a=!1);let c=n?.(e,o)??!1;c!==a&&(r+=c?`\x1B[7m`:wg,a=c),r+=s.ch}return a&&(r+=wg),i&&(r+=`\x1B[0m`),r}setChromeWidths(e){if(!e||e.length===0){this.chromeWidths=null;return}this.chromeWidths=Int32Array.from(e)}chromeWidth(e){return!this.chromeWidths||e<0||e>=this.chromeWidths.length?0:this.chromeWidths[e]}setSelectionQuery(e){this.selectionQuery=e??void 0}buildSelectionRepaint(e,t){let n=Math.max(0,Math.min(e,t)),r=Math.min(this.rows.length-1,Math.max(e,t));if(r<n||this.rows.length===0)return``;let i=this.cursorRow(),a=`\x1B7`,o=i-n;o>0?a+=`[${o}A`:o<0&&(a+=`[${-o}B`),a+=`\r`;for(let e=n;e<=r;e++)a+=`[2K${this.renderLine(e)}`,e<r&&(a+=`
|
|
97
97
|
\r`);return a+=`\x1B8`,a}markRowDirty(e){e>=0&&e<this.rows.length&&this.markDirty(e)}markAllDirty(){for(let e=0;e<this.rows.length;e++)this.markDirty(e)}};function Og(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){let r=e[n],i=t[n];if(r.ch!==i.ch||r.style!==i.style||r.width!==i.width)return!1}return!0}function kg(e){let t=[],n=``,r=0,i=0,a=/^\x1b\]9;cw=(\d+)\x07/.exec(e);for(a&&(i=parseInt(a[1],10),r=a[0].length),kg._lastChromeWidth=i;r<e.length;){if(e.charCodeAt(r)===27){Eg.lastIndex=r;let t=Eg.exec(e);if(t){let e=t[0];n=/\x1b\[0?m/.test(e)?``:n+e,r=Eg.lastIndex;continue}r++;continue}let i=String.fromCodePoint(e.codePointAt(r));r+=i.length,Le(i)===2?(t.push({ch:i,style:n,width:2}),t.push({ch:``,style:n,width:0})):t.push({ch:i,style:n,width:1})}return t}function Ag(e=process.env){return e.OTTO_TUI_CELL_BUFFER!==`0`}async function jg(e,t=process.env){if(!Ag(t)||!e.isTTY)return null;let n=new Dg,r=0,i=0,a=null,o,s=()=>{a&&clearTimeout(a),a=setTimeout(()=>{if(a=null,o)try{let t=n.buildCursorOnlySequence(o);t&&e.write(t)}catch{}},210),a.unref?.()},c=null,l=null;return c=await xg(t=>{r++,n.ingest(t);let a=n.takeDamage();l?.(a);let u=c?.cursorIntent();if(o=u,!a)return i++,u&&e.write(n.buildCursorOnlySequence(u)),!1;try{e.write(n.buildFlushSequence(a,u)),s()}catch{return!0}return!1}),c?{buffer:n,dispose:()=>{a&&clearTimeout(a),l=null,c.dispose()},stats:()=>({frames:r,skipped:i}),onDamage:e=>{l=e}}:null}function Mg({anchor:e,focus:t}){return t.row<e.row||t.row===e.row&&t.col<e.col?{start:t,end:e}:{start:e,end:t}}function Ng(e){return e.anchor.row===e.focus.row&&e.anchor.col===e.focus.col}function Pg(e,t,n,r){return!(t<e.start.row||t>e.end.row||r?.(t,n)||t===e.start.row&&n<e.start.col||t===e.end.row&&n>=e.end.col)}function Fg(e,t,n){if(!n)return 0;for(let r=0;r<e.length;r++)if(!n(t,r))return r;return e.length}function Ig({selection:e,lineAt:t,noSelect:n}){if(Ng(e))return``;let r=Mg(e),i=[];for(let e=r.start.row;e<=r.end.row;e++){let a=t(e);if(!a||Fg(a,e,n)>=a.length)continue;let o=``;for(let t=0;t<a.length;t++){let i=a[t];i.width!==0&&Pg(r,e,t,n)&&(o+=i.ch)}i.push(o.replace(/\s+$/,``))}return i.join(`
|
|
98
|
-
`)}var Lg=class{range=null;dragging=!1;begin(e){this.range={anchor:e,focus:e},this.dragging=!0}extend(e){!this.dragging||!this.range||(this.range={anchor:this.range.anchor,focus:e})}commit(){this.dragging=!1}clear(){this.range=null,this.dragging=!1}current(){return!this.range||Ng(this.range)?null:this.range}isDragging(){return this.dragging}};function Rg(e){let{buffer:t,terminalRows:n,writeSelectionRepaint:r,writeClipboard:i,onCopied:a}=e,o=e.noSelect??((e,n)=>n<t.chromeWidth(e)),s=(e,r)=>{let i=Math.max(0,r-1),a=Math.max(0,n()-t.height);return{row:Math.max(0,i-a),col:Math.max(0,e-1)}},c=new Lg,l=null,u=()=>{let e=c.current(),n=null;if(!e)t.setSelectionQuery(null);else{let r=Mg(e);t.setSelectionQuery((e,t)=>Pg(r,e,t,o)),n={top:r.start.row,bottom:r.end.row}}let i=Math.min(n?.top??1/0,l?.top??1/0),a=Math.max(n?.bottom??-1,l?.bottom??-1);l=n,!(a<i)&&r(t.buildSelectionRepaint(i,a))},d=({clearAfter:e})=>{let n=c.current();if(!n)return!1;let r=Ig({selection:n,lineAt:e=>t.lineAt(e),noSelect:o});if(r.length===0)return!1;let s=i(r);return a?.(r,s),e&&(c.clear(),u()),s};return{handleDrag(e){let t=s(e.x,e.y);switch(e.type){case`down`:c.begin(t),u();break;case`move`:if(!c.isDragging())return;c.extend(t),u();break;case`up`:c.extend(s(e.x,e.y)),c.commit(),u(),d({clearAfter:!1});break}},copySelection(){return d({clearAfter:!0})},onFrameDamage(e){if(!e)return!1;let t=c.current();if(!t||c.isDragging())return!1;let{start:n,end:r}=Mg(t);return e.bottom<n.row||e.top>r.row?!1:(c.clear(),u(),!0)},clear(){!c.current()&&!c.isDragging()||(c.clear(),u())},hasSelection(){return c.current()!==null}}}function zg(e){return Array.from(e).length}const Bg=`\x1B[?1006h\x1B[?1002h`,Vg=`\x1B[?1002l\x1B[?1006l`;function Hg(e,t){let n=t;if(
|
|
98
|
+
`)}var Lg=class{range=null;dragging=!1;begin(e){this.range={anchor:e,focus:e},this.dragging=!0}extend(e){!this.dragging||!this.range||(this.range={anchor:this.range.anchor,focus:e})}commit(){this.dragging=!1}clear(){this.range=null,this.dragging=!1}current(){return!this.range||Ng(this.range)?null:this.range}isDragging(){return this.dragging}};function Rg(e){let{buffer:t,terminalRows:n,writeSelectionRepaint:r,writeClipboard:i,onCopied:a}=e,o=e.noSelect??((e,n)=>n<t.chromeWidth(e)),s=(e,r)=>{let i=Math.max(0,r-1),a=Math.max(0,n()-t.height);return{row:Math.max(0,i-a),col:Math.max(0,e-1)}},c=new Lg,l=null,u=()=>{let e=c.current(),n=null;if(!e)t.setSelectionQuery(null);else{let r=Mg(e);t.setSelectionQuery((e,t)=>Pg(r,e,t,o)),n={top:r.start.row,bottom:r.end.row}}let i=Math.min(n?.top??1/0,l?.top??1/0),a=Math.max(n?.bottom??-1,l?.bottom??-1);l=n,!(a<i)&&r(t.buildSelectionRepaint(i,a))},d=({clearAfter:e})=>{let n=c.current();if(!n)return!1;let r=Ig({selection:n,lineAt:e=>t.lineAt(e),noSelect:o});if(r.length===0)return!1;let s=i(r);return a?.(r,s),e&&(c.clear(),u()),s};return{handleDrag(e){let t=s(e.x,e.y);switch(e.type){case`down`:c.begin(t),u();break;case`move`:if(!c.isDragging())return;c.extend(t),u();break;case`up`:c.extend(s(e.x,e.y)),c.commit(),u(),d({clearAfter:!1});break}},copySelection(){return d({clearAfter:!0})},onFrameDamage(e){if(!e)return!1;let t=c.current();if(!t||c.isDragging())return!1;let{start:n,end:r}=Mg(t);return e.bottom<n.row||e.top>r.row?!1:(c.clear(),u(),!0)},clear(){!c.current()&&!c.isDragging()||(c.clear(),u())},hasSelection(){return c.current()!==null}}}function zg(e){return Array.from(e).length}const Bg=`\x1B[?1006h\x1B[?1002h`,Vg=`\x1B[?1002l\x1B[?1006l`;function Hg(e,t){let n=t;if(n>=e.length)return`pending`;let r=[],i=0,a=!1;for(;n<e.length;n++){let t=e[n];if(t>=48&&t<=57)i=i*10+(t-48),a=!0;else if(t===59){if(!a)return null;r.push(i),i=0,a=!1}else if(t===77||t===109)return!a||(r.push(i),r.length<3)?null:{b:r[0],x:r[1],y:r[2],final:t,end:n+1};else return null}return a||r.length>0?`pending`:null}function Ug(e,t){return e[t]!==27||e[t+1]!==91||e[t+2]!==60?null:Hg(e,t+3)}function Wg(e,t){return e.length<=t?`pending`:e[t]===91?e.length<=t+1?`pending`:e[t+1]===60?Hg(e,t+2):null:null}function Gg(e,t,n){let{b:r,x:i,y:a,final:o}=e,s=e=>r===e||r===e+4||r===e+8||r===e+16;if(o===77&&(s(64)||s(65))){let e=s(64)?64:65;return r&4||t.push({kind:`wheel`,delta:e===64?1:-1,x:i,y:a,shift:!1,ctrl:!!(r&16)}),{kind:`wheel-consumed`}}let c=!!(r&4),l=r&-29,u=o===77&&l===0,d=o===77&&l===32;return!c&&(u||d||o===109)?(n.push({kind:`drag`,type:u?`down`:d?`move`:`up`,x:i,y:a,ctrl:!!(r&16)}),{kind:`drag-consumed`}):c?{kind:`shift-passthrough`}:{kind:`swallowed`}}function Kg(){let e=Buffer.alloc(0),t=!1,n=!1,r=!1;return i=>{let a=F(i),o=e.length?Buffer.concat([e,a]):a;e=Buffer.alloc(0);let s=r;r=!1;let c=n;n=!1;let l=[],u=[],d=[];if(s||c){let t=Wg(o,0);if(t===`pending`)return e=o,r=!0,{wheels:[],drags:[],rest:Buffer.alloc(0)};if(t!==null){if(Gg(t,l,u).kind===`shift-passthrough`)for(let e=0;e<t.end;e++)d.push(o[e]);o=o.subarray(t.end)}}let f=0;f=((n,r)=>{let i=n;for(;i<o.length;){if(t){let e=o.indexOf(`\x1B[201~`,i);if(e===-1){r.push(...o.subarray(i)),i=o.length;break}r.push(...o.subarray(i,e+6)),i=e+6,t=!1;continue}let n=o.indexOf(`\x1B[200~`,i),a=o[i]===27&&o[i+1]===91&&o[i+2]===60?i:-1;if(n!==-1&&(a===-1||n<a)){r.push(...o.subarray(i,n+6)),i=n+6,t=!0;continue}if(a===-1&&i+2===o.length&&o[i]===27&&o[i+1]===91)return e=Buffer.from(o.subarray(i)),i;if(a!==-1){let t=Ug(o,a);if(t===`pending`)return e=Buffer.from(o.subarray(a)),i;if(t!==null){if(Gg(t,l,u).kind===`shift-passthrough`)for(let e=a;e<t.end;e++)r.push(o[e]);i=t.end;continue}r.push(o[i]),i++;continue}r.push(o[i]),i++}return i})(f,d);let p=Buffer.from(d);return n=p.length>0&&p[p.length-1]===27,{wheels:l,drags:u,rest:p}}}function qg(e,t=16){let n=0,r=null,i=()=>{if(r!==null&&(clearTimeout(r),r=null),n!==0){let t=n;n=0,e(t)}};return{push(e){n+=e,r===null&&(r=setTimeout(i,t))},flushNow:i}}function Jg(e=process.platform,t=process.env){if(e===`darwin`)return{command:`pbcopy`,args:[]};if(e===`win32`)return{command:`powershell`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,`$input | Set-Clipboard`]};if(e===`linux`){if(t.WSL_DISTRO_NAME||t.WSLENV)return{command:`powershell.exe`,args:[`-NoProfile`,`-NonInteractive`,`-Command`,`$input | Set-Clipboard`]};if(t.WAYLAND_DISPLAY)return{command:`wl-copy`,args:[]};if(t.DISPLAY)return{command:`xclip`,args:[`-selection`,`clipboard`]}}return null}function Yg(e,t=process.platform,n=process.env){let r=Jg(t,n);if(!r)return!1;try{let t=hn(r.command,r.args,{stdio:[`pipe`,`ignore`,`ignore`],detached:!1});return t.on(`error`,()=>{}),t.stdin.on(`error`,()=>{}),t.stdin.end(e,`utf8`),!0}catch{return!1}}const Xg=`\x1B[<u`,Zg=/\x1b\[(\d+)(?:;(\d+))?u/g;function Qg(e,t){let n=t>0?t-1:0,r=!!(n&1),i=!!(n&2),a=!!(n&4),o=!!(n&8),s=i||o?`\x1B`:``;if(e===13)return a||i||o||r?`\x1B\r`:`\r`;if(e===9)return s+` `;if(e===27)return`\x1B`;if(e===127||e===8)return s+``;if(e>=65&&e<=90||e>=97&&e<=122){let t=e>=65&&e<=90?e+32:e;return a?s+String.fromCharCode(t&31):s+String.fromCharCode(r?t-32:t)}return e>=32?a?``:s+String.fromCodePoint(e):``}function $g(e){let t=e.lastIndexOf(`\x1B`);if(t<0)return-1;let n=e.slice(t);return/^\x1b\[[\d;:]*[A-Za-z~]/.test(n)||/^\x1b[NO]./.test(n)||/^\x1b[^[NO]/.test(n)&&n.length>=2?-1:t}function e_(){let e=``;return t=>{let n=e+(typeof t==`string`?t:t.toString(`latin1`));e=``;let r=$g(n);r>=0&&(e=n.slice(r),n=n.slice(0,r));let i=n.replace(Zg,(e,t,n)=>Qg(parseInt(t,10),n?parseInt(n,10):1));return Buffer.from(i,`latin1`)}}function t_(e){let{stdin:t,renderStdout:n,kittyOn:r,kittyExitHandler:i,focusOn:a,focusExitHandler:o,mouseOn:s,mouseExitHandler:c,onInterrupt:l,terminalInputCleanup:u}=e,d=!1,f=e=>{let t=F(e);t.length>=1&&t[0]===3&&l?.()},p=()=>l?.();return{setupRawInput:()=>{try{t.isTTY&&(t.on(`data`,f),d=!0)}catch{}process.on(`SIGINT`,p)},cleanup:()=>{if(r){try{n.write(Xg)}catch{}i&&process.removeListener(`exit`,i)}if(a&&o&&process.removeListener(`exit`,o),s){try{n.write(Vg)}catch{}c&&process.removeListener(`exit`,c)}d&&t.removeListener(`data`,f),process.removeListener(`SIGINT`,p),u();try{t.isTTY&&t.pause()}catch{}try{t.isTTY&&t.setRawMode(!1)}catch{}}}}const n_=/\x1b\[[0-9;]*m/g;function r_(e){let t=``,n=0,r=0,i=!1,a=()=>Math.max(1,e.getColumns()-ge.borderInset),o=t=>{if(t.length===0)return;e.setHasHistory(!0);let n=!i,r=t.map((e,t)=>n&&t===0?`${Q(R.bullet,L.replyPrefix)} ${e}`:e.replace(n_,``).trim()===``?``:` ${e}`);i=!0,e.scrollbackBuffer.write((n?`
|
|
99
99
|
`:``)+r.join(`
|
|
100
100
|
`)+`
|
|
101
101
|
`)},s=()=>{t=``,n=0,r=0,i=!1,e.streamStore.setState({lastTail:void 0})},c=e=>{let t=$a(Os(e),a());if(t.length===0)return;let n=r===0?t:[``,...t];o(n),r+=n.length},l=(e,n)=>{if(n<=e)return;let r=t.slice(e,n);if((r.match(/\n/g)??[]).length+1>60){let e=r.split(`
|
|
@@ -104,6 +104,6 @@ line three`,onDismiss:$},rows:24,columns:80})}]},{id:`A2uiFormDialog`,category:`
|
|
|
104
104
|
`),s=0;c(o.slice(0,60).join(`
|
|
105
105
|
`)),s=60;let l=()=>{if(s>=o.length){i();return}c(o.slice(s,s+60).join(`
|
|
106
106
|
`)),s+=60,e.notify(),setImmediate(l)};setImmediate(l)},d=r=>{if(r===``){u(n,t.length,()=>{s(),e.streamStore.setState({streamingText:``})});return}t=r;let i=Tc(r);i>n&&(l(n,i),n=i);let o=r.slice(n);o!==e.streamStore.getState().lastTail&&e.streamStore.setState({streamingText:o.trim()?$a(Os(Xc(o)),a()).join(`
|
|
107
|
-
`):``,lastTail:o})},f=t=>{if(e.scrollbackMode){d(t);return}let{chunks:n,tail:r,state:i}=Dc(e.streamStore.getState().streamCommit,t);if(n.length>0){let t=n.map(t=>{let n=e.incMsgCounter();return{role:`assistant_stream`,text:t.text,lead:t.lead,id:`s-${n}`}});e.messageStoreHandle.appendMany(t,()=>`s-${e.incMsgCounter()}`)}e.streamStore.setState({streamCommit:i,streamingText:r}),(t===``||n.length>0)&&e.notify()},p=t=>{e.streamStore.setState({streamingThinking:t})};return{applyStreamText:f,applyStreamThinking:p,streamTextCoalescer:Ac(f,e.coalesceMs),streamThinkingCoalescer:Ac(p,e.coalesceMs),outputTokensThrottle:sl(e.streamStore,e.coalesceMs),resetController:()=>{t=``,n=0,r=0,i=!1}}}function t_(e,t){if(e.length===0)return[];let n=Math.max(1,t);return e.map(e=>nc(e,n))}function n_(e){let t=t=>{let n=t_(t,e.getColumns()),{text:r,hasHistory:i}=Vc(t.map((e,t)=>({role:e.role??``,lines:n[t]??[]})),e.getHasHistory());return e.setHasHistory(i),r},n=null,r=r=>{let i=t(r);if(i){if(n){n.push(i);return}e.scrollbackBuffer.write(i)}},i=i=>{if(i.length<=60&&!n){r(i);return}if(n){let e=t(i);e&&n.push(e);return}n=[t(i.slice(0,60))];let a=60,o=()=>{if(a>=i.length){let t=(n??[]).join(``);n=null,t&&e.scrollbackBuffer.write(t),e.notify();return}let r=i.slice(a,a+60);a+=60,n?.push(t(r)),setImmediate(o)};setImmediate(o)};return{commitToHistory:e=>i([e]),commitManyToHistory:i}}function r_(e){let{taskStore:t,notificationStore:n,resolvers:r,flushScrollbackIfIdle:i,paneOwnsViewport:a,setPaneOwnsViewport:o,getRouter:s=P}=e,c=null,l={},u=(e,t)=>{let n=s();n.navigate(`/dialog/plugin-panel`,{state:{panelInfo:e,onClose:()=>{n.goBack(),t?.()}}})};return{openModal:(e=>{switch(e.kind){case`select`:{let t=s();if(e.async){let n=!1;t.navigate(`/dialog/select`,{state:{title:e.title,subtitle:`Probing, please wait…`,options:[],layout:e.layout??`buttons`}}),r.select=e=>{if(e==null){n=!0;return}},(async()=>{try{let i=await e.async;if(n)return;r.select=t=>{t==null?e.onCancel?.():e.onSelect(t)},t.navigate(`/dialog/select`,{replace:!0,state:{title:i.title??e.title,subtitle:i.subtitle??e.subtitle,subtitleTone:e.subtitleTone,options:i.options,maxVisible:e.maxVisible,layout:e.layout,searchable:e.searchable,subtitleActions:e.subtitleActions,detailPlacement:e.detailPlacement,onHighlight:e.onHighlight}})}catch(i){if(n)return;r.select=()=>{},t.navigate(`/dialog/select`,{replace:!0,state:{title:e.title,subtitle:`Error: ${i instanceof Error?i.message:String(i)}`,options:[{label:`Close`,value:`close`,color:`gray`}],layout:`buttons`}})}})();return}process.env.NODE_ENV!==`production`&&t.currentPath===`/dialog/select`&&e.replace!==!0&&console.warn('[openModal] Detected re-entrant openModal({ kind: "select" }) — this pushes a new dialog stack entry instead of replacing the current one. Use the `async` field for loading→content transitions, or close the current dialog before opening a new one. See RFC-285 D2.');let n=e.replace===!0&&t.currentPath===`/dialog/select`;t.navigate(`/dialog/select`,{replace:n,state:{title:e.title,subtitle:e.subtitle,subtitleTone:e.subtitleTone,options:e.options,maxVisible:e.maxVisible,searchable:e.searchable,layout:e.layout,subtitleActions:e.subtitleActions,detailPlacement:e.detailPlacement,initialFilter:e.initialFilter,onFilterChange:e.onFilterChange,onHighlight:e.onHighlight,defaultSelectedValue:e.defaultSelectedValue}}),r.select=t=>{t==null?e.onCancel?.():e.onSelect(t)};return}case`extensionDetail`:{let t=s(),n=()=>{t.goBack()};t.navigate(`/dialog/extension`,{state:{title:e.title,meta:e.meta,metaStatus:e.metaStatus,metaSuffix:e.metaSuffix,actions:e.actions,panelInfo:e.panelInfo,info:e.info,healthStats:e.healthStats,logEntries:e.logEntries,onRefresh:e.onRefresh,dataListEntries:e.dataListEntries,fullText:e.fullText,onOpenPanel:e.panelInfo?()=>u(e.panelInfo):void 0,onAction:t=>{n(),e.onAction(t)},onClose:()=>{let r=t.stack,i=r.length>=2?r[r.length-2]?.path:void 0;n(),i!==`/dialog/extensions`&&e.onClose?.()}}});return}case`pluginPanel`:u(e.panelInfo,e.onClose);return;case`extensionsList`:{let t=s();t.navigate(`/dialog/extensions`,{state:{entries:e.entries,menuContributions:e.menuContributions,lastSelectedValue:l.value,onSelect:n=>{l.value=n,n.startsWith(`contrib:`)&&t.goBack(),e.onSelect(n)},onCancel:()=>{t.goBack(),e.onCancel?.()}}});return}case`input`:return new Promise(t=>{if(e.signal?.aborted){t(null);return}let n=!1,i=e=>{n||(n=!0,r.input===i&&(s()?.goBack(),r.input=null,r.inputAction=null),t(e))};r.input=i,e.actionButton?.onPress&&(r.inputAction=e.actionButton.onPress),e.signal?.addEventListener(`abort`,()=>i(null),{once:!0}),s().navigate(`/dialog/input`,{state:{title:e.title,description:e.description,placeholder:e.placeholder,defaultValue:e.defaultValue,mask:e.mask,actionButton:e.actionButton?{label:e.actionButton.label}:void 0}})});case`onboarding`:return new Promise(t=>{let n=!1,i=e=>{n||(n=!0,r.onboarding===i&&(s()?.navigate(`/`,{reset:!0}),r.onboarding=null),t(e))};r.onboarding=i,s().navigate(`/dialog/onboarding`,{state:{onLanguagePreview:e.onLanguagePreview}})});case`questions`:return new Promise(t=>{o(!0),r.questions=(e,n)=>{t(e?{answers:e,freeformText:n}:null)},s().navigate(`/dialog/questions`,{state:{title:e.title,questions:e.questions}})});case`confirm`:{let t=s();r.confirm=()=>e.onConfirm(),r.cancel=()=>e.onCancel?.(),r.extra=e.onExtra??null;let n=t.currentPath===`/dialog/confirm`;t.navigate(`/dialog/confirm`,{replace:n,state:{title:e.title,message:e.message,confirmLabel:e.confirmLabel,cancelLabel:e.cancelLabel,confirmColor:e.confirmColor,dangerous:e.dangerous,extraLabel:e.extraLabel,extraColor:e.extraColor}});return}case`permissions`:s().navigate(`/dialog/info`,{state:{title:`Permissions`,lines:e.lines}});return;case`info`:s().navigate(`/dialog/info`,{state:{title:e.title,lines:e.lines,action:e.action,lineTones:e.lineTones,dataListEntries:e.dataListEntries}});return;case`context`:s().navigate(`/pane/context`);return;case`memory`:s().navigate(`/dialog/memory`,{state:{projectIndex:e.projectIndex,userIndex:e.userIndex,onViewEntry:e.onViewEntry,onForget:e.onForget}});return;case`keybindingPanel`:s().navigate(`/dialog/keybindings`,{state:{overrides:e.overrides,onSave:e.onSave,onSaveReplace:e.onSaveReplace,onReset:e.onReset,onResetAll:e.onResetAll}});return;case`shortcutsPanel`:s().navigate(`/dialog/shortcuts`,{state:{bindings:e.shortcuts,onSave:e.onSave,onDelete:e.onDelete}});return;case`fileViewer`:s().navigate(`/viewer/file`,{state:{path:e.path,content:e.content,preTruncated:e.preTruncated,onDismiss:e.onDismiss}});return;case`helpViewer`:s().navigate(`/viewer/help`,{state:{title:e.title,lines:e.lines,onDismiss:e.onDismiss}});return;case`progress`:{let t=s();c={title:e.title,phases:e.phases,phaseIndex:0,phaseStatuses:[`active`,`pending`,`pending`,`pending`],percent:0,detail:e.phases[0]??``,status:`running`,onDismiss:()=>{c=null}},t.navigate(`/dialog/progress`,{state:c});return}case`wizard`:{let t=s();if(t?.currentPath===`/dialog/wizard`)return;t?.navigate(`/dialog/wizard`,{state:{...e,onDismiss:()=>{t.navigate(`/`,{reset:!0}),e.onDismiss?.()},onComplete:()=>{t.navigate(`/`,{reset:!0}),e.onComplete?.()}}});return}case`a2uiForm`:{let t=s();t.navigate(`/dialog/a2ui-form`,{state:{component:e.component,onAction:(n,r,i)=>{t.goBack(),e.onAction(n,r,i)},onDismiss:()=>{t.goBack()}}});return}default:return e}}),togglePane:(e,r)=>{let a=s();if(!a)return;let o=e=>a.currentPath===e||a.currentPath.startsWith(e+`/`),c=e=>{a.currentPath===e?a.goBack():a.navigate(`/`,{reset:!0})};switch(e){case`history`:gu()?.();return;case`backgroundTasks`:{let e=`/pane/delegates`;r??!o(e)?a.navigate(e):(c(e),t.setState({backgroundOutput:null}),i());return}case`draftPane`:{let e=`/pane/draft`;r??!o(e)?a.navigate(e):c(e);return}case`queuePane`:{let e=`/pane/queue`;r??!o(e)?a.navigate(e):c(e);return}case`notifications`:r??a.currentPath!==`/pane/notifications`?a.navigate(`/pane/notifications`):(a.goBack(),n.setState({notifications:n.getState().notifications.map(e=>({...e,read:!0}))}));return;case`schedulePane`:r??a.currentPath!==`/pane/schedule`?a.navigate(`/pane/schedule`):a.goBack();return;case`perf`:r??a.currentPath!==`/pane/perf`?a.navigate(`/pane/perf`):a.goBack();return;case`cacheStats`:r??a.currentPath!==`/pane/cache`?a.navigate(`/pane/cache`):a.goBack();return;case`compactionLog`:{let e=`/pane/compaction-log`;r??!o(e)?a.navigate(e):c(e);return}case`gallery`:r??a.currentPath!==`/pane/gallery`?a.navigate(`/pane/gallery`):a.goBack();return;case`proxy`:r??a.currentPath!==`/pane/proxy`?a.navigate(`/pane/proxy`):a.goBack();return;case`prompts`:{let e=`/pane/prompts`;r??!o(e)?a.navigate(e):c(e);return}default:return e}},getNotifyStats:e.getNotifyStats,isFullScreenPaneActive:()=>a(),getCurrentPath:()=>s()?.currentPath??`/`,isForcedUpgradeActive:()=>e.taskStore.getState().forcedUpgrade!==null,openAlert:e=>{r.alert=()=>e.onOk?.(),s().navigate(`/dialog/alert`,{state:{title:e.title,message:e.message,okLabel:e.okLabel}})},openPrompt:e=>new Promise(t=>{r.prompt=t,s().navigate(`/dialog/prompt`,{state:{title:e.title,message:e.message,placeholder:e.placeholder,initialValue:e.initialValue,submitLabel:e.submitLabel,cancelLabel:e.cancelLabel}})}),updateProgress(e){if(!c)return;let t=s();if(!t){c=null;return}c={...c,...e},t.navigate(`/dialog/progress`,{replace:!0,state:c})}}}function i_(e){let{taskStore:t,state:n,notify:r,showToast:i,getRouter:a=P}=e;return{startShellExecution:e=>{n.shellTimer&&clearTimeout(n.shellTimer),t.setState({shellExecution:{command:e,output:``,status:`running`,exitCode:null}}),a()?.navigate(`/pane/shell`),r()},appendShellOutput:e=>{t.getState().shellExecution&&(t.setState({shellExecution:{...t.getState().shellExecution,output:t.getState().shellExecution.output+e}}),r())},finishShellExecution:(e,n,i)=>{t.getState().shellExecution&&(t.setState({shellExecution:{...t.getState().shellExecution,status:e===null?`error`:`done`,exitCode:e,terminated:i,output:n?t.getState().shellExecution.output+n:t.getState().shellExecution.output}}),r())},dismissShellExecution:()=>{n.shellTimer&&clearTimeout(n.shellTimer),t.setState({shellExecution:null}),a()?.currentPath===`/pane/shell`&&a()?.goBack(),n.shellTimer=null,r()},copyShellOutput:()=>{let e=t.getState().shellExecution;e&&(Yn(e.output),i(B.t(`shell.copiedTitle`),B.t(`shell.copiedBody`)))},getShellExecutionSnapshot:()=>{let e=t.getState().shellExecution;return e?{command:e.command,output:e.output,exitCode:e.exitCode,terminated:e.terminated}:null}}}function a_(e){let{notificationStore:t,state:n,counters:r,notify:i,getRouter:a=P}=e;return{showToast:(e,o)=>{n.toastTimer&&clearTimeout(n.toastTimer);let s={id:++r.toast,title:e,content:o};t.setState({toast:s}),qr(a(),Ir,!0),n.toastTimer=setTimeout(()=>{t.setState({toast:null}),n.toastTimer=null,qr(a(),Ir,!1),i()},km),i()},showRetryDialog:(e,n,r,o,s,c,l)=>{t.setState({retryCountdown:{attempt:e,max:n,delayMs:r,accelerate:o,reason:c,onExpired:()=>{t.setState({retryCountdown:null}),qr(a(),Rr,!1),i(),s()},onStop:l?()=>{t.setState({retryCountdown:null}),qr(a(),Rr,!1),i(),l()}:void 0}}),qr(a(),Rr,!0),i()},clearRetryDialog:()=>{t.setState({retryCountdown:null}),qr(a(),Rr,!1),i()},showErrorRetry:e=>{let n=e=>()=>{t.setState({errorRetry:null}),qr(a(),zr,!1),i(),e()};t.setState({errorRetry:{...e,actions:e.actions.map(e=>({...e,run:n(e.run)})),focusIndex:0,exhausted:e.exhausted??!1,onExpired:n(e.onExpired),onCancel:n(e.onCancel)}}),qr(a(),zr,!0),i()},clearErrorRetry:()=>{t.setState({errorRetry:null}),qr(a(),zr,!1),i()},pushNotification:(e,n,a=`system`,o=`info`)=>{t.setState({notifications:[{id:++r.notify,source:a,level:o,title:e,message:n,timestamp:Date.now(),read:!1},...t.getState().notifications.slice(0,49)]}),i()},dismissNotification:e=>{t.setState({notifications:t.getState().notifications.filter(t=>t.id!==e)}),t.getState().notifications.length===0&&a()?.goBack(),i()},markAllNotificationsRead:()=>{t.setState({notifications:t.getState().notifications.map(e=>({...e,read:!0}))}),i()}}}function o_(e){let{taskStore:t,messageStoreHandle:n,counters:r,pendingSteerMsgIds:i,scrollbackMode:a,commitToHistory:o,scanA2uiButtons:s,notify:c}=e;return{setPendingEcho:(e,r)=>{if(t.setState({pendingEcho:{text:e,mode:r}}),!a){let e=n.store.getState().messages.at(-1);e?.id?n.patchById(e.id,{streaming:!0}):n.patchLast({streaming:!0})}c()},clearPendingEcho:()=>{let e=t.getState().pendingEcho;if(e){if(a&&(o({role:`user`,content:e.text}),s()),t.setState({pendingEcho:null}),!a){let e=n.store.getState().messages.at(-1);e?.id?n.patchById(e.id,{streaming:!1}):n.patchLast({streaming:!1})}c()}},withdrawPendingEcho:()=>{if(t.getState().pendingEcho){if(t.setState({pendingEcho:null}),!a){let e=`u-${r.msg}`,t=n.store.getState().messages.findLastIndex(t=>t.id===e);if(t!==-1){let e=[...n.store.getState().messages];e.splice(t,1),n.store.setState({messages:e})}else n.removeLast()}c()}},setPendingSteer:(e,o)=>{if(t.setState({pendingSteers:[...t.getState().pendingSteers,{text:e,id:o}]}),!a){r.msg++;let t=`u-${r.msg}`;i.set(o,t),n.append({role:`user`,content:e,streaming:!0,id:t},t)}c()},commitPendingSteer:e=>{let r=t.getState().pendingSteers,l=r.find(t=>t.id===e);if(l){if(a)o({role:`user`,content:l.text}),s();else{let t=i.get(e);t&&(n.patchById(t,{streaming:!1}),i.delete(e))}t.setState({pendingSteers:r.filter(t=>t.id!==e)}),c()}},withdrawPendingSteer:e=>{let r=t.getState().pendingSteers;if(r.some(t=>t.id===e)){if(t.setState({pendingSteers:r.filter(t=>t.id!==e)}),!a){let t=i.get(e);if(t){let r=n.store.getState().messages.filter(e=>e.id!==t);n.store.setState({messages:r}),i.delete(e)}}c()}},clearPendingSteers:()=>{let e=t.getState().pendingSteers;if(e.length!==0){if(a){for(let t of e)o({role:`user`,content:t.text});s()}else for(let t of e){let e=i.get(t.id);e&&(n.patchById(e,{streaming:!1}),i.delete(t.id))}t.setState({pendingSteers:[]}),c()}}}}function s_(e){let{streamStore:t,streamTextCoalescer:n,streamThinkingCoalescer:r,outputTokensThrottle:i,perfStore:a,compactionLogStore:o,drainQueue:s,getRouterRef:c,notify:l}=e;return{pushEngineEvent:e=>{switch(e.kind){case`agentProcessing`:t.setState({processing:e.value}),e.value||s();break;case`streamingText`:n.push(e.text,e.text===``);break;case`streamingThinking`:r.push(e.text,e.text===``);break;case`activeTool`:t.setState({activeTool:e.name});break;case`spinnerMode`:t.setState(e.mode===`requesting`?{spinnerMode:e.mode,outputTokensThisTurn:0}:{spinnerMode:e.mode});break;case`outputTokensThisTurn`:i.push(e.n);break;case`maxOutputTokens`:t.setState({maxOutputTokens:e.n});break;case`toolBudget`:t.setState({toolTurnCount:e.toolTurnCount,maxToolTurns:e.maxToolTurns,promptOutputTokens:e.outputTokens??0,promptOutputTokenBudget:e.outputTokenBudget??0});break;case`perf`:{let t=!1;e.memory&&(a.setMemory(e.memory),t=!0),e.notify&&(a.setNotify(e.notify),t=!0),e.pluginMetrics&&(a.setPluginMetrics(e.pluginMetrics),t=!0),e.indicatorLevel&&a.setIndicatorLevel(e.indicatorLevel),t&&l();break}case`compactionLog`:switch(e.entryKind){case`compact`:o.recordCompaction(e.before,e.after,e.summary);break;case`prune`:o.recordPrune(e.tokensSaved,e.prunedCount??0);break;case`history_capped`:o.recordHistoryCapped(e.removedCount);break}c()?.currentPath.startsWith(`/pane/compaction-log`)&&l();break}}}}function c_(e){let{modalHandleMethods:t,permResolvers:n,counters:r,taskStore:i,getRouterRef:a,notify:o,onConfirmResolve:s}=e;return{...t,resolveConfirm:e=>{s(e)},requestPermission:e=>{let t=`perm-${++r.perm}`;return new Promise(r=>{n.set(t,r);let s={id:t,tool:e.tool,input:e.input,risk:e.risk,description:e.description,alwaysAllowLabel:e.alwaysAllowLabel};i.setState({pendingPermission:s}),o(),a()?.navigate(`/dialog/permission`,{state:s})})}}}function l_(e){let{pendingMethods:t,restoreInputRef:n,pasteBridgeRef:r}=e;return{...t,restoreInputText:e=>{n.current?.fill(e)},hydratePaste:e=>{r.current?.hydrate(e)},exportPaste:()=>r.current?.export()??null}}function u_(e){let{lifecycleFlags:t,scrollbackBuffer:n,streamTextCoalescer:r,streamThinkingCoalescer:i,notifyScheduler:a,state:o,registryUnregisterAll:s,unmount:c,windowMode:l,scopedViewport:u,hasHistoryRef:d,resetStreamController:f,messageStoreHandle:p,scrollStoreHandle:m,streamStoreHandle:h,taskStoreHandle:g,notificationStoreHandle:_,perfStore:v,contextStore:y,budgetStore:b,taskStore:x,notificationStore:S,a2uiButtonsRef:C,resetStatusWidgetBreakers:w,getRouterRef:T,overlayPaths:E,syncOverlayRoute:ee,notify:D,i18next:te,detectLanguage:ne,setLanguage:O,getThemeRef:k,setTerminalTitle:re}=e;return{stop:()=>{if(!t.stopped){t.stopped=!0,t.unmounted=!0,e.detachSessionSource?.(),s();try{n.flush()}catch{}r.cancel(),i.cancel(),a.cancel(),o.toastTimer&&=(clearTimeout(o.toastTimer),null),c(),e.onStop?.()}},clearSession:()=>{l||n.write(u?`\x1B[2J\x1B[H`:`\x1B[2J\x1B[3J\x1B[H`),d.set(!1),f(),p.reset(),m.toBottom(),h.reset(),g.reset(),_.reset(),v.reset(),y.reset(),b.reset(),x.setState({tasks:[]}),x.setState({tasksTitle:void 0}),x.setState({turnBoundaries:[]}),x.setState({editedFiles:[]}),x.setState({subagentsAccum:new Map}),S.setState({toast:null}),S.setState({retryCountdown:null}),S.setState({errorRetry:null});let e=T();if(e)for(let t of E)ee(e,t,!1);S.setState({providerUsage:null}),o.toastTimer&&=(clearTimeout(o.toastTimer),null),C.current=[],s(),w(),e?.currentPath!==`/home`&&e?.navigate(`/home`,{reset:!0}),D()},setLanguage:e=>{let t=e===`auto`?ne():e;return te.changeLanguage(t),O(t),D(),t},setPresetSelection:e=>{k()?.setPresetSelection(e)},setTerminalTitle:e=>re(e)}}function d_(e){let{messageStoreHandle:t,notify:n}=e,r=null,i=()=>{let e=r;e&&(r=null,e.stop())};return{attachSessionSource:async e=>{if(r)throw Error(`attachSessionSource: a session data source is already attached`);return r={stop:await e.start({messageStore:{setState:e=>t.store.setState(e)}})},n(),i},detachSessionSource:i}}function f_(e){let{scrollbackMode:t,commitToHistory:n,commitManyToHistory:r,messageStoreHandle:i,counters:a,getTurnMessagesFor:o,taskStore:s,notify:c,scanA2uiButtons:l}=e;return{pushMessage:e=>{if(t){n(e),c(),l();return}a.msg++,i.append(e,`m-${a.msg}`),c(),l()},pushMessages:e=>{if(e.length!==0){if(t){r(e),c(),l();return}i.appendMany(e,()=>(a.msg++,`m-${a.msg}`)),c(),l()}},echoUserInput:(e,r)=>{let o=r?.pending===!0;if(t){if(o)return;n({role:`user`,content:e}),l();return}a.msg++;let s=`u-${a.msg}`;i.append({role:`user`,content:e,streaming:o,id:s},s),c(),l()},getTurnMessages:o,getTurnBoundaries:()=>s.getState().turnBoundaries,getEditedFiles:()=>s.getState().editedFiles}}function p_(e){let{streamMethods:t,taskStore:n,notificationStore:r,notificationMethods:i,getRouterRef:a,syncOverlayRoute:o,overlayPause:s,drainQueue:c,notify:l}=e;return{pushEngineEvent:t.pushEngineEvent,hasQueuedFollowUp:()=>n.getState().queued.length>0,takeLastQueuedFollowUp:()=>{let e=n.getState().queued,t=e.at(-1);if(t)return n.setState({queued:e.slice(0,-1)}),l(),t},enqueueFollowUp:(e,t=`send`)=>{n.setState({queued:[...n.getState().queued,{text:e,mode:t}]}),l(),c()},setPauseDialog:e=>{r.setState({pauseDialog:e}),o(a(),s,!!e),l()},showRetryDialog:i.showRetryDialog,clearRetryDialog:i.clearRetryDialog,showErrorRetry:i.showErrorRetry,clearErrorRetry:i.clearErrorRetry}}function m_(e){let{modalHandleMethods:t,taskStore:n,getRouterRef:r,syncOverlayRoute:i,overlayServices:a,flushScrollbackIfIdle:o,notify:s}=e;return{togglePane:t.togglePane,setServices:e=>{i(r(),a,e),s()},switchToSubagentContext:e=>{n.setState({subagentContext:e});let t=r();e&&t?.currentPath!==`/subagent`&&t?.navigate(`/subagent`),o(),s()},toggleEditedFiles:e=>{if(n.getState().editedFiles.length===0)return;let t=r();if(!t)return;let i=`/pane/edited-files`,a=t.currentPath===i||t.currentPath.startsWith(i+`/`),o=e??!a;o&&!a?t.navigate(i):!o&&a&&t.currentPath===i&&t.goBack()},clearEditedFiles:()=>{n.setState({editedFiles:[]}),s()},removeQueuedAt:e=>{n.setState({queued:n.getState().queued.filter((t,n)=>n!==e)}),s()},clearQueue:()=>{n.setState({queued:[]}),s()},moveQueuedItem:(e,t)=>{let r=e,i=e+t;if(i<0||i>=n.getState().queued.length||r<0||r>=n.getState().queued.length)return;let a=[...n.getState().queued],[o]=a.splice(r,1);o&&a.splice(i,0,o),n.setState({queued:a}),s()}}}function h_(e){let{taskStore:t,taskStoreHandle:n,registerPlugin:r,registryUnregister:i,computeStalePluginIds:a,getRegistrySnapshot:o,getStatusItems:s,getStatusWidgets:c,resetStatusWidgetBreakers:l,registryRef:u,a2uiButtonsRef:d,subagentRestoreFields:f,notify:p}=e;return{setPluginRegistrations:e=>{let n=new Set;for(let t of e)n.add(t.pluginId),r(t.pluginId,t);for(let e of a(n,o()))i(e);l(),t.setState({pluginStatusItems:s(),statusWidgets:c()}),p()},unregisterPluginSource:e=>{i(e),l(),t.setState({pluginStatusItems:s(),statusWidgets:c()}),p()},setPluginStatusItems:e=>{n.actions.setPluginStatusItems(e.map(e=>({id:e.icon,text:e.text})))},setCommands:e=>{t.setState({commands:e}),r(`cli-commands`,{pluginId:`cli-commands`,commands:[...e]})},registerArgumentSuggester:(e,t)=>{u?.current&&u.current.registerArgumentSuggester(e,t)},setA2uiButtons:e=>{d.current=e},addSubagent:e=>{let n=new Map(t.getState().subagentsAccum);n.set(e.id,{id:e.id,command:e.name,type:`agent-session`,startedAt:e.startedAt??Date.now(),...f(e.status)}),t.setState({subagentsAccum:n}),p()},getSubagents:()=>t.getState().subagentsAccum,clearSubagents:()=>{t.setState({subagentsAccum:new Map}),p()}}}function g_(e){let{notificationMethods:t,notifyScheduler:n,taskStore:r,modalHandleMethods:i,shellMethods:a,contextStore:o,getRouterRef:s,scrollStoreHandle:c}=e;return{pushNotification:t.pushNotification,dismissNotification:t.dismissNotification,markAllNotificationsRead:t.markAllNotificationsRead,getNotifyStats:()=>n.getStats(),getCurrentPath:()=>s()?.currentPath??`/`,isForcedUpgradeActive:()=>r.getState().forcedUpgrade!==null,isFullScreenPaneActive:()=>i.isFullScreenPaneActive(),getShellExecutionSnapshot:a.getShellExecutionSnapshot,addContextTurn:e=>o.addTurn(e),markContextTurns:e=>o.markTurns(e),showToast:t.showToast,setTopView:e=>{s()?.navigate(`/`,{reset:!0}),c.toBottom(),c.setTotalLines(0)}}}function __(e){let t=e.intervalMs??5e3,n=e.minIntervalMs??2e3,{stdout:r,enabled:i}=e,a=null,o=0,s=()=>{try{r.write(`\x1B]11;?\x07`),o=Date.now()}catch{}};return{start:()=>{i&&r.isTTY&&(a||(s(),a=setInterval(s,t),a.unref?.()))},stop:()=>{a&&=(clearInterval(a),null)},pollNow:()=>{i&&r.isTTY&&(Date.now()-o<n||s())}}}function v_(e,t,n,r,i){return{onPermissionDecision:(e,n,i)=>{let a=t.get(e);t.delete(e),r.setState({pendingPermission:null}),P()?.goBack(),a?.({approved:n,mode:i})},onSelectResolve:e=>{let t=n.select;n.select=null,P()?.goBack(),t?.(e)},onInputResolve:e=>{let t=n.input;t&&(n.input=null,P()?.currentPath===`/dialog/input`&&P()?.goBack(),t(e))},onOnboardingResolve:e=>{n.onboarding?.(e)},onInputAction:()=>{let e=n.inputAction;e?.()},onQuestionsResolve:(e,t)=>{let r=n.questions;r&&(i?.(!1),n.questions=null,P()?.currentPath===`/dialog/questions`&&P()?.goBack(),r(e,t))},onConfirmResolve:(e,t)=>{let r=n.confirm,i=n.cancel,a=n.extra;n.confirm=null,n.cancel=null,n.extra=null,P()?.currentPath===`/dialog/confirm`&&P()?.goBack(),!(!r&&!i&&!a)&&(t?a?.():e?r?.():i?.())},onAlertResolve:()=>{let e=n.alert;n.alert=null,P()?.goBack(),e?.()},onPromptResolve:e=>{let t=n.prompt;n.prompt=null,P()?.goBack(),t?.(e)},getTurnMessagesFor:t=>{let n=r.getState().turnBoundaries,i=e.getMessages(),a=t>1?n[t-2]??0:0,o=n[t-1]??i.length;return i.slice(a,o)}}}function y_(e,t,n,r,i){return()=>{if(t()||i.getState().queued.length===0)return;let[e,...a]=i.getState().queued;i.setState({queued:a}),n(),queueMicrotask(()=>r?.(e.text,e.mode))}}function b_(e){let[,t]=K(0);V.useEffect(()=>{let n=()=>t(e=>e+1);return e.state.listener=n,()=>{e.state.listener===n&&(e.state.listener=null)}},[]);let n=V.useCallback(()=>{Ql(),e.taskStore.setState({backgroundOutput:null}),e.opts.onBackgroundOutputClose?.(),e.flushScrollbackIfIdle(),e.notify()},[]),r=V.useCallback(()=>{P()?.goBack(),e.taskStore.setState({backgroundOutput:null}),e.opts.onBackgroundOutputClose?.(),e.flushScrollbackIfIdle(),e.notify()},[]),i=V.useCallback(()=>{P()?.currentPath===`/subagent`&&P()?.goBack(),e.opts.onSubagentExit?.(),e.taskStore.setState({subagentContext:null}),e.flushScrollbackIfIdle(),e.notify()},[]),a=V.useCallback(()=>{e.taskStore.getState().queued.length!==0&&(e.taskStore.setState({queued:e.taskStore.getState().queued.slice(0,-1)}),e.notify())},[]),o=V.useCallback(()=>{P()?.currentPath===`/dialog/info`&&P()?.goBack(),e.notify()},[]),s=V.useCallback(()=>{P()?.currentPath===`/dialog/memory`&&P()?.goBack(),e.notify()},[]),c=V.useCallback(()=>{P()?.currentPath===`/dialog/keybindings`&&P()?.goBack(),e.notify()},[]),l=V.useCallback(()=>{P()?.currentPath===`/dialog/shortcuts`&&P()?.goBack(),e.notify()},[]),u=V.useCallback(()=>{P()?.navigate(`/pane/context/detail`)},[]),d=V.useCallback(()=>{P()?.currentPath===`/pane/context/detail`&&P()?.goBack()},[]),f=V.useCallback(()=>{let e=P();e?.currentPath.startsWith(`/pane/context`)&&e.navigate(`/`,{reset:!0})},[]),p=V.useCallback(()=>{let e=P();e&&(e.currentPath===`/pane/notifications`?e.goBack():e.navigate(`/pane/notifications`))},[]),m=V.useCallback(t=>{e.notificationStore.setState({notifications:e.notificationStore.getState().notifications.filter(e=>e.id!==t)}),e.notificationStore.getState().notifications.length===0&&P()?.goBack()},[]),h=V.useCallback(()=>{e.notificationStore.setState({notifications:e.notificationStore.getState().notifications.map(e=>({...e,read:!0}))}),P()?.goBack()},[]),g=V.useCallback(()=>{e.opts.onSubmit?.(`/upgrade`,`send`)},[]),_=V.useCallback(()=>{e.stopRef.current?.()},[]),v=V.useCallback((t,n)=>{e.state.toastTimer&&clearTimeout(e.state.toastTimer);let r={id:++e.toastCounterRef.current,title:t,content:n};e.notificationStore.setState({toast:r}),qr(P(),Ir,!0),e.state.toastTimer=setTimeout(()=>{e.notificationStore.setState({toast:null}),e.state.toastTimer=null,qr(P(),Ir,!1),e.notify()},km),e.notify()},[]),y=V.useCallback(()=>{e.state.toastTimer&&(clearTimeout(e.state.toastTimer),e.state.toastTimer=null),e.notificationStore.getState().toast&&(e.notificationStore.setState({toast:null}),qr(P(),Ir,!1),e.notify())},[]),b=e.scrollbackMode?V.useCallback(t=>{e.inkWriteRef.current=t},[]):void 0,x=e.opts.welcome?.cwd?V.useCallback(async t=>{let{content:n,truncated:r}=await en(fn(e.opts.welcome.cwd,t));return{content:n,truncated:r}},[]):void 0,S=V.useCallback(()=>{if(e.taskStore.getState().editedFiles.length===0)return;let t=P();if(!t)return;let n=`/pane/edited-files`;t.currentPath===n||t.currentPath.startsWith(n+`/`)?t.navigate(`/`,{reset:!0}):t.navigate(n,{replace:!0})},[]),C=V.useCallback(()=>{if(e.taskStore.getState().subagentsAccum.size===0)return;let t=P();t&&(t.currentPath===`/pane/subagents`?t.navigate(`/`,{reset:!0}):t.navigate(`/pane/subagents`,{replace:!0}))},[]),w=V.useCallback(()=>{if(e.taskStore.getState().scheduleTasks.length===0)return;let t=P();t&&(t.currentPath===`/pane/schedule`?t.navigate(`/`,{reset:!0}):t.navigate(`/pane/schedule`,{replace:!0}))},[]),T=V.useCallback(e=>{let t=P();if(!t)return;let n=`/pane/draft`,r=t.currentPath===n||t.currentPath.startsWith(n+`/`),i=e??!r;i&&!r?t.navigate(n,{replace:!0}):!i&&r&&t.navigate(`/`,{reset:!0})},[]),E=V.useCallback(e=>{let t=P();if(!t)return;let n=`/pane/queue`,r=t.currentPath===n||t.currentPath.startsWith(n+`/`),i=e??!r;i&&!r?t.navigate(n,{replace:!0}):!i&&r&&t.navigate(`/`,{reset:!0})},[]),ee=V.useCallback(()=>{let e=P();if(!e)return;let t=`/pane/prompts`;e.currentPath===t||e.currentPath.startsWith(t+`/`)?Ql():e.navigate(t,{replace:!0})},[]),D=V.useCallback(t=>{e.opts.onDraftSave?.(t)},[]),te=V.useCallback(t=>{let n=e.taskStore.getState().drafts[t];n&&e.opts.onDraftDelete?.(n.id)},[]),ne=V.useCallback(t=>{e.opts.onDraftDeleteMany?.(t)},[]),O=V.useCallback(t=>{e.taskStore.setState({queued:e.taskStore.getState().queued.filter((e,n)=>n!==t)}),e.notify()},[]),k=V.useCallback((t,n)=>{let r=t,i=t+n;if(i<0||i>=e.taskStore.getState().queued.length||r<0||r>=e.taskStore.getState().queued.length)return;let a=[...e.taskStore.getState().queued],[o]=a.splice(r,1);o&&a.splice(i,0,o),e.taskStore.setState({queued:a}),e.notify()},[]),re=V.useCallback((t,n)=>{let r=e.taskStore.getState().queued;if(t<0||t>=r.length)return;let i=[...r],a=i[t];a&&(i[t]={...a,text:n}),e.taskStore.setState({queued:i}),e.notify()},[]),A=V.useCallback((t,n)=>{let r=e.taskStore.getState().queued;if(t<0||t>=r.length)return;let i=r[t].mode;e.taskStore.setState({queued:r.filter((e,n)=>n!==t)}),e.notify(),e.opts.onQueueSendNow?.(n,i)},[]),ie=V.useCallback(t=>{let n=e.notificationStore.getState().errorRetry;n&&(e.notificationStore.setState({errorRetry:{...n,focusIndex:t}}),e.notify())},[]),j=V.useCallback(t=>{let n=e.notificationStore.getState().pulseSurvey;n&&(e.notificationStore.setState({pulseSurvey:{...n,...t}}),e.notify())},[]),ae=V.useCallback(()=>{if(e.taskStore.getState().backgroundTasks.length===0)return;let t=P();if(!t)return;let n=`/pane/delegates`;t.currentPath===n||t.currentPath.startsWith(n+`/`)?(t.navigate(`/`,{reset:!0}),e.taskStore.setState({backgroundOutput:null}),e.flushScrollbackIfIdle()):t.navigate(n,{replace:!0})},[]),oe=V.useCallback(()=>{e.state.shellTimer&&clearTimeout(e.state.shellTimer),e.taskStore.setState({shellExecution:null}),e.state.shellTimer=null,P()?.currentPath===`/pane/shell`&&P()?.goBack(),e.notify()},[]),M=V.useCallback(()=>{let t=e.taskStore.getState().shellExecution;t&&(Yn(t.output),v(B.t(`shell.copiedTitle`),B.t(`shell.copiedBody`)))},[]);return V.useEffect(()=>{let t=null,n=()=>{t&&clearTimeout(t),t=setTimeout(()=>{let t=e.opts.columns||(e.stdout.columns>0?e.stdout.columns:process.stdout.columns>0?process.stdout.columns:80),n=e.opts.rows||(e.stdout.rows>0?e.stdout.rows:process.stdout.rows>0?process.stdout.rows:24);(t!==e.columnsRef.current||n!==e.rowsRef.current)&&(e.columnsRef.current=t,e.rowsRef.current=n,e.notify())},100)};return e.stdout.on(`resize`,n),()=>{t&&clearTimeout(t),e.stdout.off(`resize`,n)}},[]),V.createElement(dg,{columns:e.columnsRef.current,rows:e.rowsRef.current,registerWrite:e.scrollbackMode?b:void 0,maxPreviewRows:e.scrollbackMode?1:void 0,hasHistory:e.hasHistoryRef.current,messages:e.messageStore.getState().messages,scrollStore:e.scrollStore,loadHistory:e.opts.loadHistory,messageStore:e.messageStoreHandle,windowMode:e.windowMode,scrollbackMode:e.scrollbackMode,shadow:e.opts.shadow??!1,language:e.languageRef.current,systemTheme:e.systemTheme,themeRegistry:e.themeRegistry,presetSelection:e.presetSelection,keybindingOverrides:e.opts.keybindingOverrides,onCyclePermissionMode:e.opts.onCyclePermissionMode,pluginInput:e.opts.pluginInput,readFileContent:x,getTurnMessages:e.getTurnMessagesFor,editedFilesOpen:!1,onToggleEditedFiles:S,subagentsOpen:!1,onToggleSubagents:C,onToggleSchedule:w,initialHistory:e.opts.initialHistory,externalHistoryCommands:e.opts.externalHistoryCommands,onHistoryPush:e.opts.onHistoryPush,residencyGovernor:e.opts.residencyGovernor,resolveWholeFileDiff:e.opts.resolveWholeFileDiff,restoreInputRef:e.restoreInputRef,pasteBridgeRef:e.pasteBridgeRef,scheduleOpen:!1,draftOpen:!1,onToggleDraftPane:T,onDraftSave:D,onDraftDelete:te,onDraftDeleteMany:ne,onSigilSelect:e.opts.onSigilSelect,queueOpen:!1,onToggleQueuePane:E,onTogglePrompts:ee,onQueueDelete:O,onQueueMove:k,onQueueEditText:re,onQueueSendNow:A,pendingEcho:e.taskStore.getState().pendingEcho,onErrorRetryFocusChange:ie,onPulseSurveyChange:j,backgroundTasksOpen:!1,onToggleDelegates:ae,onBackgroundClose:n,onBackgroundKill:e.opts.onBackgroundKill,onBackgroundViewOutput:e.opts.onBackgroundViewOutput,onBackgroundOutputClose:r,onBackgroundApply:e.opts.onBackgroundApply,onBackgroundSwitch:e.opts.onBackgroundSwitch,onBackgroundDelete:e.opts.onBackgroundDelete,onExitSubagentContext:i,onPaneOwnsViewportChange:e.scrollbackMode?e.setPaneOwnsViewport:void 0,onFocusOwnerChange:e.scrollbackMode?e.setFocusOwnerForBuffer:void 0,onScrollActiveChange:e.setScrollActive,onDelegateSupply:e.opts.onDelegateSupply,welcome:e.opts.welcome,onSessionSelect:e.opts.onSessionSelect,budgetStore:e.budgetStore,contextStore:e.contextStore,notificationStore:e.notificationStoreHandle,perfStore:e.perfStore,onPerfDismiss:()=>{P()?.currentPath===`/pane/perf`&&P()?.goBack()},cacheStore:e.cacheStore,onCacheDismiss:()=>{P()?.currentPath===`/pane/cache`&&P()?.goBack()},proxyStore:e.proxyStore,proxyOpen:!1,onProxyDismiss:()=>{P()?.goBack()},onProxyOpenModal:e.proxyOpenModal,onProxySubmitUrl:e.opts.onProxySubmitUrl,onProxyToggleEnabled:e.opts.onProxyToggleEnabled,onProxyClear:e.opts.onProxyClear,compactionLogStore:e.compactionLogStore,onCompactionLogDismiss:()=>{let e=P();e?.currentPath.startsWith(`/pane/compaction-log`)&&e.navigate(`/`,{reset:!0})},galleryStore:e.galleryStore,onGalleryDismiss:()=>{P()?.currentPath===`/pane/gallery`&&P()?.goBack()},streamStore:e.streamStoreHandle,taskStore:e.taskStoreHandle,initialPath:e.opts.initialPath,onPerfRefresh:e.opts.onPerfRefresh,onSubmit:e.submitOrQueue,onInterrupt:e.opts.onInterrupt,onWithdrawPending:e.opts.onWithdrawPending,onWithdrawSteer:e.opts.onWithdrawSteer,onPopQueued:a,onPermissionDecision:e.onPermissionDecision,onSelectResolve:e.onSelectResolve,onInputResolve:e.onInputResolve,onOnboardingResolve:e.onOnboardingResolve,onInputAction:e.onInputAction,onQuestionsResolve:e.onQuestionsResolve,onConfirmResolve:e.onConfirmResolve,onAlertResolve:e.onAlertResolve,onPromptResolve:e.onPromptResolve,onInfoDismiss:o,onMemoryDismiss:s,onKeybindingPanelDismiss:c,onShortcutsDialogDismiss:l,onViewDetails:u,onBackToContextPane:d,onContextDismiss:f,notificationsOpen:!1,onToggleNotifications:p,onDismissNotification:m,onCloseNotifications:h,onUpgrade:g,onCancelUpgrade:_,onToast:v,onDismissToast:y,registryRef:e.registryRef,shellBackendRef:e.shellBackendRef,shellExecution:e.taskStore.getState().shellExecution,onShellAbort:e.opts.onInterrupt,onShellDismiss:oe,onShellCopyOutput:M,onShellAskAi:e.opts.onShellAskAi,a2uiButtons:e.a2uiButtonsRef.current,onA2uiAction:e.a2uiActionRef.current})}function x_(){let e=Buffer.alloc(0);return t=>{let n=F(t),r=e.length?Buffer.concat([e,n]):n;e=Buffer.alloc(0);let i=r.length;i>=2&&r[i-2]===27&&r[i-1]===91&&(e=Buffer.from(r.subarray(i-2)),i-=2);let a,o=[],s=0;for(;s<i;){if(r[s]===27&&r[s+1]===91&&(r[s+2]===73||r[s+2]===79)){a=r[s+2]===73,s+=3;continue}o.push(r[s]),s++}return{focused:a,rest:Buffer.from(o)}}}var S_=class{pending=null;feed(e){let t=F(e),n=this.pending?Buffer.concat([this.pending,t]):t;this.pending=null;let r=[],i=null,a=0;for(;a<n.length;){let e=n.indexOf(`\x1B]`,a,`latin1`);if(e<0){a<n.length&&r.push(n.slice(a));break}e>a&&r.push(n.slice(a,e));let t=n.indexOf(7,e),o=n.indexOf(`\x1B\\`,e,`latin1`),s=-1,c=0;if(t>=0&&(o<0||t<o)?(s=t,c=1):o>=0&&(s=o,c=2),s<0){let t=n.slice(e);t.length>64?r.push(t):this.pending=t;break}let l=C_(n.slice(e,s).toString(`latin1`));l&&(i=l),a=s+c}return{keys:r.length>0?Buffer.concat(r):Buffer.alloc(0),osc11:i}}};function C_(e){let t=e.match(/\]11;rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(!t)return null;let n=parseInt(t[1].slice(0,2),16),r=parseInt(t[2].slice(0,2),16),i=parseInt(t[3].slice(0,2),16);return Number.isNaN(n)||Number.isNaN(r)||Number.isNaN(i)?null:{r:n,g:r,b:i}}function w_(e,t,n){return .2126*e+.7152*t+.0722*n<128?`dark`:`light`}function T_(e){let{stdin:t,renderStdout:n,onInterrupt:r,onFocusChange:i,onTerminalBgDetected:a,onMouseWheel:o,onMouseDrag:s}=e,c=[],l=process.env.OTTO_TUI_MOUSE===`0`,u=(typeof o==`function`||typeof s==`function`)&&!!t.isTTY,d=u&&!l,f=u?Ug():null,p=d,m;if(d)try{n.write(Bg)}catch{}u&&(m=()=>{try{n.write(Vg)}catch{}},process.once(`exit`,m));let h=e=>{if(!u)return!1;if(e===p)return p;p=e;try{n.write(e?Bg:Vg)}catch{}return p},g=new S_,_=e=>{if(!a)return F(e);let{keys:t,osc11:n}=g.feed(e);return n&&a(w_(n.r,n.g,n.b)),t},v=e=>{if(!f)return _(e);let{wheels:t,drags:n,rest:r}=f(e);if(p){for(let e of t)o?.(e.delta);for(let e of n)s?.(e)}return _(r)},y=process.env.OTTO_TUI_KITTY===`1`&&!!t.isTTY,b,x=t;if(y){try{n.write(`\x1B[>1u`)}catch{}b=()=>{try{n.write(qg)}catch{}},process.once(`exit`,b);let e=Zg(),i=new xn;Object.assign(i,{isTTY:!0,setRawMode:e=>{try{t.setRawMode?.(e)}catch{}return i},ref:()=>{try{t.ref?.()}catch{}return i},unref:()=>{try{t.unref?.()}catch{}return i}});let a=t=>{let n=v(t);if(n.length===0)return;let a=e(n);a.includes(3)&&r?.(),i.write(a)};t.on(`data`,a),c.push({stream:t,fn:a}),x=i}let S=process.env.OTTO_TUI_FOCUS===`1`&&!!t.isTTY&&typeof i==`function`,C;if(S){try{n.write(`\x1B[?1004h`)}catch{}C=()=>{try{n.write(`\x1B[?1004l`)}catch{}},process.once(`exit`,C);let e=x,t=x_(),r=new xn;Object.assign(r,{isTTY:!0,setRawMode:t=>{try{e.setRawMode?.(t)}catch{}return r},ref:()=>{try{e.ref?.()}catch{}return r},unref:()=>{try{e.unref?.()}catch{}return r}});let a=e=>{let n=v(e);if(n.length===0)return;let{focused:a,rest:o}=t(n);a!==void 0&&i?.(a),o.length&&r.write(o)};e.on(`data`,a),c.push({stream:e,fn:a}),x=r}if(!y&&!S&&(a||d)){let e=x,t=new xn;Object.assign(t,{isTTY:!0,setRawMode:n=>(e.setRawMode?.(n),t),ref:()=>(e.ref?.(),t),unref:()=>(e.unref?.(),t)});let n=e=>{let n=v(e);n.length>0&&t.write(n)};e.on(`data`,n),c.push({stream:e,fn:n}),e.resume(),x=t}return{renderStdin:x,kittyOn:y,focusOn:S,mouseOn:d,kittyExitHandler:b,focusExitHandler:C,mouseExitHandler:m,setMouseEnabled:h,isMouseEnabled:()=>p,cleanup:()=>{for(let{stream:e,fn:t}of c)e.removeListener(`data`,t);c.length=0}}}const E_=12e3;async function D_(e){let{stdin:t,stdout:n,onStop:r}=e,i=Oc(e.maxFps??30),a=e.renderMaxFps??90;Ta();let o=e.columns||(n.columns>0?n.columns:process.stdout.columns>0?process.stdout.columns:80),s=e.rows||(n.rows>0?n.rows:process.stdout.rows>0?process.stdout.rows:24),c=e.language&&e.language!==`auto`?e.language:Et();Tt(c);let l=await _(),u=e.themeRegistry,d=e.presetSelection,f=process.env.OTTO_TUI_SCOPED_VIEWPORT!==`0`,p=bg(n),m=()=>Math.max(1,s-1);process.once(`exit`,()=>p.exit());let h=e.scrollback===!0||process.env.OTTO_TUI_SCROLLBACK===`1`,g=e.scrollback===!1||process.env.OTTO_TUI_SCROLLBACK===`0`,v=!h&&!g,y=rr()?nr(n):n;h&&!f&&(y=or(y));let b=e=>{y.write(e)},S=!1,{streamStoreHandle:C,streamStore:w,notificationStoreHandle:T,notificationStore:E,taskStoreHandle:ee,taskStore:D,messageStoreHandle:te,messageStore:ne,scrollStoreHandle:O,budgetStore:k,contextStore:re,perfStore:A,cacheStore:ie,proxyStore:j,compactionLogStore:ae,galleryStore:oe,completer:M,shellBackendRef:se,a2uiButtonsRef:ce,a2uiActionRef:N,scanA2uiButtons:le}=_g(e),ue={toastTimer:null,listener:null,shellTimer:null},F={current:null},de={current:null},fe=process.env.OTTO_TUI_PANE_BUFFER!==`0`,pe=`prompt`,me=()=>fe&&(D.getState().subagentContext!=null||D.getState().backgroundOutput!=null||D.getState().paneOwnsViewportFlag||pe!==`prompt`),he=vg({paneOwnsViewport:me,realWrite:e=>b(e)}),ge=()=>{me()||he.flush()},_e=e=>{let t=pe===`prompt`;pe=e,e===`prompt`&&!t&&ge()},ve=!0,ye=e=>{ve=e},be=e=>{D.setState({paneOwnsViewportFlag:e}),e||ge()},xe={msg:0,perm:0,toast:0,notify:0},Se=new Map,Ce=new Map,we={select:null,input:null,inputAction:null,questions:null,confirm:null,cancel:null,extra:null,alert:null,prompt:null,onboarding:null},I={current:null},Te={current:null},Ee=(e=>Te.current?Te.current.openModal(e):e.kind===`input`?Promise.resolve(null):void 0),De=jc({listener:()=>ue.listener?.(),intervalMs:i}),Oe=()=>De.immediate();ee.setNotify(Oe),T.setNotify(Oe);let{commitToHistory:ke,commitManyToHistory:Ae}=n_({scrollbackBuffer:he,getColumns:()=>o,getHasHistory:()=>S,setHasHistory:e=>{S=e},notify:Oe}),{streamTextCoalescer:je,streamThinkingCoalescer:Me,outputTokensThrottle:Ne,resetController:Pe}=e_({streamStore:w,messageStore:ne,messageStoreHandle:te,scrollbackBuffer:he,scrollbackMode:h,coalesceMs:i,getColumns:()=>o,getHasHistory:()=>S,setHasHistory:e=>{S=e},getMsgCounter:()=>xe.msg,incMsgCounter:()=>++xe.msg,notify:Oe}),Fe=()=>Qi(Zi(Yi(e.isAgentBusy,w.getState().processing),!!E.getState().errorRetry),!!e.isPaused?.()),Ie=(t,n,r)=>{let i=$i(t,n,r??!1,{processing:Fe(),isImmediateCommand:t=>e.isImmediateCommand?.(t)??!1,isInterruptCommand:t=>e.isInterruptCommand?.(t)??!1});if(i===`queue`){D.setState({queued:[...D.getState().queued,{text:t,mode:n}]}),Oe();return}e.onSubmit?.(t,n,i===`steer`?`steer`:`send`)},Le=y_(ue,Fe,Oe,e.onSubmit,D);ee.setEffects({syncForcedUpgradeRoute:e=>qr(P(),Vr,e),backgroundOutputRoute:e=>{e?P()?.navigate(`/pane/delegates/output`):P()?.currentPath===`/pane/delegates/output`&&P()?.goBack()},flushScrollbackIfIdle:ge,registerStatusItems:e=>Wo(`cli-status`,{pluginId:`cli-status`,statusItems:[...e]})}),T.setEffects({drainQueueOnResume:()=>Le(),syncPulseSurveyRoute:e=>qr(P(),Br,e)});let{onPermissionDecision:Re,onSelectResolve:ze,onInputResolve:Be,onOnboardingResolve:Ve,onInputAction:He,onQuestionsResolve:Ue,onConfirmResolve:We,onAlertResolve:Ge,onPromptResolve:Ke,getTurnMessagesFor:qe}=v_({getMessages:()=>ne.getState().messages},Ce,we,D,be),Je={state:ue,columnsRef:{get current(){return o},set current(e){o=e}},rowsRef:{get current(){return s},set current(e){s=e}},hasHistoryRef:{get current(){return S},set current(e){S=e}},inkWriteRef:{get current(){return b},set current(e){b=e}},toastCounterRef:{get current(){return xe.toast},set current(e){xe.toast=e}},languageRef:{get current(){return c},set current(e){c=e}},systemTheme:l,themeRegistry:u,presetSelection:d,stopRef:{},taskStore:D,notificationStore:E,messageStore:ne,streamStoreHandle:C,taskStoreHandle:ee,notificationStoreHandle:T,messageStoreHandle:te,budgetStore:k,contextStore:re,perfStore:A,cacheStore:ie,proxyStore:j,compactionLogStore:ae,galleryStore:oe,opts:e,notify:Oe,flushScrollbackIfIdle:ge,setPaneOwnsViewport:be,setFocusOwnerForBuffer:_e,setScrollActive:ye,getTurnMessagesFor:qe,submitOrQueue:Ie,onPermissionDecision:Re,onSelectResolve:ze,onInputResolve:Be,onOnboardingResolve:Ve,onInputAction:He,onQuestionsResolve:Ue,onConfirmResolve:We,onAlertResolve:Ge,onPromptResolve:Ke,proxyOpenModal:Ee,restoreInputRef:F,pasteBridgeRef:de,registryRef:I,shellBackendRef:se,a2uiButtonsRef:ce,a2uiActionRef:N,scrollbackMode:h,windowMode:v,scrollStore:O,stdout:n},L=()=>b_(Je),Ye=__({stdout:y,enabled:!0}),Xe=Wg(e=>{O.dispatchWheel(e)||pe===`prompt`&&ve&&O.scrollBy(e*3)}),R={current:null};nu(O.store,()=>R.current?.clear());let{renderStdin:Ze,kittyOn:Qe,focusOn:$e,mouseOn:et,kittyExitHandler:tt,focusExitHandler:nt,mouseExitHandler:rt,setMouseEnabled:it,isMouseEnabled:at,cleanup:ot}=T_({stdin:t,renderStdout:y,onInterrupt:e.onInterrupt,onFocusChange:e.onFocusChange,onMouseWheel:e=>Xe.push(e),onMouseDrag:e=>{R.current?.handleDrag(e)},onTerminalBgDetected:e=>{process.env.OTTO_DEBUG_THEME&&process.stderr.write(`[RFC-282] OSC detected: ${e} themeRef=${!!x()}\n`),x()?.setSystemTheme(e)}}),st=e.concurrent??process.env.OTTO_TUI_CONCURRENT===`1`;f&&p.enter();let ct=await jg(y);ct?.buffer.setMaxLineWidth(o),ct&&(R.current=Rg({buffer:ct.buffer,terminalRows:()=>m(),writeSelectionRepaint:e=>{if(e)try{y.write(e)}catch{}},writeClipboard:e=>{let t=Kg(e),n=!1;try{Yn(e),n=!0}catch{n=!1}return t||n},onCopied:(e,t)=>{let n=zg(e);t?(D.setState({clipboardChars:n,clipboardText:e,clipboardFailed:!1}),setTimeout(()=>{D.getState().clipboardChars===n&&D.setState({clipboardChars:0})},E_)):(D.setState({clipboardFailed:!0,clipboardChars:0}),setTimeout(()=>{D.getState().clipboardFailed&&D.setState({clipboardFailed:!1})},E_))}}),eu(R.current),ct.onDamage(e=>{R.current?.onFrameDamage(e)}));let{waitUntilExit:lt,unmount:ut}=Rt(V.createElement(L),{stdout:y,stdin:Ze,exitOnCtrlC:!1,maxFps:a,concurrent:st});st&&await new Promise(e=>{let t=Date.now()+1e3,n=()=>{ue.listener||Date.now()>t?e():setImmediate(n)};n()});let dt=Qg({stdin:t,stdout:n,renderStdout:y,kittyOn:Qe,kittyExitHandler:tt,focusOn:$e,focusExitHandler:nt,mouseOn:et,mouseExitHandler:rt,onInterrupt:e.onInterrupt,unmount:()=>ut(),terminalInputCleanup:ot});dt.setupRawInput(),Ye.start();let ft=()=>{Ye.pollNow();let e=n.columns>0?n.columns:o;ct?.buffer.setMaxLineWidth(e)};n.on(`resize`,ft),process.once(`exit`,()=>{n.removeListener(`resize`,ft),Ye.stop()});let pt={stopped:!1,unmounted:!1},mt=r_({taskStore:D,notificationStore:E,cacheStore:ie,proxyStore:j,resolvers:we,getNotifyStats:()=>De.getStats(),flushScrollbackIfIdle:ge,paneOwnsViewport:me,setPaneOwnsViewport:be});Te.current=mt;let z=i_({taskStore:D,state:ue,notify:Oe,showToast:(...e)=>wt.info.showToast(...e)}),ht=a_({notificationStore:E,state:ue,counters:xe,notify:Oe}),gt=l_({pendingMethods:o_({taskStore:D,messageStoreHandle:te,counters:xe,pendingSteerMsgIds:Se,scrollbackMode:h,commitToHistory:ke,scanA2uiButtons:le,notify:Oe}),restoreInputRef:F,pasteBridgeRef:de}),_t=d_({messageStoreHandle:te,notify:Oe}),vt=u_({lifecycleFlags:pt,scrollbackBuffer:he,streamTextCoalescer:je,streamThinkingCoalescer:Me,notifyScheduler:De,state:ue,registryUnregisterAll:Ko,unmount:ut,windowMode:v,scopedViewport:f,hasHistoryRef:{set:e=>{S=e}},resetStreamController:Pe,messageStoreHandle:te,scrollStoreHandle:O,streamStoreHandle:C,taskStoreHandle:ee,notificationStoreHandle:T,perfStore:A,contextStore:re,budgetStore:k,taskStore:D,notificationStore:E,a2uiButtonsRef:ce,resetStatusWidgetBreakers:lu,getRouterRef:P,overlayPaths:Gr,syncOverlayRoute:qr,notify:Oe,i18next:B,detectLanguage:Et,setLanguage:e=>{c=e},getThemeRef:x,setTerminalTitle:Gn,onStop:r,detachSessionSource:_t.detachSessionSource}),yt=m_({modalHandleMethods:mt,taskStore:D,getRouterRef:P,syncOverlayRoute:qr,overlayServices:Ur,flushScrollbackIfIdle:ge,notify:Oe}),bt=h_({taskStore:D,taskStoreHandle:ee,registerPlugin:Wo,registryUnregister:Go,computeStalePluginIds:Yo,getRegistrySnapshot:qo,getStatusItems:Zo,getStatusWidgets:$o,resetStatusWidgetBreakers:lu,registryRef:I,a2uiButtonsRef:ce,subagentRestoreFields:Eo,notify:Oe}),xt=g_({notificationMethods:ht,notifyScheduler:De,taskStore:D,modalHandleMethods:mt,shellMethods:z,contextStore:re,getRouterRef:P,scrollStoreHandle:O}),St=p_({streamMethods:s_({streamStore:w,streamTextCoalescer:je,streamThinkingCoalescer:Me,outputTokensThrottle:Ne,perfStore:A,compactionLogStore:ae,drainQueue:Le,getRouterRef:P,notify:Oe}),taskStore:D,notificationStore:E,notificationMethods:ht,getRouterRef:P,syncOverlayRoute:qr,overlayPause:Lr,drainQueue:Le,notify:Oe}),Ct=f_({scrollbackMode:h,commitToHistory:ke,commitManyToHistory:Ae,messageStoreHandle:te,counters:xe,getTurnMessagesFor:qe,taskStore:D,notify:Oe,scanA2uiButtons:le}),wt={modal:c_({modalHandleMethods:mt,permResolvers:Ce,counters:xe,taskStore:D,getRouterRef:P,notify:Oe,onConfirmResolve:We}),pending:gt,lifecycle:{...vt,..._t,toggleMouse:()=>{let e=it(!at());return wt.info.showToast(B.t(`mouse.toggleTitle`),e?B.t(`mouse.enabledBody`,{modifier:rf()}):B.t(`mouse.disabledBody`)),e}},messages:Ct,engine:St,panes:yt,plugins:bt,info:xt,shell:z,stores:{tasks:ee.actions,budget:{setBudget:k.setBudget},context:{setBudget:re.setBudget,addTurn:re.addTurn,markTurns:re.markTurns},cache:{setView:ie.setView},proxy:{setView:j.setView},notification:{setProviderUsage:T.setProviderUsage,setPausePending:T.setPausePending,setPaused:T.setPaused,setPulseSurvey:T.setPulseSurvey}}};return Je.stopRef.current=()=>wt.lifecycle.stop(),lt().then(()=>{pt.unmounted||(pt.unmounted=!0,dt.cleanup(),ct?.dispose(),ut(),p.active()||n.write(yg(m())),n.write(`\x1B[?25h`),p.exit())}),wt}function O_(){return{streamBuf:``,thinkBuf:``,turnStart:0,turnToolCount:0,lastTasks:[],messageIndex:0}}function k_(e,t){let n=[];e.forEach((e,t)=>{e?.role===`user`&&n.push(t)});let r=n.length,i=Math.max(t,r);if(r===0||i<=1)return[];let a=n[0],o=Array(i-1).fill(a);for(let e=0;e<r;e++){let t=i-r-1+e;t>=0&&t<o.length&&(o[t]=n[e])}return o}function A_(e){return e.filter(e=>e.status!==`done`&&e.status!==`skipped`&&e.status!==`failed`).length}function j_(e,t,n){if(t.length===0)return[...e];let r=[];e.forEach((e,t)=>{e?.role===`user`&&r.push(t)});let i=r.length,a=Math.max(n,i);if(i===0||a<=0)return[...e];let o=a-i+1,s=new Map;for(let e of t)s.set(e.turn,e);let c=new Map;for(let t of s.values()){if(t.turn<o||t.turn>a)continue;let n=t.turn-o,s=n+1<i?r[n+1]:e.length,{turn:l,...u}=t,d={role:`summary`,...u},f=c.get(s);f?f.push(d):c.set(s,[d])}if(c.size===0)return[...e];let l=[];for(let t=0;t<e.length;t++){l.push(e[t]);let n=c.get(t+1);n&&l.push(...n)}return l}function M_(e,t){let n=A_(t.lastTasks),r=e.stopReason??`completed`,i=r===`error`?`error`:r===`interrupted`?`interrupted`:n>0?`incomplete`:`done`,a={toolCount:t.turnToolCount,elapsedMs:t.turnStart>0?performance.now()-t.turnStart:0,tokensUsed:e.tokens??void 0,model:e.model||void 0,effort:e.effort||void 0,cacheHitRatio:e.cacheHitRatio??void 0};return i===`incomplete`?{...a,status:i,tasksDone:t.lastTasks.length-n,tasksTotal:t.lastTasks.length}:{...a,status:i}}function N_(e,t,n){let r=()=>{n.thinkBuf.trim()&&(t.pushMessage({role:`assistant`,content:[{type:`thinking`,thinking:n.thinkBuf}]}),n.messageIndex++),n.thinkBuf=``,t.pushEngineEvent({kind:`streamingThinking`,text:``})};switch(e.kind){case`prompt.start`:n.turnStart=performance.now(),n.turnToolCount=0,t.addTurnBoundary?.(n.messageIndex);return;case`prompt.end`:{n.thinkBuf.trim()&&(t.pushMessage({role:`assistant`,content:[{type:`thinking`,thinking:n.thinkBuf}]}),n.messageIndex++),n.streamBuf=``,n.thinkBuf=``,t.pushEngineEvent({kind:`streamingText`,text:``}),t.pushEngineEvent({kind:`streamingThinking`,text:``});let r={role:`summary`,...M_(e,n)};t.pushMessage(r),n.messageIndex++;return}case`stream.text.delta`:n.streamBuf+=e.delta,t.pushEngineEvent({kind:`streamingText`,text:n.streamBuf});return;case`stream.thinking.delta`:n.thinkBuf+=e.delta,t.pushEngineEvent({kind:`streamingThinking`,text:n.thinkBuf});return;case`stream.text.start`:r(),n.streamBuf=``;return;case`stream.text.end`:t.pushEngineEvent({kind:`streamingText`,text:``}),n.streamBuf=``;return;case`stream.thinking.start`:n.thinkBuf=``;return;case`stream.thinking.end`:r();return;case`tool.start`:t.pushEngineEvent({kind:`activeTool`,name:e.call.name});return;case`tool.end`:{if(t.pushEngineEvent({kind:`activeTool`,name:null}),n.turnToolCount++,e.suppressMessage)return;let r=e.call.arguments??{},i=r,a=i.command??i.path??i.file_path??i.pattern??i.query??JSON.stringify(r);t.pushMessage({role:`tool`,name:e.call.name,args:typeof a==`string`?a:JSON.stringify(a),argsObj:r,result:e.resultText,isError:e.isError}),n.messageIndex++;return}case`tasks.update`:n.lastTasks=e.tasks,t.setTasks(e.tasks,e.title);return;case`turn.budget`:t.pushEngineEvent({kind:`toolBudget`,toolTurnCount:e.toolTurnCount,maxToolTurns:e.maxToolTurns,outputTokens:e.outputTokens,outputTokenBudget:e.outputTokenBudget});return;case`delegate.update`:return}}function P_(e,t={}){for(let t of e){let e=t.role??`unknown`,n=t.content??[],r=Array.isArray(n)?n.filter(e=>e.type===`text`).map(e=>String(e.text??``)).join(`
|
|
108
|
-
`):String(n);if(e===`user`)process.stdout.write(`\x1b[34m▸ ${r}\x1b[0m\n`);else if(e===`assistant`){process.stdout.write(`${r}\n`);let e=t.tool_calls??[];for(let t of e){let e=t.function;process.stdout.write(`\x1b[33m ⚙ ${e?.name??`unknown`}\x1b[0m\n`)}}else e===`system`?process.stdout.write(`\x1b[2m${r}\x1b[0m\n`):process.stdout.write(`${r}\n`)}}function
|
|
107
|
+
`):``,lastTail:o})},f=t=>{if(e.scrollbackMode){d(t);return}let{chunks:n,tail:r,state:i}=Dc(e.streamStore.getState().streamCommit,t);if(n.length>0){let t=n.map(t=>{let n=e.incMsgCounter();return{role:`assistant_stream`,text:t.text,lead:t.lead,id:`s-${n}`}});e.messageStoreHandle.appendMany(t,()=>`s-${e.incMsgCounter()}`)}e.streamStore.setState({streamCommit:i,streamingText:r}),(t===``||n.length>0)&&e.notify()},p=t=>{e.streamStore.setState({streamingThinking:t})};return{applyStreamText:f,applyStreamThinking:p,streamTextCoalescer:Ac(f,e.coalesceMs),streamThinkingCoalescer:Ac(p,e.coalesceMs),outputTokensThrottle:sl(e.streamStore,e.coalesceMs),resetController:()=>{t=``,n=0,r=0,i=!1}}}function i_(e,t){if(e.length===0)return[];let n=Math.max(1,t);return e.map(e=>nc(e,n))}function a_(e){let t=t=>{let n=i_(t,e.getColumns()),{text:r,hasHistory:i}=Vc(t.map((e,t)=>({role:e.role??``,lines:n[t]??[]})),e.getHasHistory());return e.setHasHistory(i),r},n=null,r=r=>{let i=t(r);if(i){if(n){n.push(i);return}e.scrollbackBuffer.write(i)}},i=i=>{if(i.length<=60&&!n){r(i);return}if(n){let e=t(i);e&&n.push(e);return}n=[t(i.slice(0,60))];let a=60,o=()=>{if(a>=i.length){let t=(n??[]).join(``);n=null,t&&e.scrollbackBuffer.write(t),e.notify();return}let r=i.slice(a,a+60);a+=60,n?.push(t(r)),setImmediate(o)};setImmediate(o)};return{commitToHistory:e=>i([e]),commitManyToHistory:i}}function o_(e){let{taskStore:t,notificationStore:n,resolvers:r,flushScrollbackIfIdle:i,paneOwnsViewport:a,setPaneOwnsViewport:o,getRouter:s=P}=e,c=null,l={},u=(e,t)=>{let n=s();n.navigate(`/dialog/plugin-panel`,{state:{panelInfo:e,onClose:()=>{n.goBack(),t?.()}}})};return{openModal:(e=>{switch(e.kind){case`select`:{let t=s();if(e.async){let n=!1;t.navigate(`/dialog/select`,{state:{title:e.title,subtitle:`Probing, please wait…`,options:[],layout:e.layout??`buttons`}}),r.select=e=>{if(e==null){n=!0;return}},(async()=>{try{let i=await e.async;if(n)return;r.select=t=>{t==null?e.onCancel?.():e.onSelect(t)},t.navigate(`/dialog/select`,{replace:!0,state:{title:i.title??e.title,subtitle:i.subtitle??e.subtitle,subtitleTone:e.subtitleTone,options:i.options,maxVisible:e.maxVisible,layout:e.layout,searchable:e.searchable,subtitleActions:e.subtitleActions,detailPlacement:e.detailPlacement,onHighlight:e.onHighlight}})}catch(i){if(n)return;r.select=()=>{},t.navigate(`/dialog/select`,{replace:!0,state:{title:e.title,subtitle:`Error: ${i instanceof Error?i.message:String(i)}`,options:[{label:`Close`,value:`close`,color:`gray`}],layout:`buttons`}})}})();return}process.env.NODE_ENV!==`production`&&t.currentPath===`/dialog/select`&&e.replace!==!0&&console.warn('[openModal] Detected re-entrant openModal({ kind: "select" }) — this pushes a new dialog stack entry instead of replacing the current one. Use the `async` field for loading→content transitions, or close the current dialog before opening a new one. See RFC-285 D2.');let n=e.replace===!0&&t.currentPath===`/dialog/select`;t.navigate(`/dialog/select`,{replace:n,state:{title:e.title,subtitle:e.subtitle,subtitleTone:e.subtitleTone,options:e.options,maxVisible:e.maxVisible,searchable:e.searchable,layout:e.layout,subtitleActions:e.subtitleActions,detailPlacement:e.detailPlacement,initialFilter:e.initialFilter,onFilterChange:e.onFilterChange,onHighlight:e.onHighlight,defaultSelectedValue:e.defaultSelectedValue}}),r.select=t=>{t==null?e.onCancel?.():e.onSelect(t)};return}case`extensionDetail`:{let t=s(),n=()=>{t.goBack()};t.navigate(`/dialog/extension`,{state:{title:e.title,meta:e.meta,metaStatus:e.metaStatus,metaSuffix:e.metaSuffix,actions:e.actions,panelInfo:e.panelInfo,info:e.info,healthStats:e.healthStats,logEntries:e.logEntries,onRefresh:e.onRefresh,dataListEntries:e.dataListEntries,fullText:e.fullText,onOpenPanel:e.panelInfo?()=>u(e.panelInfo):void 0,onAction:t=>{n(),e.onAction(t)},onClose:()=>{let r=t.stack,i=r.length>=2?r[r.length-2]?.path:void 0;n(),i!==`/dialog/extensions`&&e.onClose?.()}}});return}case`pluginPanel`:u(e.panelInfo,e.onClose);return;case`extensionsList`:{let t=s();t.navigate(`/dialog/extensions`,{state:{entries:e.entries,menuContributions:e.menuContributions,lastSelectedValue:l.value,onSelect:n=>{l.value=n,n.startsWith(`contrib:`)&&t.goBack(),e.onSelect(n)},onCancel:()=>{t.goBack(),e.onCancel?.()}}});return}case`input`:return new Promise(t=>{if(e.signal?.aborted){t(null);return}let n=!1,i=e=>{n||(n=!0,r.input===i&&(s()?.goBack(),r.input=null,r.inputAction=null),t(e))};r.input=i,e.actionButton?.onPress&&(r.inputAction=e.actionButton.onPress),e.signal?.addEventListener(`abort`,()=>i(null),{once:!0}),s().navigate(`/dialog/input`,{state:{title:e.title,description:e.description,placeholder:e.placeholder,defaultValue:e.defaultValue,mask:e.mask,actionButton:e.actionButton?{label:e.actionButton.label}:void 0}})});case`onboarding`:return new Promise(t=>{let n=!1,i=e=>{n||(n=!0,r.onboarding===i&&(s()?.navigate(`/`,{reset:!0}),r.onboarding=null),t(e))};r.onboarding=i,s().navigate(`/dialog/onboarding`,{state:{onLanguagePreview:e.onLanguagePreview}})});case`questions`:return new Promise(t=>{o(!0),r.questions=(e,n)=>{t(e?{answers:e,freeformText:n}:null)},s().navigate(`/dialog/questions`,{state:{title:e.title,questions:e.questions}})});case`confirm`:{let t=s();r.confirm=()=>e.onConfirm(),r.cancel=()=>e.onCancel?.(),r.extra=e.onExtra??null;let n=t.currentPath===`/dialog/confirm`;t.navigate(`/dialog/confirm`,{replace:n,state:{title:e.title,message:e.message,confirmLabel:e.confirmLabel,cancelLabel:e.cancelLabel,confirmColor:e.confirmColor,dangerous:e.dangerous,extraLabel:e.extraLabel,extraColor:e.extraColor}});return}case`permissions`:s().navigate(`/dialog/info`,{state:{title:`Permissions`,lines:e.lines}});return;case`info`:s().navigate(`/dialog/info`,{state:{title:e.title,lines:e.lines,action:e.action,lineTones:e.lineTones,dataListEntries:e.dataListEntries}});return;case`context`:s().navigate(`/pane/context`);return;case`memory`:s().navigate(`/dialog/memory`,{state:{projectIndex:e.projectIndex,userIndex:e.userIndex,onViewEntry:e.onViewEntry,onForget:e.onForget}});return;case`keybindingPanel`:s().navigate(`/dialog/keybindings`,{state:{overrides:e.overrides,onSave:e.onSave,onSaveReplace:e.onSaveReplace,onReset:e.onReset,onResetAll:e.onResetAll}});return;case`shortcutsPanel`:s().navigate(`/dialog/shortcuts`,{state:{bindings:e.shortcuts,onSave:e.onSave,onDelete:e.onDelete}});return;case`fileViewer`:s().navigate(`/viewer/file`,{state:{path:e.path,content:e.content,preTruncated:e.preTruncated,onDismiss:e.onDismiss}});return;case`helpViewer`:s().navigate(`/viewer/help`,{state:{title:e.title,lines:e.lines,onDismiss:e.onDismiss}});return;case`progress`:{let t=s();c={title:e.title,phases:e.phases,phaseIndex:0,phaseStatuses:[`active`,`pending`,`pending`,`pending`],percent:0,detail:e.phases[0]??``,status:`running`,onDismiss:()=>{c=null}},t.navigate(`/dialog/progress`,{state:c});return}case`wizard`:{let t=s();if(t?.currentPath===`/dialog/wizard`)return;t?.navigate(`/dialog/wizard`,{state:{...e,onDismiss:()=>{t.navigate(`/`,{reset:!0}),e.onDismiss?.()},onComplete:()=>{t.navigate(`/`,{reset:!0}),e.onComplete?.()}}});return}case`a2uiForm`:{let t=s();t.navigate(`/dialog/a2ui-form`,{state:{component:e.component,onAction:(n,r,i)=>{t.goBack(),e.onAction(n,r,i)},onDismiss:()=>{t.goBack()}}});return}default:return e}}),togglePane:(e,r)=>{let a=s();if(!a)return;let o=e=>a.currentPath===e||a.currentPath.startsWith(e+`/`),c=e=>{a.currentPath===e?a.goBack():a.navigate(`/`,{reset:!0})};switch(e){case`history`:gu()?.();return;case`backgroundTasks`:{let e=`/pane/delegates`;r??!o(e)?a.navigate(e):(c(e),t.setState({backgroundOutput:null}),i());return}case`draftPane`:{let e=`/pane/draft`;r??!o(e)?a.navigate(e):c(e);return}case`queuePane`:{let e=`/pane/queue`;r??!o(e)?a.navigate(e):c(e);return}case`notifications`:r??a.currentPath!==`/pane/notifications`?a.navigate(`/pane/notifications`):(a.goBack(),n.setState({notifications:n.getState().notifications.map(e=>({...e,read:!0}))}));return;case`schedulePane`:r??a.currentPath!==`/pane/schedule`?a.navigate(`/pane/schedule`):a.goBack();return;case`perf`:r??a.currentPath!==`/pane/perf`?a.navigate(`/pane/perf`):a.goBack();return;case`cacheStats`:r??a.currentPath!==`/pane/cache`?a.navigate(`/pane/cache`):a.goBack();return;case`compactionLog`:{let e=`/pane/compaction-log`;r??!o(e)?a.navigate(e):c(e);return}case`gallery`:r??a.currentPath!==`/pane/gallery`?a.navigate(`/pane/gallery`):a.goBack();return;case`proxy`:r??a.currentPath!==`/pane/proxy`?a.navigate(`/pane/proxy`):a.goBack();return;case`prompts`:{let e=`/pane/prompts`;r??!o(e)?a.navigate(e):c(e);return}default:return e}},getNotifyStats:e.getNotifyStats,isFullScreenPaneActive:()=>a(),getCurrentPath:()=>s()?.currentPath??`/`,isForcedUpgradeActive:()=>e.taskStore.getState().forcedUpgrade!==null,openAlert:e=>{r.alert=()=>e.onOk?.(),s().navigate(`/dialog/alert`,{state:{title:e.title,message:e.message,okLabel:e.okLabel}})},openPrompt:e=>new Promise(t=>{r.prompt=t,s().navigate(`/dialog/prompt`,{state:{title:e.title,message:e.message,placeholder:e.placeholder,initialValue:e.initialValue,submitLabel:e.submitLabel,cancelLabel:e.cancelLabel}})}),updateProgress(e){if(!c)return;let t=s();if(!t){c=null;return}c={...c,...e},t.navigate(`/dialog/progress`,{replace:!0,state:c})}}}function s_(e){let{taskStore:t,state:n,notify:r,showToast:i,getRouter:a=P}=e;return{startShellExecution:e=>{n.shellTimer&&clearTimeout(n.shellTimer),t.setState({shellExecution:{command:e,output:``,status:`running`,exitCode:null}}),a()?.navigate(`/pane/shell`),r()},appendShellOutput:e=>{t.getState().shellExecution&&(t.setState({shellExecution:{...t.getState().shellExecution,output:t.getState().shellExecution.output+e}}),r())},finishShellExecution:(e,n,i)=>{t.getState().shellExecution&&(t.setState({shellExecution:{...t.getState().shellExecution,status:e===null?`error`:`done`,exitCode:e,terminated:i,output:n?t.getState().shellExecution.output+n:t.getState().shellExecution.output}}),r())},dismissShellExecution:()=>{n.shellTimer&&clearTimeout(n.shellTimer),t.setState({shellExecution:null}),a()?.currentPath===`/pane/shell`&&a()?.goBack(),n.shellTimer=null,r()},copyShellOutput:()=>{let e=t.getState().shellExecution;e&&(Yn(e.output),i(B.t(`shell.copiedTitle`),B.t(`shell.copiedBody`)))},getShellExecutionSnapshot:()=>{let e=t.getState().shellExecution;return e?{command:e.command,output:e.output,exitCode:e.exitCode,terminated:e.terminated}:null}}}function c_(e){let{notificationStore:t,state:n,counters:r,notify:i,getRouter:a=P}=e;return{showToast:(e,o)=>{n.toastTimer&&clearTimeout(n.toastTimer);let s={id:++r.toast,title:e,content:o};t.setState({toast:s}),qr(a(),Ir,!0),n.toastTimer=setTimeout(()=>{t.setState({toast:null}),n.toastTimer=null,qr(a(),Ir,!1),i()},km),i()},showRetryDialog:(e,n,r,o,s,c,l)=>{t.setState({retryCountdown:{attempt:e,max:n,delayMs:r,accelerate:o,reason:c,onExpired:()=>{t.setState({retryCountdown:null}),qr(a(),Rr,!1),i(),s()},onStop:l?()=>{t.setState({retryCountdown:null}),qr(a(),Rr,!1),i(),l()}:void 0}}),qr(a(),Rr,!0),i()},clearRetryDialog:()=>{t.setState({retryCountdown:null}),qr(a(),Rr,!1),i()},showErrorRetry:e=>{let n=e=>()=>{t.setState({errorRetry:null}),qr(a(),zr,!1),i(),e()};t.setState({errorRetry:{...e,actions:e.actions.map(e=>({...e,run:n(e.run)})),focusIndex:0,exhausted:e.exhausted??!1,onExpired:n(e.onExpired),onCancel:n(e.onCancel)}}),qr(a(),zr,!0),i()},clearErrorRetry:()=>{t.setState({errorRetry:null}),qr(a(),zr,!1),i()},pushNotification:(e,n,a=`system`,o=`info`)=>{t.setState({notifications:[{id:++r.notify,source:a,level:o,title:e,message:n,timestamp:Date.now(),read:!1},...t.getState().notifications.slice(0,49)]}),i()},dismissNotification:e=>{t.setState({notifications:t.getState().notifications.filter(t=>t.id!==e)}),t.getState().notifications.length===0&&a()?.goBack(),i()},markAllNotificationsRead:()=>{t.setState({notifications:t.getState().notifications.map(e=>({...e,read:!0}))}),i()}}}function l_(e){let{taskStore:t,messageStoreHandle:n,counters:r,pendingSteerMsgIds:i,scrollbackMode:a,commitToHistory:o,scanA2uiButtons:s,notify:c}=e;return{setPendingEcho:(e,r)=>{if(t.setState({pendingEcho:{text:e,mode:r}}),!a){let e=n.store.getState().messages.at(-1);e?.id?n.patchById(e.id,{streaming:!0}):n.patchLast({streaming:!0})}c()},clearPendingEcho:()=>{let e=t.getState().pendingEcho;if(e){if(a&&(o({role:`user`,content:e.text}),s()),t.setState({pendingEcho:null}),!a){let e=n.store.getState().messages.at(-1);e?.id?n.patchById(e.id,{streaming:!1}):n.patchLast({streaming:!1})}c()}},withdrawPendingEcho:()=>{if(t.getState().pendingEcho){if(t.setState({pendingEcho:null}),!a){let e=`u-${r.msg}`,t=n.store.getState().messages.findLastIndex(t=>t.id===e);if(t!==-1){let e=[...n.store.getState().messages];e.splice(t,1),n.store.setState({messages:e})}else n.removeLast()}c()}},setPendingSteer:(e,o)=>{if(t.setState({pendingSteers:[...t.getState().pendingSteers,{text:e,id:o}]}),!a){r.msg++;let t=`u-${r.msg}`;i.set(o,t),n.append({role:`user`,content:e,streaming:!0,id:t},t)}c()},commitPendingSteer:e=>{let r=t.getState().pendingSteers,l=r.find(t=>t.id===e);if(l){if(a)o({role:`user`,content:l.text}),s();else{let t=i.get(e);t&&(n.patchById(t,{streaming:!1}),i.delete(e))}t.setState({pendingSteers:r.filter(t=>t.id!==e)}),c()}},withdrawPendingSteer:e=>{let r=t.getState().pendingSteers;if(r.some(t=>t.id===e)){if(t.setState({pendingSteers:r.filter(t=>t.id!==e)}),!a){let t=i.get(e);if(t){let r=n.store.getState().messages.filter(e=>e.id!==t);n.store.setState({messages:r}),i.delete(e)}}c()}},clearPendingSteers:()=>{let e=t.getState().pendingSteers;if(e.length!==0){if(a){for(let t of e)o({role:`user`,content:t.text});s()}else for(let t of e){let e=i.get(t.id);e&&(n.patchById(e,{streaming:!1}),i.delete(t.id))}t.setState({pendingSteers:[]}),c()}}}}function u_(e){let{streamStore:t,streamTextCoalescer:n,streamThinkingCoalescer:r,outputTokensThrottle:i,perfStore:a,compactionLogStore:o,drainQueue:s,getRouterRef:c,notify:l}=e;return{pushEngineEvent:e=>{switch(e.kind){case`agentProcessing`:t.setState({processing:e.value}),e.value||s();break;case`streamingText`:n.push(e.text,e.text===``);break;case`streamingThinking`:r.push(e.text,e.text===``);break;case`activeTool`:t.setState({activeTool:e.name});break;case`spinnerMode`:t.setState(e.mode===`requesting`?{spinnerMode:e.mode,outputTokensThisTurn:0}:{spinnerMode:e.mode});break;case`outputTokensThisTurn`:i.push(e.n);break;case`maxOutputTokens`:t.setState({maxOutputTokens:e.n});break;case`toolBudget`:t.setState({toolTurnCount:e.toolTurnCount,maxToolTurns:e.maxToolTurns,promptOutputTokens:e.outputTokens??0,promptOutputTokenBudget:e.outputTokenBudget??0});break;case`perf`:{let t=!1;e.memory&&(a.setMemory(e.memory),t=!0),e.notify&&(a.setNotify(e.notify),t=!0),e.pluginMetrics&&(a.setPluginMetrics(e.pluginMetrics),t=!0),e.indicatorLevel&&a.setIndicatorLevel(e.indicatorLevel),t&&l();break}case`compactionLog`:switch(e.entryKind){case`compact`:o.recordCompaction(e.before,e.after,e.summary);break;case`prune`:o.recordPrune(e.tokensSaved,e.prunedCount??0);break;case`history_capped`:o.recordHistoryCapped(e.removedCount);break}c()?.currentPath.startsWith(`/pane/compaction-log`)&&l();break}}}}function d_(e){let{modalHandleMethods:t,permResolvers:n,counters:r,taskStore:i,getRouterRef:a,notify:o,onConfirmResolve:s}=e;return{...t,resolveConfirm:e=>{s(e)},requestPermission:e=>{let t=`perm-${++r.perm}`;return new Promise(r=>{n.set(t,r);let s={id:t,tool:e.tool,input:e.input,risk:e.risk,description:e.description,alwaysAllowLabel:e.alwaysAllowLabel};i.setState({pendingPermission:s}),o(),a()?.navigate(`/dialog/permission`,{state:s})})}}}function f_(e){let{pendingMethods:t,restoreInputRef:n,pasteBridgeRef:r}=e;return{...t,restoreInputText:e=>{n.current?.fill(e)},hydratePaste:e=>{r.current?.hydrate(e)},exportPaste:()=>r.current?.export()??null}}function p_(e){let{lifecycleFlags:t,scrollbackBuffer:n,streamTextCoalescer:r,streamThinkingCoalescer:i,notifyScheduler:a,state:o,registryUnregisterAll:s,unmount:c,windowMode:l,scopedViewport:u,hasHistoryRef:d,resetStreamController:f,messageStoreHandle:p,scrollStoreHandle:m,streamStoreHandle:h,taskStoreHandle:g,notificationStoreHandle:_,perfStore:v,contextStore:y,budgetStore:b,taskStore:x,notificationStore:S,a2uiButtonsRef:C,resetStatusWidgetBreakers:w,getRouterRef:T,overlayPaths:E,syncOverlayRoute:ee,notify:D,i18next:te,detectLanguage:ne,setLanguage:O,getThemeRef:k,setTerminalTitle:re}=e;return{stop:()=>{if(!t.stopped){t.stopped=!0,t.unmounted=!0,e.detachSessionSource?.(),s();try{n.flush()}catch{}r.cancel(),i.cancel(),a.cancel(),o.toastTimer&&=(clearTimeout(o.toastTimer),null),c(),e.onStop?.()}},clearSession:()=>{l||n.write(u?`\x1B[2J\x1B[H`:`\x1B[2J\x1B[3J\x1B[H`),d.set(!1),f(),p.reset(),m.toBottom(),h.reset(),g.reset(),_.reset(),v.reset(),y.reset(),b.reset(),x.setState({tasks:[]}),x.setState({tasksTitle:void 0}),x.setState({turnBoundaries:[]}),x.setState({editedFiles:[]}),x.setState({subagentsAccum:new Map}),S.setState({toast:null}),S.setState({retryCountdown:null}),S.setState({errorRetry:null});let e=T();if(e)for(let t of E)ee(e,t,!1);S.setState({providerUsage:null}),o.toastTimer&&=(clearTimeout(o.toastTimer),null),C.current=[],s(),w(),e?.currentPath!==`/home`&&e?.navigate(`/home`,{reset:!0}),D()},setLanguage:e=>{let t=e===`auto`?ne():e;return te.changeLanguage(t),O(t),D(),t},setPresetSelection:e=>{k()?.setPresetSelection(e)},setTerminalTitle:e=>re(e)}}function m_(e){let{messageStoreHandle:t,notify:n}=e,r=null,i=()=>{let e=r;e&&(r=null,e.stop())};return{attachSessionSource:async e=>{if(r)throw Error(`attachSessionSource: a session data source is already attached`);return r={stop:await e.start({messageStore:{setState:e=>t.store.setState(e)}})},n(),i},detachSessionSource:i}}function h_(e){let{scrollbackMode:t,commitToHistory:n,commitManyToHistory:r,messageStoreHandle:i,counters:a,getTurnMessagesFor:o,taskStore:s,notify:c,scanA2uiButtons:l}=e;return{pushMessage:e=>{if(t){n(e),c(),l();return}a.msg++,i.append(e,`m-${a.msg}`),c(),l()},pushMessages:e=>{if(e.length!==0){if(t){r(e),c(),l();return}i.appendMany(e,()=>(a.msg++,`m-${a.msg}`)),c(),l()}},echoUserInput:(e,r)=>{let o=r?.pending===!0;if(t){if(o)return;n({role:`user`,content:e}),l();return}a.msg++;let s=`u-${a.msg}`;i.append({role:`user`,content:e,streaming:o,id:s},s),c(),l()},getTurnMessages:o,getTurnBoundaries:()=>s.getState().turnBoundaries,getEditedFiles:()=>s.getState().editedFiles}}function g_(e){let{streamMethods:t,taskStore:n,notificationStore:r,notificationMethods:i,getRouterRef:a,syncOverlayRoute:o,overlayPause:s,drainQueue:c,notify:l}=e;return{pushEngineEvent:t.pushEngineEvent,hasQueuedFollowUp:()=>n.getState().queued.length>0,takeLastQueuedFollowUp:()=>{let e=n.getState().queued,t=e.at(-1);if(t)return n.setState({queued:e.slice(0,-1)}),l(),t},enqueueFollowUp:(e,t=`send`)=>{n.setState({queued:[...n.getState().queued,{text:e,mode:t}]}),l(),c()},setPauseDialog:e=>{r.setState({pauseDialog:e}),o(a(),s,!!e),l()},showRetryDialog:i.showRetryDialog,clearRetryDialog:i.clearRetryDialog,showErrorRetry:i.showErrorRetry,clearErrorRetry:i.clearErrorRetry}}function __(e){let{modalHandleMethods:t,taskStore:n,getRouterRef:r,syncOverlayRoute:i,overlayServices:a,flushScrollbackIfIdle:o,notify:s}=e;return{togglePane:t.togglePane,setServices:e=>{i(r(),a,e),s()},switchToSubagentContext:e=>{n.setState({subagentContext:e});let t=r();e&&t?.currentPath!==`/subagent`&&t?.navigate(`/subagent`),o(),s()},toggleEditedFiles:e=>{if(n.getState().editedFiles.length===0)return;let t=r();if(!t)return;let i=`/pane/edited-files`,a=t.currentPath===i||t.currentPath.startsWith(i+`/`),o=e??!a;o&&!a?t.navigate(i):!o&&a&&t.currentPath===i&&t.goBack()},clearEditedFiles:()=>{n.setState({editedFiles:[]}),s()},removeQueuedAt:e=>{n.setState({queued:n.getState().queued.filter((t,n)=>n!==e)}),s()},clearQueue:()=>{n.setState({queued:[]}),s()},moveQueuedItem:(e,t)=>{let r=e,i=e+t;if(i<0||i>=n.getState().queued.length||r<0||r>=n.getState().queued.length)return;let a=[...n.getState().queued],[o]=a.splice(r,1);o&&a.splice(i,0,o),n.setState({queued:a}),s()}}}function v_(e){let{taskStore:t,taskStoreHandle:n,registerPlugin:r,registryUnregister:i,computeStalePluginIds:a,getRegistrySnapshot:o,getStatusItems:s,getStatusWidgets:c,resetStatusWidgetBreakers:l,registryRef:u,a2uiButtonsRef:d,subagentRestoreFields:f,notify:p}=e;return{setPluginRegistrations:e=>{let n=new Set;for(let t of e)n.add(t.pluginId),r(t.pluginId,t);for(let e of a(n,o()))i(e);l(),t.setState({pluginStatusItems:s(),statusWidgets:c()}),p()},unregisterPluginSource:e=>{i(e),l(),t.setState({pluginStatusItems:s(),statusWidgets:c()}),p()},setPluginStatusItems:e=>{n.actions.setPluginStatusItems(e.map(e=>({id:e.icon,text:e.text})))},setCommands:e=>{t.setState({commands:e}),r(`cli-commands`,{pluginId:`cli-commands`,commands:[...e]})},registerArgumentSuggester:(e,t)=>{u?.current&&u.current.registerArgumentSuggester(e,t)},setA2uiButtons:e=>{d.current=e},addSubagent:e=>{let n=new Map(t.getState().subagentsAccum);n.set(e.id,{id:e.id,command:e.name,type:`agent-session`,startedAt:e.startedAt??Date.now(),...f(e.status)}),t.setState({subagentsAccum:n}),p()},getSubagents:()=>t.getState().subagentsAccum,clearSubagents:()=>{t.setState({subagentsAccum:new Map}),p()}}}function y_(e){let{notificationMethods:t,notifyScheduler:n,taskStore:r,modalHandleMethods:i,shellMethods:a,contextStore:o,getRouterRef:s,scrollStoreHandle:c}=e;return{pushNotification:t.pushNotification,dismissNotification:t.dismissNotification,markAllNotificationsRead:t.markAllNotificationsRead,getNotifyStats:()=>n.getStats(),getCurrentPath:()=>s()?.currentPath??`/`,isForcedUpgradeActive:()=>r.getState().forcedUpgrade!==null,isFullScreenPaneActive:()=>i.isFullScreenPaneActive(),getShellExecutionSnapshot:a.getShellExecutionSnapshot,addContextTurn:e=>o.addTurn(e),markContextTurns:e=>o.markTurns(e),showToast:t.showToast,setTopView:e=>{s()?.navigate(`/`,{reset:!0}),c.toBottom(),c.setTotalLines(0)}}}function b_(e){let t=e.intervalMs??5e3,n=e.minIntervalMs??2e3,{stdout:r,enabled:i}=e,a=null,o=0,s=()=>{try{r.write(`\x1B]11;?\x07`),o=Date.now()}catch{}};return{start:()=>{i&&r.isTTY&&(a||(s(),a=setInterval(s,t),a.unref?.()))},stop:()=>{a&&=(clearInterval(a),null)},pollNow:()=>{i&&r.isTTY&&(Date.now()-o<n||s())}}}function x_(e,t,n,r,i){return{onPermissionDecision:(e,n,i)=>{let a=t.get(e);t.delete(e),r.setState({pendingPermission:null}),P()?.goBack(),a?.({approved:n,mode:i})},onSelectResolve:e=>{let t=n.select;n.select=null,P()?.goBack(),t?.(e)},onInputResolve:e=>{let t=n.input;t&&(n.input=null,P()?.currentPath===`/dialog/input`&&P()?.goBack(),t(e))},onOnboardingResolve:e=>{n.onboarding?.(e)},onInputAction:()=>{let e=n.inputAction;e?.()},onQuestionsResolve:(e,t)=>{let r=n.questions;r&&(i?.(!1),n.questions=null,P()?.currentPath===`/dialog/questions`&&P()?.goBack(),r(e,t))},onConfirmResolve:(e,t)=>{let r=n.confirm,i=n.cancel,a=n.extra;n.confirm=null,n.cancel=null,n.extra=null,P()?.currentPath===`/dialog/confirm`&&P()?.goBack(),!(!r&&!i&&!a)&&(t?a?.():e?r?.():i?.())},onAlertResolve:()=>{let e=n.alert;n.alert=null,P()?.goBack(),e?.()},onPromptResolve:e=>{let t=n.prompt;n.prompt=null,P()?.goBack(),t?.(e)},getTurnMessagesFor:t=>{let n=r.getState().turnBoundaries,i=e.getMessages(),a=t>1?n[t-2]??0:0,o=n[t-1]??i.length;return i.slice(a,o)}}}function S_(e,t,n,r,i){return()=>{if(t()||i.getState().queued.length===0)return;let[e,...a]=i.getState().queued;i.setState({queued:a}),n(),queueMicrotask(()=>r?.(e.text,e.mode))}}function C_(e){let[,t]=K(0);V.useEffect(()=>{let n=()=>t(e=>e+1);return e.state.listener=n,()=>{e.state.listener===n&&(e.state.listener=null)}},[]);let n=V.useCallback(()=>{Ql(),e.taskStore.setState({backgroundOutput:null}),e.opts.onBackgroundOutputClose?.(),e.flushScrollbackIfIdle(),e.notify()},[]),r=V.useCallback(()=>{P()?.goBack(),e.taskStore.setState({backgroundOutput:null}),e.opts.onBackgroundOutputClose?.(),e.flushScrollbackIfIdle(),e.notify()},[]),i=V.useCallback(()=>{P()?.currentPath===`/subagent`&&P()?.goBack(),e.opts.onSubagentExit?.(),e.taskStore.setState({subagentContext:null}),e.flushScrollbackIfIdle(),e.notify()},[]),a=V.useCallback(()=>{e.taskStore.getState().queued.length!==0&&(e.taskStore.setState({queued:e.taskStore.getState().queued.slice(0,-1)}),e.notify())},[]),o=V.useCallback(()=>{P()?.currentPath===`/dialog/info`&&P()?.goBack(),e.notify()},[]),s=V.useCallback(()=>{P()?.currentPath===`/dialog/memory`&&P()?.goBack(),e.notify()},[]),c=V.useCallback(()=>{P()?.currentPath===`/dialog/keybindings`&&P()?.goBack(),e.notify()},[]),l=V.useCallback(()=>{P()?.currentPath===`/dialog/shortcuts`&&P()?.goBack(),e.notify()},[]),u=V.useCallback(()=>{P()?.navigate(`/pane/context/detail`)},[]),d=V.useCallback(()=>{P()?.currentPath===`/pane/context/detail`&&P()?.goBack()},[]),f=V.useCallback(()=>{let e=P();e?.currentPath.startsWith(`/pane/context`)&&e.navigate(`/`,{reset:!0})},[]),p=V.useCallback(()=>{let e=P();e&&(e.currentPath===`/pane/notifications`?e.goBack():e.navigate(`/pane/notifications`))},[]),m=V.useCallback(t=>{e.notificationStore.setState({notifications:e.notificationStore.getState().notifications.filter(e=>e.id!==t)}),e.notificationStore.getState().notifications.length===0&&P()?.goBack()},[]),h=V.useCallback(()=>{e.notificationStore.setState({notifications:e.notificationStore.getState().notifications.map(e=>({...e,read:!0}))}),P()?.goBack()},[]),g=V.useCallback(()=>{e.opts.onSubmit?.(`/upgrade`,`send`)},[]),_=V.useCallback(()=>{e.stopRef.current?.()},[]),v=V.useCallback((t,n)=>{e.state.toastTimer&&clearTimeout(e.state.toastTimer);let r={id:++e.toastCounterRef.current,title:t,content:n};e.notificationStore.setState({toast:r}),qr(P(),Ir,!0),e.state.toastTimer=setTimeout(()=>{e.notificationStore.setState({toast:null}),e.state.toastTimer=null,qr(P(),Ir,!1),e.notify()},km),e.notify()},[]),y=V.useCallback(()=>{e.state.toastTimer&&(clearTimeout(e.state.toastTimer),e.state.toastTimer=null),e.notificationStore.getState().toast&&(e.notificationStore.setState({toast:null}),qr(P(),Ir,!1),e.notify())},[]),b=e.scrollbackMode?V.useCallback(t=>{e.inkWriteRef.current=t},[]):void 0,x=e.opts.welcome?.cwd?V.useCallback(async t=>{let{content:n,truncated:r}=await en(fn(e.opts.welcome.cwd,t));return{content:n,truncated:r}},[]):void 0,S=V.useCallback(()=>{if(e.taskStore.getState().editedFiles.length===0)return;let t=P();if(!t)return;let n=`/pane/edited-files`;t.currentPath===n||t.currentPath.startsWith(n+`/`)?t.navigate(`/`,{reset:!0}):t.navigate(n,{replace:!0})},[]),C=V.useCallback(()=>{if(e.taskStore.getState().subagentsAccum.size===0)return;let t=P();t&&(t.currentPath===`/pane/subagents`?t.navigate(`/`,{reset:!0}):t.navigate(`/pane/subagents`,{replace:!0}))},[]),w=V.useCallback(()=>{if(e.taskStore.getState().scheduleTasks.length===0)return;let t=P();t&&(t.currentPath===`/pane/schedule`?t.navigate(`/`,{reset:!0}):t.navigate(`/pane/schedule`,{replace:!0}))},[]),T=V.useCallback(e=>{let t=P();if(!t)return;let n=`/pane/draft`,r=t.currentPath===n||t.currentPath.startsWith(n+`/`),i=e??!r;i&&!r?t.navigate(n,{replace:!0}):!i&&r&&t.navigate(`/`,{reset:!0})},[]),E=V.useCallback(e=>{let t=P();if(!t)return;let n=`/pane/queue`,r=t.currentPath===n||t.currentPath.startsWith(n+`/`),i=e??!r;i&&!r?t.navigate(n,{replace:!0}):!i&&r&&t.navigate(`/`,{reset:!0})},[]),ee=V.useCallback(()=>{let e=P();if(!e)return;let t=`/pane/prompts`;e.currentPath===t||e.currentPath.startsWith(t+`/`)?Ql():e.navigate(t,{replace:!0})},[]),D=V.useCallback(t=>{e.opts.onDraftSave?.(t)},[]),te=V.useCallback(t=>{let n=e.taskStore.getState().drafts[t];n&&e.opts.onDraftDelete?.(n.id)},[]),ne=V.useCallback(t=>{e.opts.onDraftDeleteMany?.(t)},[]),O=V.useCallback(t=>{e.taskStore.setState({queued:e.taskStore.getState().queued.filter((e,n)=>n!==t)}),e.notify()},[]),k=V.useCallback((t,n)=>{let r=t,i=t+n;if(i<0||i>=e.taskStore.getState().queued.length||r<0||r>=e.taskStore.getState().queued.length)return;let a=[...e.taskStore.getState().queued],[o]=a.splice(r,1);o&&a.splice(i,0,o),e.taskStore.setState({queued:a}),e.notify()},[]),re=V.useCallback((t,n)=>{let r=e.taskStore.getState().queued;if(t<0||t>=r.length)return;let i=[...r],a=i[t];a&&(i[t]={...a,text:n}),e.taskStore.setState({queued:i}),e.notify()},[]),A=V.useCallback((t,n)=>{let r=e.taskStore.getState().queued;if(t<0||t>=r.length)return;let i=r[t].mode;e.taskStore.setState({queued:r.filter((e,n)=>n!==t)}),e.notify(),e.opts.onQueueSendNow?.(n,i)},[]),ie=V.useCallback(t=>{let n=e.notificationStore.getState().errorRetry;n&&(e.notificationStore.setState({errorRetry:{...n,focusIndex:t}}),e.notify())},[]),j=V.useCallback(t=>{let n=e.notificationStore.getState().pulseSurvey;n&&(e.notificationStore.setState({pulseSurvey:{...n,...t}}),e.notify())},[]),ae=V.useCallback(()=>{if(e.taskStore.getState().backgroundTasks.length===0)return;let t=P();if(!t)return;let n=`/pane/delegates`;t.currentPath===n||t.currentPath.startsWith(n+`/`)?(t.navigate(`/`,{reset:!0}),e.taskStore.setState({backgroundOutput:null}),e.flushScrollbackIfIdle()):t.navigate(n,{replace:!0})},[]),oe=V.useCallback(()=>{e.state.shellTimer&&clearTimeout(e.state.shellTimer),e.taskStore.setState({shellExecution:null}),e.state.shellTimer=null,P()?.currentPath===`/pane/shell`&&P()?.goBack(),e.notify()},[]),M=V.useCallback(()=>{let t=e.taskStore.getState().shellExecution;t&&(Yn(t.output),v(B.t(`shell.copiedTitle`),B.t(`shell.copiedBody`)))},[]);return V.useEffect(()=>{let t=null,n=()=>{t&&clearTimeout(t),t=setTimeout(()=>{let t=e.opts.columns||(e.stdout.columns>0?e.stdout.columns:process.stdout.columns>0?process.stdout.columns:80),n=e.opts.rows||(e.stdout.rows>0?e.stdout.rows:process.stdout.rows>0?process.stdout.rows:24);(t!==e.columnsRef.current||n!==e.rowsRef.current)&&(e.columnsRef.current=t,e.rowsRef.current=n,e.notify())},100)};return e.stdout.on(`resize`,n),()=>{t&&clearTimeout(t),e.stdout.off(`resize`,n)}},[]),V.createElement(dg,{columns:e.columnsRef.current,rows:e.rowsRef.current,registerWrite:e.scrollbackMode?b:void 0,maxPreviewRows:e.scrollbackMode?1:void 0,hasHistory:e.hasHistoryRef.current,messages:e.messageStore.getState().messages,scrollStore:e.scrollStore,loadHistory:e.opts.loadHistory,messageStore:e.messageStoreHandle,windowMode:e.windowMode,scrollbackMode:e.scrollbackMode,shadow:e.opts.shadow??!1,language:e.languageRef.current,systemTheme:e.systemTheme,themeRegistry:e.themeRegistry,presetSelection:e.presetSelection,keybindingOverrides:e.opts.keybindingOverrides,onCyclePermissionMode:e.opts.onCyclePermissionMode,pluginInput:e.opts.pluginInput,readFileContent:x,getTurnMessages:e.getTurnMessagesFor,editedFilesOpen:!1,onToggleEditedFiles:S,subagentsOpen:!1,onToggleSubagents:C,onToggleSchedule:w,initialHistory:e.opts.initialHistory,externalHistoryCommands:e.opts.externalHistoryCommands,onHistoryPush:e.opts.onHistoryPush,residencyGovernor:e.opts.residencyGovernor,resolveWholeFileDiff:e.opts.resolveWholeFileDiff,restoreInputRef:e.restoreInputRef,pasteBridgeRef:e.pasteBridgeRef,scheduleOpen:!1,draftOpen:!1,onToggleDraftPane:T,onDraftSave:D,onDraftDelete:te,onDraftDeleteMany:ne,onSigilSelect:e.opts.onSigilSelect,queueOpen:!1,onToggleQueuePane:E,onTogglePrompts:ee,onQueueDelete:O,onQueueMove:k,onQueueEditText:re,onQueueSendNow:A,pendingEcho:e.taskStore.getState().pendingEcho,onErrorRetryFocusChange:ie,onPulseSurveyChange:j,backgroundTasksOpen:!1,onToggleDelegates:ae,onBackgroundClose:n,onBackgroundKill:e.opts.onBackgroundKill,onBackgroundViewOutput:e.opts.onBackgroundViewOutput,onBackgroundOutputClose:r,onBackgroundApply:e.opts.onBackgroundApply,onBackgroundSwitch:e.opts.onBackgroundSwitch,onBackgroundDelete:e.opts.onBackgroundDelete,onExitSubagentContext:i,onPaneOwnsViewportChange:e.scrollbackMode?e.setPaneOwnsViewport:void 0,onFocusOwnerChange:e.scrollbackMode?e.setFocusOwnerForBuffer:void 0,onScrollActiveChange:e.setScrollActive,onDelegateSupply:e.opts.onDelegateSupply,welcome:e.opts.welcome,onSessionSelect:e.opts.onSessionSelect,budgetStore:e.budgetStore,contextStore:e.contextStore,notificationStore:e.notificationStoreHandle,perfStore:e.perfStore,onPerfDismiss:()=>{P()?.currentPath===`/pane/perf`&&P()?.goBack()},cacheStore:e.cacheStore,onCacheDismiss:()=>{P()?.currentPath===`/pane/cache`&&P()?.goBack()},proxyStore:e.proxyStore,proxyOpen:!1,onProxyDismiss:()=>{P()?.goBack()},onProxyOpenModal:e.proxyOpenModal,onProxySubmitUrl:e.opts.onProxySubmitUrl,onProxyToggleEnabled:e.opts.onProxyToggleEnabled,onProxyClear:e.opts.onProxyClear,compactionLogStore:e.compactionLogStore,onCompactionLogDismiss:()=>{let e=P();e?.currentPath.startsWith(`/pane/compaction-log`)&&e.navigate(`/`,{reset:!0})},galleryStore:e.galleryStore,onGalleryDismiss:()=>{P()?.currentPath===`/pane/gallery`&&P()?.goBack()},streamStore:e.streamStoreHandle,taskStore:e.taskStoreHandle,initialPath:e.opts.initialPath,onPerfRefresh:e.opts.onPerfRefresh,onSubmit:e.submitOrQueue,onInterrupt:e.opts.onInterrupt,onWithdrawPending:e.opts.onWithdrawPending,onWithdrawSteer:e.opts.onWithdrawSteer,onPopQueued:a,onPermissionDecision:e.onPermissionDecision,onSelectResolve:e.onSelectResolve,onInputResolve:e.onInputResolve,onOnboardingResolve:e.onOnboardingResolve,onInputAction:e.onInputAction,onQuestionsResolve:e.onQuestionsResolve,onConfirmResolve:e.onConfirmResolve,onAlertResolve:e.onAlertResolve,onPromptResolve:e.onPromptResolve,onInfoDismiss:o,onMemoryDismiss:s,onKeybindingPanelDismiss:c,onShortcutsDialogDismiss:l,onViewDetails:u,onBackToContextPane:d,onContextDismiss:f,notificationsOpen:!1,onToggleNotifications:p,onDismissNotification:m,onCloseNotifications:h,onUpgrade:g,onCancelUpgrade:_,onToast:v,onDismissToast:y,registryRef:e.registryRef,shellBackendRef:e.shellBackendRef,shellExecution:e.taskStore.getState().shellExecution,onShellAbort:e.opts.onInterrupt,onShellDismiss:oe,onShellCopyOutput:M,onShellAskAi:e.opts.onShellAskAi,a2uiButtons:e.a2uiButtonsRef.current,onA2uiAction:e.a2uiActionRef.current})}function w_(){let e=Buffer.alloc(0);return t=>{let n=F(t),r=e.length?Buffer.concat([e,n]):n;e=Buffer.alloc(0);let i=r.length;i>=2&&r[i-2]===27&&r[i-1]===91&&(e=Buffer.from(r.subarray(i-2)),i-=2);let a,o=[],s=0;for(;s<i;){if(r[s]===27&&r[s+1]===91&&(r[s+2]===73||r[s+2]===79)){a=r[s+2]===73,s+=3;continue}o.push(r[s]),s++}return{focused:a,rest:Buffer.from(o)}}}var T_=class{pending=null;feed(e){let t=F(e),n=this.pending?Buffer.concat([this.pending,t]):t;this.pending=null;let r=[],i=null,a=0;for(;a<n.length;){let e=n.indexOf(`\x1B]`,a,`latin1`);if(e<0){a<n.length&&r.push(n.slice(a));break}e>a&&r.push(n.slice(a,e));let t=n.indexOf(7,e),o=n.indexOf(`\x1B\\`,e,`latin1`),s=-1,c=0;if(t>=0&&(o<0||t<o)?(s=t,c=1):o>=0&&(s=o,c=2),s<0){let t=n.slice(e);t.length>64?r.push(t):this.pending=t;break}let l=E_(n.slice(e,s).toString(`latin1`));l&&(i=l),a=s+c}return{keys:r.length>0?Buffer.concat(r):Buffer.alloc(0),osc11:i}}};function E_(e){let t=e.match(/\]11;rgb:([0-9a-fA-F]+)\/([0-9a-fA-F]+)\/([0-9a-fA-F]+)/);if(!t)return null;let n=parseInt(t[1].slice(0,2),16),r=parseInt(t[2].slice(0,2),16),i=parseInt(t[3].slice(0,2),16);return Number.isNaN(n)||Number.isNaN(r)||Number.isNaN(i)?null:{r:n,g:r,b:i}}function D_(e,t,n){return .2126*e+.7152*t+.0722*n<128?`dark`:`light`}function O_(e){let{stdin:t,renderStdout:n,onInterrupt:r,onFocusChange:i,onTerminalBgDetected:a,onMouseWheel:o,onMouseDrag:s}=e,c=[],l=process.env.OTTO_TUI_MOUSE===`0`,u=(typeof o==`function`||typeof s==`function`)&&!!t.isTTY,d=u&&!l,f=u?Kg():null,p=d,m;if(d)try{n.write(Bg)}catch{}u&&(m=()=>{try{n.write(Vg)}catch{}},process.once(`exit`,m));let h=e=>{if(!u)return!1;if(e===p)return p;p=e;try{n.write(e?Bg:Vg)}catch{}return p},g=new T_,_=e=>{if(!a)return F(e);let{keys:t,osc11:n}=g.feed(e);return n&&a(D_(n.r,n.g,n.b)),t},v=e=>{if(!f)return _(e);let{wheels:t,drags:n,rest:r}=f(e);if(p){for(let e of t)o?.(e.delta);for(let e of n)s?.(e)}return _(r)},y=process.env.OTTO_TUI_KITTY===`1`&&!!t.isTTY,b,x=t;if(y){try{n.write(`\x1B[>1u`)}catch{}b=()=>{try{n.write(Xg)}catch{}},process.once(`exit`,b);let e=e_(),i=new xn;Object.assign(i,{isTTY:!0,setRawMode:e=>{try{t.setRawMode?.(e)}catch{}return i},ref:()=>{try{t.ref?.()}catch{}return i},unref:()=>{try{t.unref?.()}catch{}return i}});let a=t=>{let n=v(t);if(n.length===0)return;let a=e(n);a.includes(3)&&r?.(),i.write(a)};t.on(`data`,a),c.push({stream:t,fn:a}),x=i}let S=process.env.OTTO_TUI_FOCUS===`1`&&!!t.isTTY&&typeof i==`function`,C;if(S){try{n.write(`\x1B[?1004h`)}catch{}C=()=>{try{n.write(`\x1B[?1004l`)}catch{}},process.once(`exit`,C);let e=x,t=w_(),r=new xn;Object.assign(r,{isTTY:!0,setRawMode:t=>{try{e.setRawMode?.(t)}catch{}return r},ref:()=>{try{e.ref?.()}catch{}return r},unref:()=>{try{e.unref?.()}catch{}return r}});let a=e=>{let n=v(e);if(n.length===0)return;let{focused:a,rest:o}=t(n);a!==void 0&&i?.(a),o.length&&r.write(o)};e.on(`data`,a),c.push({stream:e,fn:a}),x=r}if(!y&&!S&&(a||d)){let e=x,t=new xn;Object.assign(t,{isTTY:!0,setRawMode:n=>(e.setRawMode?.(n),t),ref:()=>(e.ref?.(),t),unref:()=>(e.unref?.(),t)});let n=e=>{let n=v(e);n.length>0&&t.write(n)};e.on(`data`,n),c.push({stream:e,fn:n}),e.resume(),x=t}return{renderStdin:x,kittyOn:y,focusOn:S,mouseOn:d,kittyExitHandler:b,focusExitHandler:C,mouseExitHandler:m,setMouseEnabled:h,isMouseEnabled:()=>p,cleanup:()=>{for(let{stream:e,fn:t}of c)e.removeListener(`data`,t);c.length=0}}}const k_=12e3;async function A_(e){let{stdin:t,stdout:n,onStop:r}=e,i=Oc(e.maxFps??30),a=e.renderMaxFps??90;Ta();let o=e.columns||(n.columns>0?n.columns:process.stdout.columns>0?process.stdout.columns:80),s=e.rows||(n.rows>0?n.rows:process.stdout.rows>0?process.stdout.rows:24),c=e.language&&e.language!==`auto`?e.language:Et();Tt(c);let l=await _(),u=e.themeRegistry,d=e.presetSelection,f=process.env.OTTO_TUI_SCOPED_VIEWPORT!==`0`,p=bg(n),m=()=>Math.max(1,s-1);process.once(`exit`,()=>p.exit());let h=e.scrollback===!0||process.env.OTTO_TUI_SCROLLBACK===`1`,g=e.scrollback===!1||process.env.OTTO_TUI_SCROLLBACK===`0`,v=!h&&!g,y=rr()?nr(n):n;h&&!f&&(y=or(y));let b=e=>{y.write(e)},S=!1,{streamStoreHandle:C,streamStore:w,notificationStoreHandle:T,notificationStore:E,taskStoreHandle:ee,taskStore:D,messageStoreHandle:te,messageStore:ne,scrollStoreHandle:O,budgetStore:k,contextStore:re,perfStore:A,cacheStore:ie,proxyStore:j,compactionLogStore:ae,galleryStore:oe,completer:M,shellBackendRef:se,a2uiButtonsRef:ce,a2uiActionRef:N,scanA2uiButtons:le}=_g(e),ue={toastTimer:null,listener:null,shellTimer:null},F={current:null},de={current:null},fe=process.env.OTTO_TUI_PANE_BUFFER!==`0`,pe=`prompt`,me=()=>fe&&(D.getState().subagentContext!=null||D.getState().backgroundOutput!=null||D.getState().paneOwnsViewportFlag||pe!==`prompt`),he=vg({paneOwnsViewport:me,realWrite:e=>b(e)}),ge=()=>{me()||he.flush()},_e=e=>{let t=pe===`prompt`;pe=e,e===`prompt`&&!t&&ge()},ve=!0,ye=e=>{ve=e},be=e=>{D.setState({paneOwnsViewportFlag:e}),e||ge()},xe={msg:0,perm:0,toast:0,notify:0},Se=new Map,Ce=new Map,we={select:null,input:null,inputAction:null,questions:null,confirm:null,cancel:null,extra:null,alert:null,prompt:null,onboarding:null},I={current:null},Te={current:null},Ee=(e=>Te.current?Te.current.openModal(e):e.kind===`input`?Promise.resolve(null):void 0),De=jc({listener:()=>ue.listener?.(),intervalMs:i}),Oe=()=>De.immediate();ee.setNotify(Oe),T.setNotify(Oe);let{commitToHistory:ke,commitManyToHistory:Ae}=a_({scrollbackBuffer:he,getColumns:()=>o,getHasHistory:()=>S,setHasHistory:e=>{S=e},notify:Oe}),{streamTextCoalescer:je,streamThinkingCoalescer:Me,outputTokensThrottle:Ne,resetController:Pe}=r_({streamStore:w,messageStore:ne,messageStoreHandle:te,scrollbackBuffer:he,scrollbackMode:h,coalesceMs:i,getColumns:()=>o,getHasHistory:()=>S,setHasHistory:e=>{S=e},getMsgCounter:()=>xe.msg,incMsgCounter:()=>++xe.msg,notify:Oe}),Fe=()=>Qi(Zi(Yi(e.isAgentBusy,w.getState().processing),!!E.getState().errorRetry),!!e.isPaused?.()),Ie=(t,n,r)=>{let i=$i(t,n,r??!1,{processing:Fe(),isImmediateCommand:t=>e.isImmediateCommand?.(t)??!1,isInterruptCommand:t=>e.isInterruptCommand?.(t)??!1});if(i===`queue`){D.setState({queued:[...D.getState().queued,{text:t,mode:n}]}),Oe();return}e.onSubmit?.(t,n,i===`steer`?`steer`:`send`)},Le=S_(ue,Fe,Oe,e.onSubmit,D);ee.setEffects({syncForcedUpgradeRoute:e=>qr(P(),Vr,e),backgroundOutputRoute:e=>{e?P()?.navigate(`/pane/delegates/output`):P()?.currentPath===`/pane/delegates/output`&&P()?.goBack()},flushScrollbackIfIdle:ge,registerStatusItems:e=>Wo(`cli-status`,{pluginId:`cli-status`,statusItems:[...e]})}),T.setEffects({drainQueueOnResume:()=>Le(),syncPulseSurveyRoute:e=>qr(P(),Br,e)});let{onPermissionDecision:Re,onSelectResolve:ze,onInputResolve:Be,onOnboardingResolve:Ve,onInputAction:He,onQuestionsResolve:Ue,onConfirmResolve:We,onAlertResolve:Ge,onPromptResolve:Ke,getTurnMessagesFor:qe}=x_({getMessages:()=>ne.getState().messages},Ce,we,D,be),Je={state:ue,columnsRef:{get current(){return o},set current(e){o=e}},rowsRef:{get current(){return s},set current(e){s=e}},hasHistoryRef:{get current(){return S},set current(e){S=e}},inkWriteRef:{get current(){return b},set current(e){b=e}},toastCounterRef:{get current(){return xe.toast},set current(e){xe.toast=e}},languageRef:{get current(){return c},set current(e){c=e}},systemTheme:l,themeRegistry:u,presetSelection:d,stopRef:{},taskStore:D,notificationStore:E,messageStore:ne,streamStoreHandle:C,taskStoreHandle:ee,notificationStoreHandle:T,messageStoreHandle:te,budgetStore:k,contextStore:re,perfStore:A,cacheStore:ie,proxyStore:j,compactionLogStore:ae,galleryStore:oe,opts:e,notify:Oe,flushScrollbackIfIdle:ge,setPaneOwnsViewport:be,setFocusOwnerForBuffer:_e,setScrollActive:ye,getTurnMessagesFor:qe,submitOrQueue:Ie,onPermissionDecision:Re,onSelectResolve:ze,onInputResolve:Be,onOnboardingResolve:Ve,onInputAction:He,onQuestionsResolve:Ue,onConfirmResolve:We,onAlertResolve:Ge,onPromptResolve:Ke,proxyOpenModal:Ee,restoreInputRef:F,pasteBridgeRef:de,registryRef:I,shellBackendRef:se,a2uiButtonsRef:ce,a2uiActionRef:N,scrollbackMode:h,windowMode:v,scrollStore:O,stdout:n},L=()=>C_(Je),Ye=b_({stdout:y,enabled:!0}),Xe=qg(e=>{O.dispatchWheel(e)||pe===`prompt`&&ve&&O.scrollBy(e*3)}),R={current:null};nu(O.store,()=>R.current?.clear());let{renderStdin:Ze,kittyOn:Qe,focusOn:$e,mouseOn:et,kittyExitHandler:tt,focusExitHandler:nt,mouseExitHandler:rt,setMouseEnabled:it,isMouseEnabled:at,cleanup:ot}=O_({stdin:t,renderStdout:y,onInterrupt:e.onInterrupt,onFocusChange:e.onFocusChange,onMouseWheel:e=>Xe.push(e),onMouseDrag:e=>{R.current?.handleDrag(e)},onTerminalBgDetected:e=>{process.env.OTTO_DEBUG_THEME&&process.stderr.write(`[RFC-282] OSC detected: ${e} themeRef=${!!x()}\n`),x()?.setSystemTheme(e)}}),st=e.concurrent??process.env.OTTO_TUI_CONCURRENT===`1`;f&&p.enter();let ct=await jg(y);ct?.buffer.setMaxLineWidth(o),ct&&(R.current=Rg({buffer:ct.buffer,terminalRows:()=>m(),writeSelectionRepaint:e=>{if(e)try{y.write(e)}catch{}},writeClipboard:e=>{let t=Yg(e),n=!1;try{Yn(e),n=!0}catch{n=!1}return t||n},onCopied:(e,t)=>{let n=zg(e);t?(D.setState({clipboardChars:n,clipboardText:e,clipboardFailed:!1}),setTimeout(()=>{D.getState().clipboardChars===n&&D.setState({clipboardChars:0})},k_)):(D.setState({clipboardFailed:!0,clipboardChars:0}),setTimeout(()=>{D.getState().clipboardFailed&&D.setState({clipboardFailed:!1})},k_))}}),eu(R.current),ct.onDamage(e=>{R.current?.onFrameDamage(e)}));let{waitUntilExit:lt,unmount:ut}=Rt(V.createElement(L),{stdout:y,stdin:Ze,exitOnCtrlC:!1,maxFps:a,concurrent:st});st&&await new Promise(e=>{let t=Date.now()+1e3,n=()=>{ue.listener||Date.now()>t?e():setImmediate(n)};n()});let dt=t_({stdin:t,stdout:n,renderStdout:y,kittyOn:Qe,kittyExitHandler:tt,focusOn:$e,focusExitHandler:nt,mouseOn:et,mouseExitHandler:rt,onInterrupt:e.onInterrupt,unmount:()=>ut(),terminalInputCleanup:ot});dt.setupRawInput(),Ye.start();let ft=()=>{Ye.pollNow();let e=n.columns>0?n.columns:o;ct?.buffer.setMaxLineWidth(e)};n.on(`resize`,ft),process.once(`exit`,()=>{n.removeListener(`resize`,ft),Ye.stop()});let pt={stopped:!1,unmounted:!1},mt=o_({taskStore:D,notificationStore:E,cacheStore:ie,proxyStore:j,resolvers:we,getNotifyStats:()=>De.getStats(),flushScrollbackIfIdle:ge,paneOwnsViewport:me,setPaneOwnsViewport:be});Te.current=mt;let z=s_({taskStore:D,state:ue,notify:Oe,showToast:(...e)=>wt.info.showToast(...e)}),ht=c_({notificationStore:E,state:ue,counters:xe,notify:Oe}),gt=f_({pendingMethods:l_({taskStore:D,messageStoreHandle:te,counters:xe,pendingSteerMsgIds:Se,scrollbackMode:h,commitToHistory:ke,scanA2uiButtons:le,notify:Oe}),restoreInputRef:F,pasteBridgeRef:de}),_t=m_({messageStoreHandle:te,notify:Oe}),vt=p_({lifecycleFlags:pt,scrollbackBuffer:he,streamTextCoalescer:je,streamThinkingCoalescer:Me,notifyScheduler:De,state:ue,registryUnregisterAll:Ko,unmount:ut,windowMode:v,scopedViewport:f,hasHistoryRef:{set:e=>{S=e}},resetStreamController:Pe,messageStoreHandle:te,scrollStoreHandle:O,streamStoreHandle:C,taskStoreHandle:ee,notificationStoreHandle:T,perfStore:A,contextStore:re,budgetStore:k,taskStore:D,notificationStore:E,a2uiButtonsRef:ce,resetStatusWidgetBreakers:lu,getRouterRef:P,overlayPaths:Gr,syncOverlayRoute:qr,notify:Oe,i18next:B,detectLanguage:Et,setLanguage:e=>{c=e},getThemeRef:x,setTerminalTitle:Gn,onStop:r,detachSessionSource:_t.detachSessionSource}),yt=__({modalHandleMethods:mt,taskStore:D,getRouterRef:P,syncOverlayRoute:qr,overlayServices:Ur,flushScrollbackIfIdle:ge,notify:Oe}),bt=v_({taskStore:D,taskStoreHandle:ee,registerPlugin:Wo,registryUnregister:Go,computeStalePluginIds:Yo,getRegistrySnapshot:qo,getStatusItems:Zo,getStatusWidgets:$o,resetStatusWidgetBreakers:lu,registryRef:I,a2uiButtonsRef:ce,subagentRestoreFields:Eo,notify:Oe}),xt=y_({notificationMethods:ht,notifyScheduler:De,taskStore:D,modalHandleMethods:mt,shellMethods:z,contextStore:re,getRouterRef:P,scrollStoreHandle:O}),St=g_({streamMethods:u_({streamStore:w,streamTextCoalescer:je,streamThinkingCoalescer:Me,outputTokensThrottle:Ne,perfStore:A,compactionLogStore:ae,drainQueue:Le,getRouterRef:P,notify:Oe}),taskStore:D,notificationStore:E,notificationMethods:ht,getRouterRef:P,syncOverlayRoute:qr,overlayPause:Lr,drainQueue:Le,notify:Oe}),Ct=h_({scrollbackMode:h,commitToHistory:ke,commitManyToHistory:Ae,messageStoreHandle:te,counters:xe,getTurnMessagesFor:qe,taskStore:D,notify:Oe,scanA2uiButtons:le}),wt={modal:d_({modalHandleMethods:mt,permResolvers:Ce,counters:xe,taskStore:D,getRouterRef:P,notify:Oe,onConfirmResolve:We}),pending:gt,lifecycle:{...vt,..._t,toggleMouse:()=>{let e=it(!at());return wt.info.showToast(B.t(`mouse.toggleTitle`),e?B.t(`mouse.enabledBody`,{modifier:rf()}):B.t(`mouse.disabledBody`)),e}},messages:Ct,engine:St,panes:yt,plugins:bt,info:xt,shell:z,stores:{tasks:ee.actions,budget:{setBudget:k.setBudget},context:{setBudget:re.setBudget,addTurn:re.addTurn,markTurns:re.markTurns},cache:{setView:ie.setView},proxy:{setView:j.setView},notification:{setProviderUsage:T.setProviderUsage,setPausePending:T.setPausePending,setPaused:T.setPaused,setPulseSurvey:T.setPulseSurvey}}};return Je.stopRef.current=()=>wt.lifecycle.stop(),lt().then(()=>{pt.unmounted||(pt.unmounted=!0,dt.cleanup(),ct?.dispose(),ut(),p.active()||n.write(yg(m())),n.write(`\x1B[?25h`),p.exit())}),wt}function j_(){return{streamBuf:``,thinkBuf:``,turnStart:0,turnToolCount:0,lastTasks:[],messageIndex:0}}function M_(e,t){let n=[];e.forEach((e,t)=>{e?.role===`user`&&n.push(t)});let r=n.length,i=Math.max(t,r);if(r===0||i<=1)return[];let a=n[0],o=Array(i-1).fill(a);for(let e=0;e<r;e++){let t=i-r-1+e;t>=0&&t<o.length&&(o[t]=n[e])}return o}function N_(e){return e.filter(e=>e.status!==`done`&&e.status!==`skipped`&&e.status!==`failed`).length}function P_(e,t,n){if(t.length===0)return[...e];let r=[];e.forEach((e,t)=>{e?.role===`user`&&r.push(t)});let i=r.length,a=Math.max(n,i);if(i===0||a<=0)return[...e];let o=a-i+1,s=new Map;for(let e of t)s.set(e.turn,e);let c=new Map;for(let t of s.values()){if(t.turn<o||t.turn>a)continue;let n=t.turn-o,s=n+1<i?r[n+1]:e.length,{turn:l,...u}=t,d={role:`summary`,...u},f=c.get(s);f?f.push(d):c.set(s,[d])}if(c.size===0)return[...e];let l=[];for(let t=0;t<e.length;t++){l.push(e[t]);let n=c.get(t+1);n&&l.push(...n)}return l}function F_(e,t){let n=N_(t.lastTasks),r=e.stopReason??`completed`,i=r===`error`?`error`:r===`interrupted`?`interrupted`:n>0?`incomplete`:`done`,a={toolCount:t.turnToolCount,elapsedMs:t.turnStart>0?performance.now()-t.turnStart:0,tokensUsed:e.tokens??void 0,model:e.model||void 0,effort:e.effort||void 0,cacheHitRatio:e.cacheHitRatio??void 0};return i===`incomplete`?{...a,status:i,tasksDone:t.lastTasks.length-n,tasksTotal:t.lastTasks.length}:{...a,status:i}}function I_(e,t,n){let r=()=>{n.thinkBuf.trim()&&(t.pushMessage({role:`assistant`,content:[{type:`thinking`,thinking:n.thinkBuf}]}),n.messageIndex++),n.thinkBuf=``,t.pushEngineEvent({kind:`streamingThinking`,text:``})};switch(e.kind){case`prompt.start`:n.turnStart=performance.now(),n.turnToolCount=0,t.addTurnBoundary?.(n.messageIndex);return;case`prompt.end`:{n.thinkBuf.trim()&&(t.pushMessage({role:`assistant`,content:[{type:`thinking`,thinking:n.thinkBuf}]}),n.messageIndex++),n.streamBuf=``,n.thinkBuf=``,t.pushEngineEvent({kind:`streamingText`,text:``}),t.pushEngineEvent({kind:`streamingThinking`,text:``});let r={role:`summary`,...F_(e,n)};t.pushMessage(r),n.messageIndex++;return}case`stream.text.delta`:n.streamBuf+=e.delta,t.pushEngineEvent({kind:`streamingText`,text:n.streamBuf});return;case`stream.thinking.delta`:n.thinkBuf+=e.delta,t.pushEngineEvent({kind:`streamingThinking`,text:n.thinkBuf});return;case`stream.text.start`:r(),n.streamBuf=``;return;case`stream.text.end`:t.pushEngineEvent({kind:`streamingText`,text:``}),n.streamBuf=``;return;case`stream.thinking.start`:n.thinkBuf=``;return;case`stream.thinking.end`:r();return;case`tool.start`:t.pushEngineEvent({kind:`activeTool`,name:e.call.name});return;case`tool.end`:{if(t.pushEngineEvent({kind:`activeTool`,name:null}),n.turnToolCount++,e.suppressMessage)return;let r=e.call.arguments??{},i=r,a=i.command??i.path??i.file_path??i.pattern??i.query??JSON.stringify(r);t.pushMessage({role:`tool`,name:e.call.name,args:typeof a==`string`?a:JSON.stringify(a),argsObj:r,result:e.resultText,isError:e.isError}),n.messageIndex++;return}case`tasks.update`:n.lastTasks=e.tasks,t.setTasks(e.tasks,e.title);return;case`turn.budget`:t.pushEngineEvent({kind:`toolBudget`,toolTurnCount:e.toolTurnCount,maxToolTurns:e.maxToolTurns,outputTokens:e.outputTokens,outputTokenBudget:e.outputTokenBudget});return;case`delegate.update`:return}}function L_(e,t={}){for(let t of e){let e=t.role??`unknown`,n=t.content??[],r=Array.isArray(n)?n.filter(e=>e.type===`text`).map(e=>String(e.text??``)).join(`
|
|
108
|
+
`):String(n);if(e===`user`)process.stdout.write(`\x1b[34m▸ ${r}\x1b[0m\n`);else if(e===`assistant`){process.stdout.write(`${r}\n`);let e=t.tool_calls??[];for(let t of e){let e=t.function;process.stdout.write(`\x1b[33m ⚙ ${e?.name??`unknown`}\x1b[0m\n`)}}else e===`system`?process.stdout.write(`\x1b[2m${r}\x1b[0m\n`):process.stdout.write(`${r}\n`)}}function R_(e,t){return{search:n=>Zt(e,n,t)}}function z_(e){let{transport:t,sessionId:n,onSessionEvent:r,hydrateMessages:i,onGap:a}=e;return{async start(e){let o=null,s=!1,c=!1,l=0,u=1,d=new Map,f=e=>{s||(o?.(),l=e,u=e+1,d.clear(),o=t.subscribe(n,e,e=>{if(!(s||e.seq<u||d.has(e.seq)))for(d.set(e.seq,e);d.has(u);){let e=d.get(u);d.delete(u),r(e),l=u,u+=1}},e=>{s||c||(a(e),p())}))},p=async()=>{if(!c){c=!0;try{let r=await t.fetchSnapshot(n);if(s)return;i(e,r.session.messages),f(r.cursor)}catch{a({reason:`gap`,oldestAvailable:l})}finally{c=!1}}};try{let r=await t.fetchSnapshot(n);if(s)return()=>{};i(e,r.session.messages),f(r.cursor)}catch(e){throw s=!0,e}return()=>{s=!0,o?.(),o=null}}}}function B_(e){let t=j_();return{handle(n){I_(n.payload,e,t)},reset(e=0){t={...j_(),messageIndex:e}}}}function V_(e){return{pushMessage:e.pushMessage,echoUserInput:e.echoUserInput,pushEngineEvent:e.pushEngineEvent,getNotifyStats:e.getNotifyStats,setTasks:e.setTasks,addTurnBoundary:e.addTurnBoundary}}export{jl as AlertDialog,dg as App,ii as BASH_HISTFILE_SOURCE,Al as BashPermissionDialog,Rn as BracketedPasteHandler,I as Button,po as COMPACTING_SENTINEL,Dt as CommandRegistry,Ge as ConfirmDialog,gt as Cursor,Jr as DEFAULT_SENSITIVE_PATTERNS,t as DIALOG_BORDER,Qe as DataList,R as FIGURES,ci as FISH_HISTFILE_SOURCE,xe as GroupDivider,dd as Home,ge as LAYOUT,Ee as MeasuredText,vl as MemoryDialog,Rc as Message,pi as OTTO_SESSION_SOURCE,Ae as PALETTE,De as PANEL_BORDER,El as PermissionDialogDialog,Ml as PromptDialog,Ni as PromptInput,Pi as QueuedCommands,ul as REPLRegion,A as SPACING,nt as STATUS,kc as STREAM_COALESCE_MS,f as ScrollIndicatorAbove,v as ScrollIndicatorBelow,Nd as Segmented,Nd as Tabs,z as Select,wc as SigilPane,yd as Spinner,L as THEME,mg as TabScope,r as Tabable,Oe as TextInput,me as ThemeRegistry,Xr as ZSH_HISTFILE_SOURCE,on as applySigilCompletion,wr as applySlashCompletion,Zn as beginSyncFrame,F_ as buildTurnSummary,ns as clearPluginRenderers,Pc as collapseMessages,z_ as createAttachSessionDataSource,yu as createBudgetStore,Ot as createBuiltinCommands,fe as createBuiltinThemeRegistry,br as createCommandRegistry,R_ as createIncrementalSearcher,sr as createInputBuffer,lr as createInputHistory,bi as createMergedHistoryProvider,yr as createPasteStore,Mc as createQueryGuard,j_ as createReducerState,tt as createSelectState,B_ as createSessionEventReduceBridge,V_ as createStoreTuiSink,E as cycleIndex,M_ as deriveTurnBoundaries,Et as detectLanguage,$e as displayWidth,Xi as effectiveBusy,Qn as endSyncFrame,yi as entriesToCommands,Ic as expandCollapsed,ln as extractSigilPrefix,xr as extractSlashPrefix,No as formatAgentDiagnosticsText,gl as formatKeyValueLines,An as formatProviderUsageLimitTypeFull,hl as formatTranscriptText,jo as formatTurnTimeline,Sr as getCommandSuggestions,Ze as getInputViewport,ct as getKillRingEntries,Pa as getMarkdownThemeUserOverrides,or as guardScrollbackStdout,Be as handleEditingKey,be as handleEditingKeyExtended,B as i18next,Tt as initI18n,Ec as initStreamCommit,ut as insertHistory,Ce as insertHistorySequence,P_ as insertTurnSummaries,Yr as isSensitiveCommand,Mn as isUsingOverage,Ac as makeCoalescer,jc as makeNotifyScheduler,Jt as matchSubsequence,hi as mergeHistoryEntries,Cr as navigateSuggestions,ri as normalizeCommand,Do as observationLiveFields,ko as observationRow,Xn as osc52QuerySequence,Yn as osc52Write,Jn as osc8FilePath,qn as osc8Hyperlink,ai as parseBashHistory,Hn as parseExtendedKey,li as parseFishHistory,ei as parseZshHistory,Ke as pickInsertMode,Xt as positionsToHighlightRanges,ht as preWrapLine,Te as preWrapLines,L_ as printMessages,Dn as promptParentWorkspaceChoice,wn as promptWorkspaceTrust,Zt as rankCandidates,Qt as rankLabeledItems,$t as rankNamedItems,I_ as reduceToTui,ts as registerPluginRenderers,za as renderInline,$a as renderMarkdownToLines,nc as renderMessageLines,et as resetKillRing,D as resolveHorizontalStep,$i as routeSubmit,Tc as safeCommitBoundary,tn as scoreSubsequence,Na as setMarkdownThemeUserOverrides,rr as shouldStripSyncOutput,we as shouldUseViewport,kt as showCommandPalette,Ji as slashCommandName,A_ as startTui,Dc as streamCommitStep,Le as stringWidth,ar as stripScrollbackClear,tr as stripSyncSequences,nr as stripSyncStdout,To as subagentEntryStatus,Eo as subagentRestoreFields,wt as t,Fc as toggleCollapse,Z as useAppState,pg as useTabScope,ee as useTabable,$n as withSyncFrame};
|
|
109
109
|
//# sourceMappingURL=index.js.map
|