aicodeman 1.30.0 → 1.31.0

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.
Files changed (173) hide show
  1. package/dist/config/cli-registry/schema.d.ts +8 -0
  2. package/dist/config/cli-registry/schema.d.ts.map +1 -1
  3. package/dist/config/cli-registry/schema.js +29 -0
  4. package/dist/config/cli-registry/schema.js.map +1 -1
  5. package/dist/config/cli-registry/stock.d.ts.map +1 -1
  6. package/dist/config/cli-registry/stock.js +62 -7
  7. package/dist/config/cli-registry/stock.js.map +1 -1
  8. package/dist/config/cli-registry/types.d.ts +62 -0
  9. package/dist/config/cli-registry/types.d.ts.map +1 -1
  10. package/dist/config/remote-wake-limits.d.ts +23 -0
  11. package/dist/config/remote-wake-limits.d.ts.map +1 -0
  12. package/dist/config/remote-wake-limits.js +23 -0
  13. package/dist/config/remote-wake-limits.js.map +1 -0
  14. package/dist/custom-model-hosts.d.ts +32 -0
  15. package/dist/custom-model-hosts.d.ts.map +1 -1
  16. package/dist/custom-model-hosts.js.map +1 -1
  17. package/dist/custom-model-injection-apply.d.ts +29 -1
  18. package/dist/custom-model-injection-apply.d.ts.map +1 -1
  19. package/dist/custom-model-injection-apply.js +191 -5
  20. package/dist/custom-model-injection-apply.js.map +1 -1
  21. package/dist/custom-model-injection.d.ts +35 -9
  22. package/dist/custom-model-injection.d.ts.map +1 -1
  23. package/dist/custom-model-injection.js +37 -16
  24. package/dist/custom-model-injection.js.map +1 -1
  25. package/dist/mux-interface.d.ts +12 -0
  26. package/dist/mux-interface.d.ts.map +1 -1
  27. package/dist/remote-hosts.d.ts +20 -0
  28. package/dist/remote-hosts.d.ts.map +1 -1
  29. package/dist/remote-hosts.js +33 -0
  30. package/dist/remote-hosts.js.map +1 -1
  31. package/dist/remote-wake.d.ts +446 -0
  32. package/dist/remote-wake.d.ts.map +1 -0
  33. package/dist/remote-wake.js +880 -0
  34. package/dist/remote-wake.js.map +1 -0
  35. package/dist/session-env-clamp.d.ts +12 -7
  36. package/dist/session-env-clamp.d.ts.map +1 -1
  37. package/dist/session-env-clamp.js +12 -7
  38. package/dist/session-env-clamp.js.map +1 -1
  39. package/dist/session-submit-verifier.d.ts +44 -0
  40. package/dist/session-submit-verifier.d.ts.map +1 -0
  41. package/dist/session-submit-verifier.js +122 -0
  42. package/dist/session-submit-verifier.js.map +1 -0
  43. package/dist/session.d.ts +9 -0
  44. package/dist/session.d.ts.map +1 -1
  45. package/dist/session.js +42 -1
  46. package/dist/session.js.map +1 -1
  47. package/dist/tmux-manager.d.ts.map +1 -1
  48. package/dist/tmux-manager.js +9 -0
  49. package/dist/tmux-manager.js.map +1 -1
  50. package/dist/types/session.d.ts +26 -0
  51. package/dist/types/session.d.ts.map +1 -1
  52. package/dist/types/session.js.map +1 -1
  53. package/dist/web/public/admin-ui.js.gz +0 -0
  54. package/dist/web/public/api-client.c9b1cddc.js.gz +0 -0
  55. package/dist/web/public/app.8df358cd.js +38 -0
  56. package/dist/web/public/app.8df358cd.js.br +0 -0
  57. package/dist/web/public/app.8df358cd.js.gz +0 -0
  58. package/dist/web/public/approvals-ui.js.gz +0 -0
  59. package/dist/web/public/{constants.258b140f.js → constants.85ed12f3.js} +74 -0
  60. package/dist/web/public/constants.85ed12f3.js.br +0 -0
  61. package/dist/web/public/constants.85ed12f3.js.gz +0 -0
  62. package/dist/web/public/cron-ui.js.gz +0 -0
  63. package/dist/web/public/entrance-animations.js.gz +0 -0
  64. package/dist/web/public/home-sessions.js.gz +0 -0
  65. package/dist/web/public/host-wake-ui.js +440 -0
  66. package/dist/web/public/host-wake-ui.js.br +0 -0
  67. package/dist/web/public/host-wake-ui.js.gz +0 -0
  68. package/dist/web/public/i18n.83924614.js +1 -0
  69. package/dist/web/public/i18n.83924614.js.br +0 -0
  70. package/dist/web/public/i18n.83924614.js.gz +0 -0
  71. package/dist/web/public/image-input.cd4b97c4.js.gz +0 -0
  72. package/dist/web/public/index.html +186 -10
  73. package/dist/web/public/index.html.br +0 -0
  74. package/dist/web/public/index.html.gz +0 -0
  75. package/dist/web/public/input-cjk.8bc46081.js.gz +0 -0
  76. package/dist/web/public/keyboard-accessory.2cf04f17.js.gz +0 -0
  77. package/dist/web/public/mobile-handlers.6f354a87.js.gz +0 -0
  78. package/dist/web/public/mobile-overview.js.gz +0 -0
  79. package/dist/web/public/mobile.6caaa28a.css.gz +0 -0
  80. package/dist/web/public/notification-manager.36ea4624.js.gz +0 -0
  81. package/dist/web/public/orchestrator-panel.js.gz +0 -0
  82. package/dist/web/public/{panels-ui.5b07ad14.js → panels-ui.28df5053.js} +5 -5
  83. package/dist/web/public/panels-ui.28df5053.js.br +0 -0
  84. package/dist/web/public/panels-ui.28df5053.js.gz +0 -0
  85. package/dist/web/public/ralph-panel.6de2d0f8.js.gz +0 -0
  86. package/dist/web/public/ralph-wizard.13a1831e.js.gz +0 -0
  87. package/dist/web/public/readmymind-ui.js.gz +0 -0
  88. package/dist/web/public/reboot-restore-ui.js.gz +0 -0
  89. package/dist/web/public/respawn-ui.ff0dae4c.js.gz +0 -0
  90. package/dist/web/public/sanitize-html.bc7078d6.js.gz +0 -0
  91. package/dist/web/public/session-lineage.js.gz +0 -0
  92. package/dist/web/public/session-ui.d4aea71a.js +88 -0
  93. package/dist/web/public/session-ui.d4aea71a.js.br +0 -0
  94. package/dist/web/public/session-ui.d4aea71a.js.gz +0 -0
  95. package/dist/web/public/settings-ui.4762f480.js +78 -0
  96. package/dist/web/public/settings-ui.4762f480.js.br +0 -0
  97. package/dist/web/public/settings-ui.4762f480.js.gz +0 -0
  98. package/dist/web/public/styles.e34fea04.css +1 -0
  99. package/dist/web/public/styles.e34fea04.css.br +0 -0
  100. package/dist/web/public/styles.e34fea04.css.gz +0 -0
  101. package/dist/web/public/subagent-windows.e6ca799f.js.gz +0 -0
  102. package/dist/web/public/sw.js.gz +0 -0
  103. package/dist/web/public/tab-rail-resize.42c24949.js.gz +0 -0
  104. package/dist/web/public/terminal-keycode229-recovery.fb91b25b.js.gz +0 -0
  105. package/dist/web/public/terminal-ui.35812aa2.js +2 -0
  106. package/dist/web/public/terminal-ui.35812aa2.js.br +0 -0
  107. package/dist/web/public/terminal-ui.35812aa2.js.gz +0 -0
  108. package/dist/web/public/ultracode-panel.js.gz +0 -0
  109. package/dist/web/public/ultracode-windows.js.gz +0 -0
  110. package/dist/web/public/upload.html.gz +0 -0
  111. package/dist/web/public/vendor/dompurify.min.js.gz +0 -0
  112. package/dist/web/public/vendor/marked.min.js.gz +0 -0
  113. package/dist/web/public/vendor/xterm-addon-fit.min.js.gz +0 -0
  114. package/dist/web/public/vendor/xterm-addon-serialize.min.js.gz +0 -0
  115. package/dist/web/public/vendor/xterm-addon-unicode11.min.js.gz +0 -0
  116. package/dist/web/public/vendor/xterm-addon-webgl.min.js.gz +0 -0
  117. package/dist/web/public/vendor/xterm-predictive-echo.bd6882b8.js.gz +0 -0
  118. package/dist/web/public/vendor/xterm-zerolag-input.6fee72f2.js.gz +0 -0
  119. package/dist/web/public/vendor/xterm.css.gz +0 -0
  120. package/dist/web/public/vendor/xterm.min.js.gz +0 -0
  121. package/dist/web/public/voice-input.c4b51eb6.js.gz +0 -0
  122. package/dist/web/public/voice-pcm-worklet.js.gz +0 -0
  123. package/dist/web/public/webview-tabs.js.gz +0 -0
  124. package/dist/web/routes/custom-model-routes.d.ts +173 -0
  125. package/dist/web/routes/custom-model-routes.d.ts.map +1 -1
  126. package/dist/web/routes/custom-model-routes.js +628 -11
  127. package/dist/web/routes/custom-model-routes.js.map +1 -1
  128. package/dist/web/routes/index.d.ts +1 -1
  129. package/dist/web/routes/index.d.ts.map +1 -1
  130. package/dist/web/routes/index.js +1 -1
  131. package/dist/web/routes/index.js.map +1 -1
  132. package/dist/web/routes/session-routes.d.ts +6 -1
  133. package/dist/web/routes/session-routes.d.ts.map +1 -1
  134. package/dist/web/routes/session-routes.js +448 -17
  135. package/dist/web/routes/session-routes.js.map +1 -1
  136. package/dist/web/schemas.d.ts +15 -0
  137. package/dist/web/schemas.d.ts.map +1 -1
  138. package/dist/web/schemas.js +76 -0
  139. package/dist/web/schemas.js.map +1 -1
  140. package/dist/web/server.d.ts +21 -0
  141. package/dist/web/server.d.ts.map +1 -1
  142. package/dist/web/server.js +130 -5
  143. package/dist/web/server.js.map +1 -1
  144. package/dist/web/sse-events.d.ts +25 -2
  145. package/dist/web/sse-events.d.ts.map +1 -1
  146. package/dist/web/sse-events.js +30 -3
  147. package/dist/web/sse-events.js.map +1 -1
  148. package/package.json +1 -1
  149. package/skills/codeman/SKILL.md +75 -26
  150. package/skills/codeman/preamble.sh +66 -19
  151. package/skills/codeman/reference/recipes.md +1 -1
  152. package/dist/web/public/app.6d2dc4e8.js +0 -38
  153. package/dist/web/public/app.6d2dc4e8.js.br +0 -0
  154. package/dist/web/public/app.6d2dc4e8.js.gz +0 -0
  155. package/dist/web/public/constants.258b140f.js.br +0 -0
  156. package/dist/web/public/constants.258b140f.js.gz +0 -0
  157. package/dist/web/public/i18n.5f897ed5.js +0 -1
  158. package/dist/web/public/i18n.5f897ed5.js.br +0 -0
  159. package/dist/web/public/i18n.5f897ed5.js.gz +0 -0
  160. package/dist/web/public/panels-ui.5b07ad14.js.br +0 -0
  161. package/dist/web/public/panels-ui.5b07ad14.js.gz +0 -0
  162. package/dist/web/public/session-ui.42b81477.js +0 -77
  163. package/dist/web/public/session-ui.42b81477.js.br +0 -0
  164. package/dist/web/public/session-ui.42b81477.js.gz +0 -0
  165. package/dist/web/public/settings-ui.58f1d756.js +0 -67
  166. package/dist/web/public/settings-ui.58f1d756.js.br +0 -0
  167. package/dist/web/public/settings-ui.58f1d756.js.gz +0 -0
  168. package/dist/web/public/styles.e6edfb0b.css +0 -1
  169. package/dist/web/public/styles.e6edfb0b.css.br +0 -0
  170. package/dist/web/public/styles.e6edfb0b.css.gz +0 -0
  171. package/dist/web/public/terminal-ui.4f8d5820.js +0 -2
  172. package/dist/web/public/terminal-ui.4f8d5820.js.br +0 -0
  173. package/dist/web/public/terminal-ui.4f8d5820.js.gz +0 -0
Binary file
@@ -0,0 +1,2 @@
1
+ "use strict";(function(e){const t=/^\x1b\[[\?>=]?[\d;]*[cnR]$/,i=/^\x1b\][\d;]*[^\x07\x1b]*(?:\x07|\x1b\\)$/,s=/^\x1b\[<\d+;\d+;\d+[Mm]$/,n=/^\x1b\[M[\s\S]{3}$/,r=/^\x1b\[[IO]$/,c=["input","textarea","select","button","a[href]",'[contenteditable=""]','[contenteditable="true"]','[tabindex]:not([tabindex="-1"])',".keyboard-accessory-bar",".path-picker-overlay"].join(","),m=/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?<>=!]*[ -/]*[@-~]|\x1b[()#][0-9A-Za-z]|\x1b[=>78M]/g,S="\x1B[5~",T="\x1B[6~",C=.5,p=3,I=4,o=/^\x1b(?:\[(?:[ABCDHF]|1;[2-8][ABCDHF]|[1-8](?:;[2-8])?~)|O[ABCDHF])$/,f="\x1B[200~";function _(E){return o.test(E)}const y=/^› /;function b(E){const F=Array.from(E);if(F.length===1){const D=F[0].codePointAt(0);return D===127?"backspace":D>=32?"char":"clear"}return E.charCodeAt(0)===27?"clear":E.charCodeAt(0)>=32?"text":"clear"}function g(E){try{const F=E.buffer.active,D=F.getLine(F.baseY+F.cursorY);return!!D&&y.test(D.translateToString(!0))}catch{return!1}}function L(E){return t.test(E)||i.test(E)}function v(E){return L(E)}function k(E){return r.test(E)||s.test(E)||n.test(E)}const A={og:{background:"#0d0d0d",foreground:"#e0e0e0",cursor:"#e0e0e0",cursorAccent:"#0d0d0d",selectionBackground:"rgba(255,255,255,0.3)",black:"#0d0d0d",red:"#ff6b6b",green:"#51cf66",yellow:"#ffd43b",blue:"#339af0",magenta:"#cc5de8",cyan:"#22b8cf",white:"#e0e0e0",brightBlack:"#495057",brightRed:"#ff8787",brightGreen:"#69db7c",brightYellow:"#ffe066",brightBlue:"#5c7cfa",brightMagenta:"#da77f2",brightCyan:"#66d9e8",brightWhite:"#ffffff"},"daylight-green":{background:"#161b23",foreground:"#dfe6ef",cursor:"#2fd3aa",cursorAccent:"#161b23",selectionBackground:"rgba(47,211,170,0.22)",black:"#161b23",red:"#ff8585",green:"#34d8a0",yellow:"#f0c25a",blue:"#5cc6e8",magenta:"#c79af2",cyan:"#2bcbbb",white:"#dfe6ef",brightBlack:"#5b6675",brightRed:"#ffa0a0",brightGreen:"#5fe6b8",brightYellow:"#ffd884",brightBlue:"#82d4ee",brightMagenta:"#d6b3f7",brightCyan:"#5ee0d4",brightWhite:"#f3f6fa"},"daylight-blue":{background:"#161b23",foreground:"#dfe6ef",cursor:"#38b6f0",cursorAccent:"#161b23",selectionBackground:"rgba(56,182,240,0.22)",black:"#161b23",red:"#ff8585",green:"#34d8a0",yellow:"#f0c25a",blue:"#5cc6e8",magenta:"#c79af2",cyan:"#2bcbbb",white:"#dfe6ef",brightBlack:"#5b6675",brightRed:"#ffa0a0",brightGreen:"#5fe6b8",brightYellow:"#ffd884",brightBlue:"#82d4ee",brightMagenta:"#d6b3f7",brightCyan:"#5ee0d4",brightWhite:"#f3f6fa"},"paper-gray":{background:"#f6f8fa",foreground:"#1f2328",cursor:"#0969da",cursorAccent:"#ffffff",selectionBackground:"rgba(9,105,218,0.2)",black:"#24292f",red:"#cf222e",green:"#1a7f37",yellow:"#9a6700",blue:"#0969da",magenta:"#8250df",cyan:"#1b7c83",white:"#59636e",brightBlack:"#6e7781",brightRed:"#a40e26",brightGreen:"#116329",brightYellow:"#7d4e00",brightBlue:"#0550ae",brightMagenta:"#6639ba",brightCyan:"#116b75",brightWhite:"#1f2328"},"solarized-light":{background:"#fdf6e3",foreground:"#586e75",cursor:"#147ba3",cursorAccent:"#fdf6e3",selectionBackground:"rgba(38,139,210,0.2)",black:"#eee8d5",red:"#dc322f",green:"#758600",yellow:"#9b7800",blue:"#147ba3",magenta:"#d33682",cyan:"#2a9189",white:"#073642",brightBlack:"#93a1a1",brightRed:"#cb4b16",brightGreen:"#657b83",brightYellow:"#586e75",brightBlue:"#268bd2",brightMagenta:"#6c71c4",brightCyan:"#2aa198",brightWhite:"#002b36"},"catppuccin-latte":{background:"#eff1f5",foreground:"#4c4f69",cursor:"#1e66f5",cursorAccent:"#ffffff",selectionBackground:"rgba(30,102,245,0.18)",black:"#5c5f77",red:"#d20f39",green:"#3b8f2b",yellow:"#a86605",blue:"#1e66f5",magenta:"#8839ef",cyan:"#177f86",white:"#6c6f85",brightBlack:"#7c7f93",brightRed:"#b50930",brightGreen:"#2f7622",brightYellow:"#8b5604",brightBlue:"#174fbf",brightMagenta:"#6f2bc5",brightCyan:"#116b71",brightWhite:"#4c4f69"},"rose-pine-dawn":{background:"#faf4ed",foreground:"#575279",cursor:"#286983",cursorAccent:"#fffaf3",selectionBackground:"rgba(40,105,131,0.2)",black:"#575279",red:"#b4637a",green:"#286983",yellow:"#96681f",blue:"#477f91",magenta:"#907aa9",cyan:"#3f7f8b",white:"#6e6a86",brightBlack:"#797593",brightRed:"#984d66",brightGreen:"#1f5266",brightYellow:"#7d5417",brightBlue:"#386b7c",brightMagenta:"#765f90",brightCyan:"#326b76",brightWhite:"#575279"}},x=new Set(["paper-gray","solarized-light","catppuccin-latte","rose-pine-dawn"]);function O(){return typeof document<"u"&&document.documentElement.dataset.skin||"daylight-blue"}function P(){const E=O();return A[E]||A["daylight-blue"]}function w(E=O()){return x.has(E)}e.CodemanTerminalInput={isTerminalQueryResponse:L,shouldSuppressTerminalQueryResponse:v,isTerminalFocusOrMouseReport:k,isComposerNavKey:_,classifyPredictInput:b,isCodexComposerRow:g,CODEX_COMPOSER_ROW_RE:y,BRACKETED_PASTE_START:f,USER_SCROLL_STICKY_SUPPRESS_MS:1500,TOUCH_COMPAT_MOUSE_SUPPRESS_MS:450,REPLAY_ESCAPE_RE:m,KEY_PAGE_UP:S,KEY_PAGE_DOWN:T,PAGE_KEY_SCREEN_FRACTION:C,PAGE_KEY_MAX_PER_BATCH:p,TUI_PROMPT_DEFAULT_ROWS_FROM_BOTTOM:I,MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR:c,MOBILE_KEYBOARD_DISMISS_TAP_SLOP:8,TOUCH_SELECT_LONG_PRESS_MS:350,TOUCH_SELECT_FOCUS_GUARD_MS:800},e.CODEMAN_XTERM_THEMES=A,e.codemanCurrentXtermTheme=P,e.codemanCurrentSkinIsLight=w})(window),Object.assign(CodemanApp.prototype,{_destroyKeyCode229Recovery(){try{this._keyCode229Recovery?.destroy?.()}catch{}this._keyCode229Recovery=null},initTerminal(){const e=parseInt(localStorage.getItem("codeman-scrollback")),t=Number.isFinite(e)&&e>0?Math.max(e,DEFAULT_SCROLLBACK):DEFAULT_SCROLLBACK;this._destroyKeyCode229Recovery();const i=this.loadAppSettingsFromStorage?.()||{};if(this.terminal=new Terminal({theme:{...window.codemanCurrentXtermTheme()},fontFamily:window.CodemanTerminalFont.resolve(i.terminalFontFamily),...window.CodemanTerminalFont.resolveWeights(i),fontSize:MobileDetection.getDeviceType()==="mobile"?10:14,lineHeight:1.2,cursorBlink:!1,cursorStyle:"block",minimumContrastRatio:window.codemanCurrentSkinIsLight()?4.5:1,scrollback:t,allowTransparency:!0,allowProposedApi:!0}),this.fitAddon=new FitAddon.FitAddon,this.terminal.loadAddon(this.fitAddon),this._xtermSnapshots=new Map,typeof SerializeAddon<"u")try{this._serializeAddon=new SerializeAddon.SerializeAddon,this.terminal.loadAddon(this._serializeAddon)}catch{this._serializeAddon=null}if(typeof Unicode11Addon<"u")try{const o=new Unicode11Addon.Unicode11Addon;this.terminal.loadAddon(o),this.terminal.unicode.activeVersion="11"}catch{}const s=document.getElementById("terminalContainer");this.terminal.open(s),this._installMobileTapMouseGuard(),this._installShiftDragSelection(),this._installTouchSelectionFocusGuard(),this.terminal.attachCustomKeyEventHandler(o=>{try{this._keyCode229Recovery?.handleKeyEvent?.(o)}catch{}if(o.isComposing||o.key==="Process"||o.keyCode===229)return!0;if(o.altKey&&!o.ctrlKey&&!o.shiftKey&&/^(Digit[1-9]|BracketLeft|BracketRight|KeyK)$/.test(o.code||"")||o.type==="keydown"&&this.shouldOpenCommandPaletteFromShortcut?.(o))return!1;if(this.shouldCopyTerminalSelectionFromShortcut?.(o)){const f=this.cleanedTerminalSelection();return f.trim()?(o.preventDefault(),this.copyTerminalSelection(f),!1):(this.terminal?.hasSelection?.()&&(this.terminal.clearSelection?.(),this.showToast("Nothing to copy","warning")),o.shiftKey?(o.preventDefault(),!1):!0)}if(o.type==="keydown"&&this.shouldToggleSessionSidebarFromShortcut?.(o))return!1;if((o.ctrlKey||o.metaKey)&&o.key==="v"&&o.type==="keydown")return this.activeSessionId&&this._handleImagePaste&&this._handleImagePaste(),!1;if(o.type==="keydown"&&o.key.toLowerCase()==="z"&&o.ctrlKey&&!o.altKey&&!o.metaKey&&!o.shiftKey){const f=this.activeSessionId?this.sessions.get(this.activeSessionId):null;if(f&&f.mode!=="shell")return o.preventDefault(),!1}if(o.key==="Enter"&&(o.shiftKey||o.ctrlKey)&&o.type==="keydown"){if(this.activeSessionId)if(this._localEchoEnabled){const f=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),f&&(this._pendingInput+=f,p()),setTimeout(()=>{fetch(`/api/sessions/${this.activeSessionId}/send-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:o.ctrlKey?"C-Enter":"S-Enter"})})},f?80:0)}else fetch(`/api/sessions/${this.activeSessionId}/send-key`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({key:o.ctrlKey?"C-Enter":"S-Enter"})});return!1}return!0}),this._webglAddon=null;const n=new URLSearchParams(location.search),r=(()=>{try{const o=localStorage.getItem("codeman-webgl-disabled");if(!o)return!1;const{at:f}=JSON.parse(o);return Date.now()-f>WEBGL_FALLBACK.STICKY_EXPIRY_MS?(localStorage.removeItem("codeman-webgl-disabled"),!1):!0}catch{return!1}})(),l=this.loadAppSettingsFromStorage(),a=this.getDefaultSettings(),h=l.webglRendererEnabled??a.webglRendererEnabled,{skip:d,clearSticky:u}=shouldSkipWebGL({deviceType:MobileDetection.getDeviceType(),noWebglParam:n.has("nowebgl"),forceParam:n.get("webgl")==="force",stickyDisabled:r,userPrefEnabled:h});if(u)try{localStorage.removeItem("codeman-webgl-disabled")}catch{}if(d&&r&&console.log("[CRASH-DIAG] WebGL sticky-disabled from prior stalls \u2014 DOM renderer in use. Re-enable: ?webgl=force"),!d)if(typeof WebglAddon<"u")this._initWebGL();else{const o=document.createElement("script");o.src="vendor/xterm-addon-webgl.min.js",o.onload=()=>this._initWebGL(),o.onerror=()=>console.warn("[CRASH-DIAG] Failed to load WebGL addon \u2014 using canvas renderer"),document.head.appendChild(o)}this._localEchoOverlay=new LocalEchoOverlay(this.terminal),this._predictiveEcho=typeof PredictiveEchoOverlay<"u"?new PredictiveEchoOverlay(this.terminal):null,this._predictiveEcho?.setPredictWhen(o=>window.CodemanTerminalInput.isCodexComposerRow(o)),MobileDetection.isTouchDevice()&&(this.terminal.onCursorMove(()=>this._syncMobileHelperTextareaToCursor()),this.terminal.onRender(()=>this._syncMobileHelperTextareaToCursor())),this._cjkInput=null,typeof CjkInput<"u"&&(this._cjkInput=CjkInput.init({send:o=>{this._handleCjkInput(o)}}));const c=this.terminal.focus.bind(this.terminal);this.terminal.focus=()=>{const o=document.getElementById("cjkInput");o?.classList.contains("cjk-input-visible")?o.focus():c()},MobileDetection.getDeviceType()==="mobile"&&document.body.classList.contains("safari-browser")?requestAnimationFrame(()=>{this.fitAddon.fit(),requestAnimationFrame(()=>this.fitAddon.fit())}):this.fitAddon.fit(),this._terminalFontReady=this._awaitTerminalFont(),this.registerFilePathLinkProvider(),this.terminal.onSelectionChange?.(()=>{if(!this.terminal?.hasSelection?.()){this._touchSelecting=!1,this._touchSelectionActive=!1,this._touchSelectionAnchor=null,this._hideTouchSelectionBar(),this._autoCopyPending=!1;return}this._autoCopyPending=!0}),this._autoCopyListenerInstalled||(this._autoCopyListenerInstalled=!0,document.addEventListener("mouseup",()=>this._flushAutoCopySelection())),s.addEventListener("wheel",o=>{const f=this.terminal?.modes?.mouseTrackingMode;if(f&&f!=="none"||this.terminal?.buffer?.active?.type==="alternate")return;if(o.preventDefault(),o.stopPropagation(),this._shouldForwardWheelToApp(o)){this._logScrollRouting("forward-sgr"),this._forwardScrollToApp(o.clientX,o.clientY,this._wheelScrollLines(o));return}const _=this._wheelScrollLinesFloat(o);this._maybePageCliTranscript(o,_)||(this._logScrollRouting("local-scrollback"),this._noteTerminalUserScroll(_),this._smoothScrollBy(_))},{passive:!1,capture:!0});{const o=()=>this.terminal._core?._renderService?.dimensions?.css?.cell?.height||13;let f=0,_=0,y=0,b=0,g=null,L=!1;const v=M=>{const R=b?(M-b)/16.67:1;if(b=M,!L&&Math.abs(y)>.3){const B=Math.round(y/o());B!==0&&(this._shouldForwardWheelToApp({shiftKey:!1})?this._forwardScrollToApp(f,_,B):this._maybePageCliTranscript({shiftKey:!1},B)||(this.terminal.scrollLines(B),this._maybeLoadMoreHistoryOnScroll(B))),y*=.92,g=requestAnimationFrame(v)}else L?g=requestAnimationFrame(v):(g=null,y=0)};let k=0,A=!1,x=null,O=0,P=0,w=0,E=!1,F=null;const D=window.CodemanTerminalInput.MOBILE_KEYBOARD_DISMISS_TAP_SLOP;s.addEventListener("touchstart",M=>{if(!M.target?.closest?.(".term-select-bar")&&(M.touches.length!==1&&(clearTimeout(x),x=null),M.touches.length===1)){f=M.touches[0].clientX,_=M.touches[0].clientY,w=_,y=0,k=0,L=!0,A=!1,E=this._isMobileTerminalInputFocused();const R=this._classifyMobileTerminalTap(f,_);F={x:f,y:_,intent:R},R==="content"&&(M.preventDefault(),this._blurMobileTerminalInput()),O=f,P=_,clearTimeout(x),x=setTimeout(()=>{x=null,this._beginTouchSelection(O,P)},window.CodemanTerminalInput.TOUCH_SELECT_LONG_PRESS_MS),b=0,g&&(cancelAnimationFrame(g),g=null)}},{passive:!1}),s.addEventListener("touchmove",M=>{if(this._touchSelecting){M.preventDefault();const R=M.touches[0];R&&this._extendTouchSelection(R.clientX,R.clientY);return}if(x&&M.touches.length===1){const R=M.touches[0];(Math.abs(R.clientX-O)>D||Math.abs(R.clientY-P)>D)&&(clearTimeout(x),x=null)}if(M.touches.length===1&&L){const R=M.touches[0].clientY;if(!A&&Math.abs(R-w)>=D&&(A=!0),!A)return;M.preventDefault();const B=_-R;k+=B,y=B*1.2,f=M.touches[0].clientX,_=R;const H=o(),N=Math.trunc(k/H);N!==0&&(this._shouldForwardWheelToApp({shiftKey:!1})?(this._logScrollRouting("forward-sgr"),this._forwardScrollToApp(f,_,N)):this._maybePageCliTranscript({shiftKey:!1},N)||(this._logScrollRouting("local-scrollback"),this._noteTerminalUserScroll(N),this.terminal.scrollLines(N),this._maybeLoadMoreHistoryOnScroll(N)),k-=N*H)}},{passive:!1}),s.addEventListener("touchend",M=>{if(!M.target?.closest?.(".term-select-bar")){if(clearTimeout(x),x=null,L=!1,this._touchSelecting){M.preventDefault(),y=0,this._endTouchSelectionGesture(),E=!1;return}if(!g&&Math.abs(y)>.3&&(g=requestAnimationFrame(v)),!A&&this.terminal){const R=M.changedTouches&&M.changedTouches[0];if(R){this._suppressTrustedTapMouseEvents();const B=F&&F.x===R.clientX&&F.y===R.clientY?F.intent:null;this._handleMobileTerminalTap(R,E,B)}}E=!1}},{passive:!1}),s.addEventListener("contextmenu",M=>{if(x!==null||this._touchSelecting||this._touchSelectionActive){M.preventDefault();return}if(!this.terminal?.hasSelection?.())return;const R=this.terminal.getSelection();R&&(M.preventDefault(),this.copyTerminalSelection(R))}),s.addEventListener("touchcancel",()=>{clearTimeout(x),x=null,L=!1,this._touchSelecting=!1,y=0,k=0,E=!1},{passive:!0})}s.addEventListener("click",o=>this._handleDesktopTerminalClick(o)),this._installMobileKeyboardDismiss(),this.showWelcome(),this.initImageInput(),this._chunkedWriteGen=0,this._bufferLoadSeq=0,this._bufferLoadOwner=null,this._lastUserScrollUpAt=null,this._resizeTimeout=null,this._lastResizeDims=null;const S=40,T=10,C=()=>{this._tabRailResizeOwnsObserver||(this._resizeTimeout&&clearTimeout(this._resizeTimeout),this._resizeTimeout=setTimeout(()=>{this._resizeTimeout=null,this.fitAddon&&this.fitAddon.fit(),this.flickerFilterBuffer&&(this.flickerFilterTimeout&&(clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=null),this.flushFlickerBuffer());const o=typeof KeyboardHandler<"u"&&KeyboardHandler.keyboardVisible,f=!this.isSoloWindow&&this.detachedSessions?.has(this.activeSessionId);if(this.activeSessionId&&!o&&!f){const _=this.fitAddon.proposeDimensions(),y=_?Math.max(_.cols,S):S,b=_?Math.max(_.rows,T):T;if(!this._lastResizeDims||y!==this._lastResizeDims.cols||b!==this._lastResizeDims.rows){const g=this.activeSessionId?this.sessions.get(this.activeSessionId):null;g&&g.mode!=="shell"&&this.terminal&&this.isTerminalAtBottom()&&this.terminal.write("\x1B[3J\x1B[H\x1B[2J"),this._lastResizeDims={cols:y,rows:b};const L=typeof MobileDetection<"u"&&MobileDetection.getDeviceType?MobileDetection.getDeviceType():"desktop";let v=!1;if(this._wsReady&&this._wsSessionId===this.activeSessionId)try{this._ws.send(JSON.stringify({t:"z",c:y,r:b,v:L})),v=!0}catch{}v||fetch(`/api/sessions/${this.activeSessionId}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cols:y,rows:b,viewportType:L})}).catch(()=>{})}}this.applyLineageLineSettings?.(),this.updateConnectionLines(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender()},300))};window.addEventListener("resize",C),this.terminalResizeObserver&&this.terminalResizeObserver.disconnect(),this.terminalResizeObserver=new ResizeObserver(C),this.terminalResizeObserver.observe(s),this._pendingInput="",this._inputFlushTimeout=null,this._lastKeystrokeTime=0;const p=()=>{if(this._inputFlushTimeout=null,this._pendingInput&&this.activeSessionId){const o=this._pendingInput,f=this.activeSessionId;this._pendingInput="",this._sendInputAsync(f,o)}},I=o=>{if(!/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(o)&&(window.cjkActive||document.activeElement?.id==="cjkInput")){const _=document.getElementById("cjkInput");_?.classList.contains("cjk-input-visible")&&document.activeElement===this.terminal.textarea&&!window.CodemanTerminalInput?.shouldSuppressTerminalQueryResponse(o)&&(_crashDiag.log("CJK regain-focus (onData swallowed input)"),_.focus());return}if(this.activeSessionId){if(window.CodemanTerminalInput?.shouldSuppressTerminalQueryResponse(o))return;typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.isCtrlArmed?.()&&!window.CodemanTerminalInput?.isTerminalFocusOrMouseReport(o)&&(o=KeyboardAccessoryBar.consumeCtrl(o)),this._lastTerminalData={data:o,time:performance.now()};const _=this._localEchoEnabled&&this._echoPassthroughSessions?.has(this.activeSessionId);if(_&&(o==="\r"||o==="")&&this._echoPassthroughSessions.delete(this.activeSessionId),this._localEchoEnabled&&!_){if(o==="\x7F"){const b=this._localEchoOverlay?.removeChar();if(b==="flushed"){const{count:g,text:L}=this._localEchoOverlay.getFlushed();this._flushedOffsets?.has(this.activeSessionId)&&(g===0?(this._flushedOffsets.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId)):(this._flushedOffsets.set(this.activeSessionId,g),this._flushedTexts?.set(this.activeSessionId,L))),this._pendingInput+=o,p()}else b===!1&&(this._pendingInput+=o,p());return}if(/^[\r\n]+$/.test(o)){const b=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),b&&(this._pendingInput+=b,p()),setTimeout(()=>{this._pendingInput+="\r",p()},80);return}if(o.length>1&&o.charCodeAt(0)>=32){this._localEchoOverlay?.appendText(o);return}if(o.charCodeAt(0)<32){if(o.length>1&&o.charCodeAt(0)===27){if(o.startsWith(window.CodemanTerminalInput.BRACKETED_PASTE_START)){const g=!!this._localEchoOverlay?.pendingText;this._flushLocalEchoPending(),g?(p(),setTimeout(()=>{this._pendingInput+=o,p()},80)):(this._pendingInput+=o,p());return}if(window.CodemanTerminalInput.isComposerNavKey(o)){this._flushLocalEchoPending(),this._echoPassthroughSessions||(this._echoPassthroughSessions=new Set),this._echoPassthroughSessions.add(this.activeSessionId),this._pendingInput+=o,p();return}this._pendingInput+=o,p();return}if(this._restoringFlushedState){this._pendingInput+=o,p();return}if(o===" "){const g=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),g&&(this._pendingInput+=g),this._pendingInput+=o,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null);let L="";try{const k=this._localEchoOverlay?.findPrompt?.();if(k){const A=this.terminal.buffer.active,x=A.getLine(A.viewportY+k.row);x&&(L=x.translateToString(!0).slice(k.col+2).trimEnd())}}catch{}this._tabCompletionBaseText=L,p(),this._tabCompletionSessionId=this.activeSessionId,this._tabCompletionRetries=0,this._tabCompletionFallback&&clearTimeout(this._tabCompletionFallback);const v=this;this._tabCompletionFallback=setTimeout(()=>{if(v._tabCompletionFallback=null,!v._tabCompletionSessionId||v._tabCompletionSessionId!==v.activeSessionId)return;const k=v._localEchoOverlay;!k||k.pendingText||v.terminal.write("",()=>{if(!v._tabCompletionSessionId)return;k.resetBufferDetection();const A=k.detectBufferText();A&&A!==v._tabCompletionBaseText&&(v._tabCompletionSessionId=null,v._tabCompletionRetries=0,v._tabCompletionBaseText=null,k.rerender())})},300);return}const b=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),b&&(this._pendingInput+=b),this._pendingInput+=o,this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),p();return}if(o.length===1&&o.charCodeAt(0)>=32){this._localEchoOverlay?.addChar(o);return}}if(this._predictHookOnData(o),this._pendingInput+=o,o.charCodeAt(0)<32||o.length>1){this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),p();return}const y=performance.now();y-this._lastKeystrokeTime>50?(this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._lastKeystrokeTime=y,p()):(this._lastKeystrokeTime=y,this._inputFlushTimeout||(this._inputFlushTimeout=setTimeout(p,0)))}};try{this._keyCode229Recovery=window.CodemanKeyCode229Recovery?.create?.({textarea:this.terminal.textarea,emitRecovered:o=>I(o),isScreenReaderMode:()=>this.terminal?.options?.screenReaderMode===!0})}catch{this._keyCode229Recovery=null}this.terminal.onData(o=>{try{const f=window.CodemanTerminalInput;!f?.shouldSuppressTerminalQueryResponse(o)&&!f?.isTerminalFocusOrMouseReport(o)&&this._keyCode229Recovery?.notifyCanonicalData?.()}catch{}I(o)})},registerFilePathLinkProvider(){const e=this;let t=-1;const i={provideLinks(s,n){s!==t&&(t=s,console.debug("[LinkProvider] Checking line:",s));const r=e.terminal.buffer.active;if(!r.getLine(s-1)){n(void 0);return}const h=window.CodemanTerminalLines?.terminalLogicalLine(r,s-1,e.terminal.cols,12);if(!h){n(void 0);return}const d=h.text,u=f=>{const _=h.offsetToCell(f);return{x:_.col+1,y:_.row+1}};if(!d||!d.includes("/")){n(void 0);return}const c=[],m=/https?:\/\/(?:[^\s"'<>|;&)\]\x00-\x1f]|&(?!&))+/g,S=(f,_)=>{const y=f.replace(/[.,;:!?)&]+$/,""),b=d.indexOf(y,_);if(b===-1)return;const g=u(b),L=u(b+y.length);c.some(v=>v.range.start.x===g.x&&v.range.start.y===g.y)||c.push({text:y,range:{start:g,end:L},decorations:{pointerCursor:!0,underline:!0},activate(v,k){e.openLinkThroughWebTabIfLoopback?.(k)||window.open(k,"_blank","noopener,noreferrer")},hover(){e._linkHovered=!0},leave(){e._linkHovered=!1}})},T=/\b(tail|cat|head|less|grep|watch|vim|nano)\s+(?:[^\s\/]+\s+){0,4}(\/[^\s"'<>|;&\n\x00-\x1f]+)/g,C=absoluteFilePathPattern(),p=/Bash\([^)]*?(\/(?:home|tmp|var|etc|opt)[^\s"'<>|;&\)\n\x00-\x1f]+)/g,I=(f,_)=>{const y=d.indexOf(f,_);if(y===-1)return;const b=u(y),g=u(y+f.length);c.some(L=>L.range.start.x===b.x&&L.range.start.y===b.y)||c.push({text:f,range:{start:b,end:g},decorations:{pointerCursor:!0,underline:!0},activate(L,v){if(previewsInFileViewer(v)||e._isExternalPreviewPath(v,e.activeSessionId)){e.openFilePreview(v,e.activeSessionId);return}e.openLogViewerWindow(v,e.activeSessionId)},hover(){e._linkHovered=!0},leave(){e._linkHovered=!1}})};let o;for(m.lastIndex=0;(o=m.exec(d))!==null;)S(o[0],o.index);for(T.lastIndex=0;(o=T.exec(d))!==null;)I(o[2],o.index);for(C.lastIndex=0;(o=C.exec(d))!==null;)I(o[1],o.index);for(p.lastIndex=0;(o=p.exec(d))!==null;)I(o[1],o.index);c.length>0&&console.debug("[LinkProvider] Found links:",c.map(f=>f.text)),n(c.length>0?c:void 0)}};this._terminalLinkProvider=i,this.terminal.registerLinkProvider(i),console.log("[LinkProvider] File path link provider registered")},_terminalLinkAtPoint(e,t){const i=this._terminalLinkProvider,s=this.terminal?.buffer?.active;if(!i||!s)return null;const n=this._clientPointToCell(e,t);if(!n)return null;const r=(s.viewportY||0)+n.row;let l=null;try{i.provideLinks(r,d=>{l=d||[]})}catch{return null}if(!l||l.length===0)return null;const a=Math.max(1,this.terminal.cols||1),h=r*a+n.col;return l.find(d=>{const u=d?.range?.start,c=d?.range?.end;return!u||!c?!1:u.y*a+u.x<=h&&h<=c.y*a+c.x})||null},_tapIsOnCaretLine(e,t){const i=this.terminal?.buffer?.active;if(!i?.getLine)return!1;const s=this._clientPointToCell(e,t);if(!s)return!1;const n=Math.max(1,this.terminal.rows||1),r=Math.max(0,Math.min(n-1,i.cursorY||0)),l=s.row-1;if(l===r)return!0;let a=r;for(;a>0&&i.getLine(i.viewportY+a)?.isWrapped;)a--;let h=r;for(;h+1<n&&i.getLine(i.viewportY+h+1)?.isWrapped;)h++;return l>=a&&l<=h},_activateTerminalLinkAtPoint(e,t){const i=this._terminalLinkAtPoint(e,t);if(!i||typeof i.activate!="function")return!1;try{i.activate(null,i.text)}catch(s){return console.warn("[LinkProvider] tap activation failed:",s),!1}return!0},_installTouchSelectionFocusGuard(){const e=this.terminal?.textarea;!e||e._codemanSelectionFocusGuard||(e._codemanSelectionFocusGuard=!0,e.addEventListener("focus",()=>{this._touchSelectionFocusGuarded()&&this._blurMobileTerminalInput()}))},_touchSelectionFocusGuarded(){return this._touchSelecting?!0:performance.now()<(this._touchSelectionFocusGuardUntil||0)},_armTouchSelectionFocusGuard(){this._touchSelectionFocusGuardUntil=performance.now()+(window.CodemanTerminalInput?.TOUCH_SELECT_FOCUS_GUARD_MS||800)},_touchSelectionCellAt(e,t){const i=this._clientPointToCell(e,t),s=this.terminal?.buffer?.active;return!i||!s?null:{col:i.col-1,row:(s.viewportY||0)+i.row-1}},_touchSelectionLogicalLine(e){const t=this.terminal?.buffer?.active,i=Math.max(1,this.terminal?.cols||1);return!t||typeof window.CodemanTerminalLines?.terminalLogicalLine!="function"?null:window.CodemanTerminalLines.terminalLogicalLine(t,e,i)},_touchSelectionWordAt(e){const t=Math.max(1,this.terminal?.cols||1),i=this._touchSelectionLogicalLine(e.row);if(!i)return null;const s=i.cellToOffset(e.row,e.col);if(s<0)return null;const n=i.text[s];if(!n||!n.trim())return null;let r=s;for(;r>0&&i.text[r-1]&&i.text[r-1].trim();)r--;let l=s;for(;l+1<i.text.length&&i.text[l+1]&&i.text[l+1].trim();)l++;const a=i.offsetToCell(r),h=i.offsetToCell(l),d=a.row*t+a.col,u=h.row*t+h.col-d+1;return u>0?{index:d,length:u}:null},_applyTouchSelection(e,t){const i=Math.max(1,this.terminal?.cols||1);t<=0||this.terminal?.select?.(e%i,Math.floor(e/i),t)},_beginTouchSelection(e,t){const i=this._touchSelectionCellAt(e,t);if(!i)return!1;const s=this._touchSelectionWordAt(i);if(!s)return!1;this._blurMobileTerminalInput(),this._touchSelectionAnchor=s,this._touchSelecting=!0,this._touchSelectionActive=!0,this._suppressTrustedTapMouseEvents(),this._armTouchSelectionFocusGuard(),this._applyTouchSelection(s.index,s.length);try{navigator.vibrate?.(15)}catch{}return this._showTouchSelectionBar(),!0},_extendTouchSelection(e,t){const i=this._touchSelectionAnchor,s=this._touchSelectionCellAt(e,t);if(!i||!s)return;const n=Math.max(1,this.terminal?.cols||1),r=s.row*n+s.col,l=Math.min(i.index,r),a=Math.max(i.index+i.length,r+1);this._applyTouchSelection(l,a-l),this._armTouchSelectionFocusGuard(),this._positionTouchSelectionBar()},_endTouchSelectionGesture(){this._touchSelecting=!1,this._suppressTrustedTapMouseEvents(),this._armTouchSelectionFocusGuard(),this._positionTouchSelectionBar(),this._flushAutoCopySelection()},_selectTouchSelectionLine(){const e=this._touchSelectionAnchor,t=Math.max(1,this.terminal?.cols||1);if(!e)return;const i=this._touchSelectionLogicalLine(Math.floor(e.index/t));if(!i)return;const n=(this.terminal?.buffer?.active?.getLine(i.endRow)?.translateToString(!0)||"").length,r=i.startRow*t,l=i.endRow*t+Math.max(0,n-1)-r+1;l<=0||(this._touchSelectionAnchor={index:r,length:l},this._applyTouchSelection(r,l),this._positionTouchSelectionBar(),this._flushAutoCopySelection())},async _copyTouchSelection(){const e=await this.copyTerminalSelection();return this._clearTouchSelection(),typeof MobileDetection<"u"&&MobileDetection.isTouchDevice?.()&&this._blurMobileTerminalInput(),e},_clearTouchSelection(){this._touchSelecting=!1,this._touchSelectionActive=!1,this._touchSelectionAnchor=null,this.terminal?.clearSelection?.(),this._hideTouchSelectionBar()},_ensureTouchSelectionBar(){if(this._touchSelectionBar?.isConnected)return this._touchSelectionBar;const e=document.getElementById("terminalContainer");if(!e)return null;const t=document.createElement("div");return t.className="term-select-bar",t.setAttribute("role","toolbar"),t.innerHTML='<button type="button" class="term-select-btn" data-act="copy">Copy</button><button type="button" class="term-select-btn" data-act="line">Line</button><button type="button" class="term-select-btn term-select-btn--close" data-act="close" aria-label="Clear selection">\u2715</button>',t.addEventListener("click",i=>{const s=i.target?.closest?.("[data-act]")?.dataset?.act;s&&(i.preventDefault(),i.stopPropagation(),s==="copy"?this._copyTouchSelection():s==="line"?this._selectTouchSelectionLine():this._clearTouchSelection())}),e.appendChild(t),this._touchSelectionBar=t,t},_showTouchSelectionBar(){const e=this._ensureTouchSelectionBar();e&&(e.classList.add("visible"),this._positionTouchSelectionBar())},_hideTouchSelectionBar(){this._touchSelectionBar?.classList.remove("visible")},_positionTouchSelectionBar(){const e=this._touchSelectionBar,t=document.getElementById("terminalContainer"),i=this.terminal?.element?.querySelector(".xterm-screen"),s=this.terminal?._core?._renderService?.dimensions?.css?.cell,n=this.terminal?.getSelectionPosition?.(),r=this.terminal?.buffer?.active;if(!e||!t||!i||!s?.height||!n||!r)return;const l=i.getBoundingClientRect(),a=t.getBoundingClientRect(),h=p=>p-(r.viewportY||0),d=l.top-a.top+h(n.start.y)*s.height,u=l.top-a.top+(h(n.end.y)+1)*s.height,c=e.offsetHeight||36,m=6;let S=d-c-m;S<0&&(S=u+m),S=Math.max(0,Math.min(S,a.height-c));const T=l.left-a.left+n.start.x*(s.width||8),C=e.offsetWidth||150;e.style.top=`${Math.round(S)}px`,e.style.left=`${Math.round(Math.max(0,Math.min(T,a.width-C)))}px`},showWelcome(){if(this.shouldUseMobileOverview?.()){const t=document.getElementById("welcomeOverlay");t&&t.classList.remove("visible"),this.hideHomeSessions?.(),this.showMobileOverview(),this._updateCjkInputState?.();return}this.hideMobileOverview?.();const e=document.getElementById("welcomeOverlay");e&&(e.classList.add("visible"),this.loadTunnelStatus(),this.applyWelcomeCliVisibility(),this.loadHistorySessions(),this.initSearchPanel(),this.showHomeSessions?.()),this._updateCjkInputState?.()},hideWelcome(){this.hideMobileOverview?.(),this.hideHomeSessions?.();const e=document.getElementById("welcomeOverlay");e&&e.classList.remove("visible");const t=document.getElementById("welcomeQr");t&&(clearTimeout(this._welcomeQrShrinkTimer),t.classList.remove("expanded")),this._updateCjkInputState?.()},async _fetchHistorySessions(){const i=(await(await fetch("/api/history/sessions")).json()).data?.sessions||[];if(i.length===0)return[];const s=new Map;for(const r of i){const l=r.projectKey||r.workingDir;s.has(l)||s.set(l,[]),s.get(l).push(r)}const n=[];for(const[,r]of s)n.push(...r.slice(0,3));return n.sort((r,l)=>new Date(l.lastModified)-new Date(r.lastModified)),n},async _fetchUnifiedSessions(e=60){const t=await fetch("/api/sessions/unified?limit="+e),i=await t.json().catch(()=>null);if(!t.ok||!i||i.success===!1||!i.data)throw new Error(i?.error||`unified sessions request failed (HTTP ${t.status})`);return i.data.sessions||[]},_worktreeLabel(e){const t=e&&e.worktreeName;if(!t)return"";let i=e.gitBranch||"";return(i===t||i===`worktree-${t}`)&&(i=""),i.length>24&&(i=i.slice(0,23)+"\u2026"),"\u2442 "+[t,i].filter(Boolean).join(" \xB7 ")},_resolveCaseLabel(e,t){if(!e)return"";let i=null;for(const s of t||[])if(!(!s||!s.path)){if(e===s.path)return`#${s.name}`;if(e.startsWith(s.path+"/")){const n=s.path.length;(!i||n>i.len)&&(i={name:s.name,suffix:e.slice(n),len:n})}}return i?`#${i.name}${i.suffix}`:e.split("/").pop()||e},_shortenHomePath(e){return(e||"").replace(/^\/(?:home|Users)\/[^/]+(?=\/|$)/,"~")},_buildHistoryItem(e,t,i){const s=i?.showViewAll!==!1,n=typeof e.sizeBytes=="number",r=n?e.sizeBytes<1024?`${e.sizeBytes}B`:e.sizeBytes<1048576?`${(e.sizeBytes/1024).toFixed(0)}K`:`${(e.sizeBytes/1048576).toFixed(1)}M`:"",l=typeof e.lastActivityAt=="number"?e.lastActivityAt:e.lastModified?Date.parse(e.lastModified):NaN;let a="";if(!Number.isNaN(l)){const w=new Date(l);a=w.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+w.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1})}const h=this._shortenHomePath(e.workingDir),d=this._resolveCaseLabel(e.workingDir,t),u=Array.isArray(e.sources)&&e.sources.includes("live"),c=e.pinned===!0,m=document.createElement("div");m.className="history-item"+(c?" is-pinned":""),m.title=e.workingDir||"";const S=document.createElement("div");S.className="history-item-main",S.addEventListener("click",i?.onActivate||(()=>{u&&this.sessions.has(e.sessionId)?this.selectSession(e.sessionId):this.resumeHistorySession(e.claudeSessionId||e.sessionId,e.workingDir||"",e.name,e.mode,e.resumeId)}));const T=document.createElement("div");T.className="history-item-text";const C=document.createElement("span");if(C.className="history-item-title",c){const w=document.createElement("span");w.className="history-item-pin",w.textContent="\u{1F4CC}",w.setAttribute("aria-label","Pinned"),w.title="Pinned",C.appendChild(w)}C.appendChild(document.createTextNode(this._historyRowLabel(e,h)));const p=document.createElement("div");if(p.className="history-item-badges",e.mode){const w=document.createElement("span");w.className="history-item-badge history-item-badge-mode",w.textContent=e.mode,p.appendChild(w)}const I=this._worktreeLabel(e);if(I){const w=document.createElement("span");w.className="history-item-badge history-item-badge-worktree",w.textContent=I,w.title=e.worktreeRepo?`worktree of ${e.worktreeRepo}`:I,p.appendChild(w)}if(u){const w=document.createElement("span");w.className="history-item-badge history-item-badge-live",w.textContent="LIVE",p.appendChild(w)}const o=document.createElement("span");o.className="history-item-subtitle",d.startsWith("#")&&o.classList.add("is-case"),o.textContent=d,T.append(C),p.childElementCount>0&&T.append(p),T.append(o);const f=document.createElement("span");f.className="history-item-meta",f.textContent=a;const _=document.createElement("button");_.className="history-item-expand",_.type="button",_.setAttribute("aria-haspopup","menu"),_.setAttribute("aria-label","Session actions"),_.setAttribute("aria-expanded","false"),_.textContent="\u22EF",S.append(T,f,_);const y=document.createElement("div");y.className="history-item-detail",y.hidden=!0;const b=document.createElement("div");b.className="history-detail-row";const g=document.createElement("span");g.className="history-detail-label",g.textContent="Prompt";const L=document.createElement("span");L.className="history-detail-value history-detail-prompt",L.textContent=e.firstPrompt||"(no prompt captured)",b.append(g,L);let v=null;if(e.lastPrompt&&e.lastPrompt!==e.firstPrompt){v=document.createElement("div"),v.className="history-detail-row";const w=document.createElement("span");w.className="history-detail-label",w.textContent="Last prompt";const E=document.createElement("span");E.className="history-detail-value history-detail-prompt",E.textContent=e.lastPrompt,v.append(w,E)}const k=document.createElement("div");k.className="history-detail-row";const A=document.createElement("span");A.className="history-detail-label",A.textContent="Path";const x=document.createElement("span");x.className="history-detail-value history-detail-path",x.textContent=h,k.append(A,x);const O=document.createElement("div");O.className="history-detail-row history-detail-meta";const P=[];if(a&&P.push(a),n&&P.push(r),P.push(e.sessionId.slice(0,8)),O.textContent=P.join(" \xB7 "),y.append(b),v&&y.append(v),y.append(k,O),s&&e.projectKey){const w=document.createElement("div");w.className="history-detail-row history-detail-actions";const E=document.createElement("button");E.type="button",E.className="history-view-all-btn",E.textContent="View all in this folder",E.addEventListener("click",F=>{F.stopPropagation(),this.openFolderHistoryModal(e.projectKey,e.workingDir,t)}),w.appendChild(E),y.appendChild(w)}return _.addEventListener("click",w=>{w.stopPropagation(),w.preventDefault(),this._openSessionRowMenu(w.currentTarget,e,t,m,y)}),m.append(S,y),m},_openSessionRowMenu(e,t,i,s,n){if(this._openRowMenuClose)try{this._openRowMenuClose()}catch{}const r=Array.isArray(t.sources)&&t.sources.includes("live")&&this.sessions.has(t.sessionId),l=document.createElement("div");l.className="session-row-menu",l.setAttribute("role","menu");let a=null,h=null,d=null;const u=()=>{document.removeEventListener("mousedown",a,!0),document.removeEventListener("keydown",h,!0),window.removeEventListener("scroll",d,!0),window.removeEventListener("resize",d,!0);try{l.remove()}catch{}this._openRowMenuEl===l&&(this._openRowMenuEl=null,this._openRowMenuClose=null)},c=(o,f,_)=>{const y=document.createElement("button");y.type="button",y.className="session-row-menu-item",y.setAttribute("role","menuitem");const b=document.createElement("span");if(b.className="session-row-menu-label",b.textContent=o,y.appendChild(b),_&&_.sublabel){const g=document.createElement("span");g.className="session-row-menu-sublabel",g.textContent=_.sublabel,y.appendChild(g)}y.addEventListener("click",async g=>{g.stopPropagation(),g.preventDefault(),await f()}),l.appendChild(y)};c(r?"Switch to session":"Resume session",()=>{r?this.selectSession(t.sessionId):this.resumeHistorySession(t.claudeSessionId||t.sessionId,t.workingDir||"",t.name,t.mode,t.resumeId),this.closeSessionManager?.(),u()});const m=t.pinned===!0;c(m?"Unpin session":"Pin to top",async()=>{await this._setSessionPinned(t.sessionId,!m)?(t.pinned=!m,this.showToast(m?"Unpinned":"Pinned to top","success")):this.showToast("Pin failed","error"),u()}),r&&c("Open folder",()=>{this.selectSession(t.sessionId),this.loadFileBrowser?.(t.sessionId),this.closeSessionManager?.(),u()}),t.workingDir&&c("Copy path",async()=>{const o=await this._copyText(t.workingDir);this.showToast(o?"Path copied":"Copy failed",o?"success":"error"),u()}),c("Show details",()=>{const o=s.classList.toggle("expanded");n.hidden=!o,e.setAttribute("aria-expanded",o?"true":"false"),u()}),document.body.appendChild(l);const S=e.getBoundingClientRect(),T=l.getBoundingClientRect(),C=4;let p=S.bottom+C;p+T.height>window.innerHeight&&S.top-C-T.height>=0&&(p=S.top-C-T.height);let I=S.right-T.width;I<C&&(I=C),I+T.width>window.innerWidth-C&&(I=Math.max(C,window.innerWidth-C-T.width)),l.style.top=`${Math.max(C,p)}px`,l.style.left=`${I}px`,a=o=>{l.contains(o.target)||e.contains(o.target)||u()},h=o=>{o.key==="Escape"&&(o.stopPropagation(),u())},d=()=>u(),document.addEventListener("mousedown",a,!0),document.addEventListener("keydown",h,!0),window.addEventListener("scroll",d,!0),window.addEventListener("resize",d,!0),this._openRowMenuEl=l,this._openRowMenuClose=u},async _setSessionPinned(e,t){try{const i=await fetch(`/api/sessions/${encodeURIComponent(e)}/pin`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"same-origin",body:JSON.stringify({pinned:t})});return i.ok?(await i.json())?.success===!0:!1}catch(i){return console.error("[_setSessionPinned]",i),!1}},_HISTORY_INITIAL_COUNT:10,_HISTORY_FETCH_LIMIT:200,_HISTORY_SORT_KEY:"codeman:historySort",async loadHistorySessions(){const e=document.getElementById("historySessions"),t=document.getElementById("historyList");if(!(!e||!t))try{const i=Array.isArray(this.cases)&&this.cases.length>0?Promise.resolve(this.cases):fetch("/api/cases").then(r=>r.ok?r.json():null).then(r=>r?.data||[]).catch(()=>[]),[s,n]=await Promise.all([this._fetchUnifiedSessions(this._HISTORY_FETCH_LIMIT),i]);if(s.length===0){e.style.display="none";return}this._historyAll=s,this._historyCases=n,this._wireHistoryControls(),this._renderHistoryList(),e.style.display=""}catch(i){console.error("[loadHistorySessions]",i),e.style.display="none"}},_wireHistoryControls(){if(this._historyControlsWired)return;const e=document.getElementById("historyFilter"),t=document.getElementById("historySort");if(!(!e&&!t)){if(this._historyControlsWired=!0,t)try{const i=localStorage.getItem(this._HISTORY_SORT_KEY);i&&Array.from(t.options).some(s=>s.value===i)&&(t.value=i)}catch{}e&&(e.addEventListener("input",()=>this._renderHistoryList()),e.addEventListener("keydown",i=>{i.key==="Escape"&&e.value&&(i.stopPropagation(),e.value="",this._renderHistoryList())})),t&&t.addEventListener("change",()=>{try{localStorage.setItem(this._HISTORY_SORT_KEY,t.value)}catch{}this._renderHistoryList()})}},_historyRowMatches(e,t,i){return[e.name,e.workingDir,this._resolveCaseLabel(e.workingDir,i),e.firstPrompt,e.lastPrompt,e.sessionId].some(n=>typeof n=="string"&&n.toLowerCase().includes(t))},_historyRowLabel(e,t){return e.name||e.firstPrompt||t||""},_sortHistoryRows(e,t){const n=t==="name"?a=>this._historyRowLabel(a,this._shortenHomePath(a.workingDir)).toLowerCase():a=>((a.workingDir||"").split("/").pop()||"").toLowerCase(),r=t==="recent"?e.slice():e.slice().sort((a,h)=>n(a).localeCompare(n(h),void 0,{sensitivity:"base",numeric:!0})),l=r.filter(a=>a.pinned);return l.length===0?r:l.concat(r.filter(a=>!a.pinned))},_renderHistoryList(){const e=document.getElementById("historyList");if(!e)return;const t=this._historyAll||[],i=this._historyCases||[],s=document.getElementById("historyCount"),n=(document.getElementById("historyFilter")?.value||"").trim().toLowerCase(),r=document.getElementById("historySort")?.value||"recent",l=n?t.filter(c=>this._historyRowMatches(c,n,i)):t,a=this._sortHistoryRows(l,r),h=!!this._historyExpanded||n.length>0,d=h?a:a.slice(0,this._HISTORY_INITIAL_COUNT);if(e.replaceChildren(),e.classList.toggle("expanded",h),a.length===0){const c=document.createElement("div");c.className="history-empty",c.textContent=`No conversations match "${n}"`,e.appendChild(c)}for(const c of d)e.appendChild(this._buildHistoryItem(c,i));const u=a.length-d.length;if(u>0){const c=document.createElement("button");c.className="history-show-more",c.textContent=`Show ${u} more`,c.addEventListener("click",()=>{this._historyExpanded=!0,this._renderHistoryList()}),e.appendChild(c)}else if(h&&!n&&a.length>this._HISTORY_INITIAL_COUNT){const c=document.createElement("button");c.className="history-show-more",c.textContent="Show less",c.addEventListener("click",()=>{this._historyExpanded=!1,this._renderHistoryList(),e.scrollTop=0}),e.appendChild(c)}s&&(s.textContent=n?`${a.length} of ${t.length}`:a.length>d.length?`${d.length} of ${a.length}`:String(a.length))},_FOLDER_HISTORY_PAGE_SIZE:20,openFolderHistoryModal(e,t,i){this._closeFolderHistoryModal();const s=document.createElement("div");s.className="modal active folder-history-modal",s.id="folderHistoryModal";const n=document.createElement("div");n.className="modal-backdrop",n.addEventListener("click",()=>this._closeFolderHistoryModal());const r=document.createElement("div");r.className="modal-content modal-lg";const l=document.createElement("div");l.className="modal-header";const a=document.createElement("h3");a.textContent="Folder History";const h=document.createElement("div");h.className="folder-history-subtitle",h.textContent=this._shortenHomePath(t);const d=document.createElement("button");d.className="modal-close",d.setAttribute("aria-label","Close"),d.innerHTML="&times;",d.addEventListener("click",()=>this._closeFolderHistoryModal()),l.append(a,d);const u=document.createElement("div");u.className="modal-body";const c=document.createElement("div");c.className="folder-history-list",c.setAttribute("data-loading","true"),c.textContent="Loading...",u.append(h,c),r.append(l,u),s.append(n,r),document.body.appendChild(s),this._folderHistoryState={projectKey:e,workingDir:t,cases:i||[],offset:0,total:null,list:c},this._folderHistoryEscHandler=m=>{m.key==="Escape"&&this._closeFolderHistoryModal()},document.addEventListener("keydown",this._folderHistoryEscHandler),this._loadFolderHistoryPage()},async _loadFolderHistoryPage(){const e=this._folderHistoryState;if(!e)return;const{projectKey:t,cases:i,list:s}=e,n=this._FOLDER_HISTORY_PAGE_SIZE,r=e.offset,l=s.querySelector(".folder-history-more");l&&l.remove(),r===0&&(s.replaceChildren(),s.removeAttribute("data-loading"));try{const a=`/api/history/sessions?projectKey=${encodeURIComponent(t)}&offset=${r}&limit=${n}`,d=await(await fetch(a)).json(),u=d.data?.sessions||[];if(e.total=typeof d.data?.total=="number"?d.data.total:u.length+r,r===0&&u.length===0){const c=document.createElement("div");c.className="folder-history-empty",c.textContent="No conversations found in this folder.",s.appendChild(c);return}for(const c of u)s.appendChild(this._buildHistoryItem(c,i,{showViewAll:!1}));if(e.offset=r+u.length,e.offset<e.total){const c=e.total-e.offset,m=document.createElement("button");m.className="history-show-more folder-history-more",m.textContent=`Show ${Math.min(n,c)} more (${c} remaining)`,m.addEventListener("click",()=>this._loadFolderHistoryPage()),s.appendChild(m)}}catch(a){console.error("[loadFolderHistoryPage]",a);const h=document.createElement("div");h.className="folder-history-empty",h.textContent="Failed to load folder history.",s.appendChild(h)}},_closeFolderHistoryModal(){const e=document.getElementById("folderHistoryModal");e&&e.remove(),this._folderHistoryEscHandler&&(document.removeEventListener("keydown",this._folderHistoryEscHandler),this._folderHistoryEscHandler=null),this._folderHistoryState=null},_resolveResumeName(e,t){if(typeof e=="string"&&e.trim())return e;const i=(t||"").split("/").pop()||"session";let s=1;for(const[,n]of this.sessions){const r=n.name&&n.name.match(/^w(\d+)-/);if(r){const l=parseInt(r[1]);l>=s&&(s=l+1)}}return`w${s}-${i}`},async resumeHistorySession(e,t,i,s,n){document.getElementById("runModeMenu")?.classList.remove("active"),this._closeFolderHistoryModal();try{this.terminal.clear(),this.terminal.writeln(`\x1B[1;32m Resuming conversation ${e.slice(0,8)}...\x1B[0m`);const r=this._resolveResumeName(i,t),a=(this.cases||[]).find(f=>f.path===t)?.name||t.split("/").pop()||"",h=this.loadAppSettingsFromStorage(),d=this.buildEnvOverrides(this.getCaseSettings(a),h),u=this.getEffortSetting(h),c=s||"claude",m={opencode:"openCodeConfig",pi:"piConfig",grok:"grokConfig",omp:"ompConfig"}[c],S=c==="codex"?n:void 0,T=m?{[m]:{continueSession:!0}}:c==="deepseek"?{deepSeekConfig:{resumeSession:!0}}:S?{codexConfig:{resumeSessionId:S}}:{},C=!!m||c==="deepseek"||!!S,I=await(await fetch("/api/sessions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workingDir:t,name:r,mode:c,...c==="claude"?{resumeSessionId:e}:{},...T,...Object.keys(d).length>0?{envOverrides:d}:{},...u?{effort:u}:{}})})).json();if(!I.success)throw new Error(I.error);const o=I.data.session.id;await fetch(`/api/sessions/${o}/interactive`,{method:"POST"}),c!=="claude"&&C&&e!==o&&fetch(`/api/sessions/${e}?killMux=true`,{method:"DELETE"}).catch(()=>{}),this.terminal.writeln(`\x1B[90m Session ${r} ready\x1B[0m`),await this.selectSession(o),this.terminal.focus()}catch(r){this.terminal.writeln(`\x1B[1;31m Error: ${r.message}\x1B[0m`)}},isTerminalAtBottom(){if(!this.terminal)return!0;const e=this.terminal.buffer.active;return e.viewportY>=e.baseY-2},_syncStickyScrollBaseline(){this._wasAtBottomBeforeWrite=this.isTerminalAtBottom()},_noteTerminalUserScroll(e){e<0?this._lastUserScrollUpAt=performance.now():this.isTerminalAtBottom()&&(this._lastUserScrollUpAt=null)},_maybeLoadMoreHistoryOnScroll(e){e>=0||this.terminal?.buffer?.active?.viewportY===0&&this._maybeRefetchFullHistory?.()},_estimateReplayRows(e,t){if(typeof e!="string"||!e)return 0;const i=t>0?t:80,s=e.replace(window.CodemanTerminalInput.REPLAY_ESCAPE_RE,"");let n=0;for(const r of s.split(`
2
+ `)){const l=r.endsWith("\r")?r.length-1:r.length;n+=l>i?Math.ceil(l/i):1}return n},_replayWouldShrinkBuffer(e){const t=this.terminal,i=t?.buffer?.active?.length||0;if(!i)return!1;const s=t?.rows||24;return this._estimateReplayRows(e,t?.cols)+s<i},_smoothScrollBy(e){if(!e||(this._smoothScrollPending=(this._smoothScrollPending||0)+e,this._smoothScrollSession=this.activeSessionId,this._smoothScrollFrame))return;const t=()=>{this._smoothScrollFrame=null;const i=this._smoothScrollPending||0;if(!i)return;if(this.activeSessionId!==this._smoothScrollSession){this._smoothScrollPending=0;return}if(Math.abs(i)<1)return;const s=i*.22,n=i>0?Math.max(1,Math.floor(s)):Math.min(-1,Math.ceil(s));this._smoothScrollPending=i-n,this.terminal.scrollLines(n),this._maybeLoadMoreHistoryOnScroll(n),Math.abs(this._smoothScrollPending)>=1&&(this._smoothScrollFrame=requestAnimationFrame(t))};this._smoothScrollFrame=requestAnimationFrame(t)},_forwardScrollToApp(e,t,i){this._terminalViewportAtBottom()||this.terminal.scrollToBottom(),this._sendSyntheticSgrWheel(e,t,i)},_hasRecentUserScrollUp(){return typeof this._lastUserScrollUpAt!="number"?!1:performance.now()-this._lastUserScrollUpAt<window.CodemanTerminalInput.USER_SCROLL_STICKY_SUPPRESS_MS},batchTerminalWrite(e){if(this._isLoadingBuffer){this._loadBufferQueue&&this._loadBufferQueue.push({at:performance.now(),data:e});return}if(this.writeFrameScheduled||(this._wasAtBottomBeforeWrite=this.isTerminalAtBottom()),(this.activeSessionId?this.sessions.get(this.activeSessionId):null)?.flickerFilterEnabled??!1){if(e.includes("\x1B[2J")||e.includes("\x1B[H\x1B[J")||e.includes("\x1B[H")&&e.includes("\x1B[?25l")){this.flickerFilterActive=!0,this.flickerFilterBuffer+=e,this.flickerFilterTimeout&&clearTimeout(this.flickerFilterTimeout),this.flickerFilterTimeout=setTimeout(()=>{this.flickerFilterTimeout=null,this.flushFlickerBuffer()},SYNC_WAIT_TIMEOUT_MS);return}if(this.flickerFilterActive){this.flickerFilterBuffer+=e;return}}this.pendingWrites.push(e),this._scheduleTerminalWriteFlush()},_scheduleTerminalWriteFlush(){this._terminalWriteInFlight||this.writeFrameScheduled||this.pendingWrites.length===0||(this.writeFrameScheduled=!0,this._safeYield(()=>{this.writeFrameScheduled=!1,this.flushPendingWrites()}))},flushFlickerBuffer(){this.flickerFilterBuffer&&(this.pendingWrites.push(this.flickerFilterBuffer),this.flickerFilterBuffer="",this.flickerFilterActive=!1,this._scheduleTerminalWriteFlush())},_flushLocalEchoPending(){const e=this._localEchoOverlay?.pendingText||"";this._localEchoOverlay?.clear(),this._localEchoOverlay?.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),e&&(this._pendingInput+=e)},_updateLocalEchoState(){const e=this.loadAppSettingsFromStorage(),t=this.activeSessionId?this.sessions.get(this.activeSessionId):null,i=e.localEchoEnabled??MobileDetection.isTouchDevice(),s=!!(i&&t);this._localEchoEnabled&&!s&&this._localEchoOverlay?.clear(),this._localEchoEnabled=s,this._localEchoOverlay&&t&&(t.mode==="opencode"?this._localEchoOverlay.setPrompt({type:"custom",offset:3,find:r=>{try{const l=r.buffer.active,a=l.cursorY,h=l.getLine(l.viewportY+a);if(!h)return null;const u=h.translateToString(!0).indexOf("\u2503");return u>=0?{row:a,col:u}:null}catch{return null}}}):t.mode==="shell"||t.mode==="codex"?(this._localEchoOverlay.clear(),this._localEchoEnabled=!1):this._localEchoOverlay.setPrompt({type:"custom",offset:0,find:r=>{try{const l=r.buffer.active;for(let a=r.rows-1;a>=0;a--){const h=l.getLine(l.viewportY+a);if(!h)continue;const u=h.translateToString(!0).lastIndexOf("\u276F");if(u>=0)return{row:a,col:u+2}}return{row:Math.max(0,Math.min(r.rows-1,l.cursorY)),col:Math.max(0,Math.min(r.cols-1,l.cursorX))}}catch{return null}}}));let n="off";t&&i&&(t.mode==="codex"?n="predict":t.mode!=="shell"&&(n="buffer")),this._localEchoPolicy=n,n!=="predict"&&this._predictiveEcho?.clearPredictions()},_predictHookOnData(e){if(!(this._localEchoPolicy!=="predict"||!this._predictiveEcho))try{const t=window.CodemanTerminalInput.classifyPredictInput(e);t==="char"?this._predictiveEcho.predictChar(e):t==="backspace"?this._predictiveEcho.predictBackspace():this._predictiveEcho.clearPredictions()}catch{}},_handleCjkInput(e){if(!this.activeSessionId){_crashDiag.log(`CJK send DROP no-session len=${e.length}`);return}typeof KeyboardAccessoryBar<"u"&&KeyboardAccessoryBar.isCtrlArmed?.()&&(e=KeyboardAccessoryBar.consumeCtrl(e)),this._localEchoPolicy==="predict"&&this._predictiveEcho?.clearPredictions(),_crashDiag.log(`CJK send\u2192${this.activeSessionId.slice(0,8)} len=${e.length}`),this._sendInputAsync(this.activeSessionId,e)},_restoreTerminalViewport(e,t){e!=null&&(t!==void 0&&t!==this.activeSessionId||this._isLoadingBuffer||typeof this.terminal?.scrollToLine=="function"&&this.terminal.buffer?.active?.viewportY!==e&&this.terminal.scrollToLine(e))},flushPendingWrites(){if(this._terminalWriteInFlight||this.pendingWrites.length===0||!this.terminal)return;const e=performance.now(),t=this.pendingWrites.join("");this.pendingWrites=[];const i=t.length;i>16384&&_crashDiag.log(`FLUSH: ${(i/1024).toFixed(0)}KB`);const n=(this.activeSessionId&&this.sessions?this.sessions.get(this.activeSessionId):null)?.mode==="codex"?32768:65536;let r=!1;const l=this.terminal.buffer?.active&&!this.isTerminalAtBottom()?this.terminal.buffer.active.viewportY:null,a=this.activeSessionId,h=t.slice(0,n);i>n&&(this.pendingWrites.push(t.slice(n)),r=!0),this._terminalWriteInFlight=!0,this._terminalWriteInFlightBytes=h.length;try{this.terminal.write(h,()=>{this._terminalWriteInFlight=!1,this._terminalWriteInFlightBytes=0,this._restoreTerminalViewport(l,a),this._scheduleTerminalWriteFlush()})}catch(c){throw this._terminalWriteInFlight=!1,this._terminalWriteInFlightBytes=0,c}const d=r?n:i,u=performance.now()-e;if((u>100||r)&&console.warn(`[CRASH-DIAG] flushPendingWrites: ${u.toFixed(0)}ms, ${(d/1024).toFixed(0)}KB written${r?", rest deferred":""} (total ${(i/1024).toFixed(0)}KB)`),l===null&&this._wasAtBottomBeforeWrite&&!this._hasRecentUserScrollUp()&&this.terminal.scrollToBottom(),this._localEchoOverlay?.hasPending&&this._localEchoOverlay.rerender(),this._tabCompletionSessionId&&this._tabCompletionSessionId===this.activeSessionId&&this._localEchoOverlay&&!this._localEchoOverlay.pendingText){const c=this._localEchoOverlay,m=this;this.terminal.write("",()=>{if(!m._tabCompletionSessionId)return;c.resetBufferDetection();const S=c.detectBufferText();S?S===m._tabCompletionBaseText?(c.undoDetection(),m._tabCompletionRetries=(m._tabCompletionRetries||0)+1,m._tabCompletionRetries>60&&(m._tabCompletionSessionId=null,m._tabCompletionRetries=0)):(m._tabCompletionSessionId=null,m._tabCompletionRetries=0,m._tabCompletionBaseText=null,m._tabCompletionFallback&&(clearTimeout(m._tabCompletionFallback),m._tabCompletionFallback=null),c.rerender()):(m._tabCompletionRetries=(m._tabCompletionRetries||0)+1,m._tabCompletionRetries>60&&(m._tabCompletionSessionId=null,m._tabCompletionRetries=0))})}},_safeYield(e){let t=!1;const i=()=>{t||(t=!0,e())};requestAnimationFrame(i),setTimeout(i,50),this._workerYield(i)},_workerYield(e){try{if(this._yieldWorker===void 0){const t="onmessage=()=>setTimeout(()=>postMessage(0),0);",i=new Blob([t],{type:"application/javascript"}),s=URL.createObjectURL(i);this._yieldWorker=new Worker(s),URL.revokeObjectURL(s),this._yieldQueue=[],this._yieldWorker.onmessage=()=>{const n=this._yieldQueue.shift();n&&n()}}if(!this._yieldWorker)return;this._yieldQueue.push(e),this._yieldWorker.postMessage(0)}catch{this._yieldWorker=null}},scrollToLastNonEmptyLine(){if(!this.terminal?.buffer?.active){this.terminal?.scrollToBottom?.();return}const e=this.terminal.buffer.active,t=e.length;let i=-1;for(let s=t-1;s>=0;s--)if(e.getLine(s)?.translateToString(!0).trim()){i=s;break}if(i>=0&&typeof this.terminal.scrollToLine=="function"){let s=Math.max(0,i-this.terminal.rows+2);const n=Math.max(0,i);for(;s<n&&!e.getLine(s)?.translateToString(!0).trim();)s++;this.terminal.scrollToLine(s)}else this.terminal.scrollToBottom()},chunkedTerminalWrite(e,t=TERMINAL_CHUNK_SIZE,i,s){const n=++this._chunkedWriteGen,r=this._beginBufferLoad(i);return new Promise(l=>{const a=(S=this._chunkedWriteGen===n)=>({parsedAt:performance.now(),bufferLength:this.terminal?.buffer?.active?.length??0,completed:S});if(!e||e.length===0){this._finishBufferLoad(r,s),l(a());return}const h=e.replace(DEC_SYNC_STRIP_RE,"");if(h.length<=t){this.terminal.write(h,()=>l(a())),this._finishBufferLoad(r,s);return}let d=0;const u=performance.now();let c=0;const m=()=>{if(this._chunkedWriteGen!==n){l(a(!1));return}const S=h.slice(d,d+t);if(d+=S.length,c++,this.terminal.write(S),d>=h.length){this.terminal.write("",()=>{const T=a(),C=T.parsedAt-u;console.log(`[CRASH-DIAG] chunkedTerminalWrite complete: ${h.length} bytes in ${c} chunks, ${C.toFixed(0)}ms parsed`),l(T)}),this._finishBufferLoad(r,s);return}this._safeYield(m)};this._safeYield(m)})},_beginBufferLoad(e){this._bufferLoadSeq===void 0&&(this._bufferLoadSeq=0);const t=e===void 0?`buffer-${++this._bufferLoadSeq}`:e,i=this._bufferLoadOwner===t&&Array.isArray(this._loadBufferQueue);return this._bufferLoadOwner=t,this._isLoadingBuffer=!0,i||(this._loadBufferQueue=[]),t},_finishBufferLoad(e,t){if(e!==void 0&&this._bufferLoadOwner!==e)return!1;const i=this._loadBufferQueue;if(this._isLoadingBuffer=!1,this._loadBufferQueue=null,this._bufferLoadOwner=null,t?.flushQueued&&i&&i.length){const s=typeof t.since=="number"?t.since:0;for(const n of i)n.at<s||this.batchTerminalWrite(n.data)}return!0},clearTerminal(){this.terminal.clear()},insertTerminalText(e){!this.activeSessionId||!e||(this._localEchoPolicy==="predict"&&this._predictiveEcho?.clearPredictions(),this._localEchoEnabled&&this._localEchoOverlay&&!this._echoPassthroughSessions?.has(this.activeSessionId)?this._localEchoOverlay.appendText(e):this.sendInput(e).catch(()=>{}),this.terminal?.focus())},clearTerminalInput(){if(this.activeSessionId){if(typeof CjkInput<"u"&&CjkInput.clear(),this._inputFlushTimeout&&(clearTimeout(this._inputFlushTimeout),this._inputFlushTimeout=null),this._pendingInput="",this._localEchoPolicy==="predict"&&this._predictiveEcho?.clearPredictions(),this._localEchoEnabled&&this._localEchoOverlay){const e=this._localEchoOverlay.getFlushed?.()||{count:0,text:""};this._localEchoOverlay.clear(),this._localEchoOverlay.suppressBufferDetection(),this._flushedOffsets?.delete(this.activeSessionId),this._flushedTexts?.delete(this.activeSessionId),e.count>0&&this.sendInput("\x7F".repeat(e.count)).catch(()=>{})}else this.sendInput("").catch(()=>{});this.showToast?.("Input cleared","success"),this.terminal?.focus()}},async restoreTerminalSize(){if(!this.activeSessionId){this.showToast("No active session","warning");return}if(!this.isSoloWindow&&this.detachedSessions?.has(this.activeSessionId)){this.showToast("This session is sized by its own window","warning");return}const e=this.getTerminalDimensions();if(!e){this.showToast("Could not determine terminal size","error");return}try{await this.sendResize(this.activeSessionId,{force:!0}),this.showToast(`Terminal restored to ${e.cols}x${e.rows}`,"success")}catch(t){console.error("Failed to restore terminal size:",t),this.showToast("Failed to restore terminal size","error")}},sendPendingCtrlL(e){},shouldCopyTerminalSelectionFromShortcut(e){if(!e||e.type!=="keydown"||!e.ctrlKey&&!e.metaKey&&!e.altKey)return!1;const i=typeof this.getShortcutRegistry=="function"&&typeof this.matchesShortcutEvent=="function"?this.getShortcutRegistry().find(s=>s.id==="copy-selection"):null;return i?!i.disabled&&this.matchesShortcutEvent(e,i):!e.altKey&&(e.key||"").toLowerCase()==="c"},cleanedTerminalSelection(e){const t=e??(this.terminal?.hasSelection?.()?this.terminal.getSelection():"");if(!t)return"";if(this.terminal?._core?._selectionService?._activeSelectionMode===3)return t;const i=window.CodemanCopySelection?.clean;return i?i(t):t},async copyTerminalSelection(e){const t=this.cleanedTerminalSelection(e);if(!t.trim())return this.terminal?.clearSelection?.(),this.showToast("Nothing to copy","warning"),!1;const i=await this._copyText(t);return i?(this.terminal.clearSelection?.(),this.showToast("Copied to clipboard","success")):this.showToast("Failed to copy","error"),this.terminal.focus(),i},_autoCopySelectionEnabled(){try{return this.loadAppSettingsFromStorage?.()?.autoCopySelection===!0}catch{return!1}},async _flushAutoCopySelection(){const e=window.CodemanAutoCopy?.decide;if(!e||!this.terminal)return;const t=this._autoCopySelectionEnabled(),i=t?this.cleanedTerminalSelection():"",s=e({enabled:t,text:i,lastCopied:this._autoCopyLastText,pending:!!this._autoCopyPending});if(this._autoCopyPending=!1,s==="skip")return;if(s==="too-large"){this._autoCopyNotify("Selection too large to copy automatically. Press Ctrl+C.","warning");return}this._autoCopyLastText=i;const n=document.activeElement,r=await this._copyText(i);if(n&&n!==document.activeElement&&n.isConnected&&typeof n.focus=="function")try{n.focus()}catch{}if(!r){this._autoCopyLastText="",this._autoCopyNotify("Auto Copy failed: the browser blocked clipboard access","error");return}this._autoCopyHintShown||(this._autoCopyHintShown=!0,this.showToast("Auto Copy: selection copied","success"))},_autoCopyNotify(e,t){const i=Date.now(),s=this._autoCopyNotifiedAt;s!==void 0&&i-s<1e4||(this._autoCopyNotifiedAt=i,this.showToast(e,t))},_syncMobileHelperTextareaToCursor(){if(!(!MobileDetection.isTouchDevice()||!this.terminal?.element))try{const e=this.terminal.element,t=this.terminal.element.querySelector(".xterm-cursor"),i=this.terminal.element.querySelector(".xterm-screen");if(!(e instanceof HTMLElement)||!(t instanceof HTMLElement)||!(i instanceof HTMLElement))return;const s=t.getBoundingClientRect(),n=i.getBoundingClientRect();if(!s.width&&!s.height)return;const r=Math.max(0,Math.round(s.left-n.left)),l=Math.max(0,Math.round(s.top-n.top));e.style.setProperty("--xterm-helper-left",`${r}px`),e.style.setProperty("--xterm-helper-top",`${l}px`)}catch{}},_isMobileTerminalInputFocused(){const e=document.activeElement;return e===this.terminal?.textarea||e?.classList?.contains("xterm-helper-textarea")||e?.id==="cjkInput"},_classifyMobileTerminalTap(e,t){if(!this._terminalViewportAtBottom())return"history";const i=this._clientPointToCell(e,t);if(!i||!this.terminal)return"input";const s=this.terminal.modes?.mouseTrackingMode;if(!(!!s&&s!=="none")&&!this._shouldReportMouseToCli())return"input";const r=this.terminal.buffer?.active;if(!r?.getLine)return"input";const l=Math.max(1,this.terminal.rows||1),a=[],h=[];let d=!1;for(let o=0;o<l;o++){const f=r.getLine(r.viewportY+o),_=f?.translateToString?.(!0)||"";a.push(_),h.push(!!f?.isWrapped),_.trim()&&(d=!0)}if(!d)return"input";const u=Math.max(0,Math.min(l-1,r.cursorY||0)),c=this.sessions?.get(this.activeSessionId)?.mode||"claude";let m=-1,S=!1;if(c==="opencode")a[u]?.includes("\u2503")&&(m=u);else for(let o=l-1;o>=0;o--){const f=a[o].match(/^\s*[❯›]/);if(!f)continue;const _=a[o].slice(f[0].length).trim(),y=a.some((b,g)=>g!==o&&/^\s+\d+[.)]\s/.test(b));if(/^\d+[.)]\s/.test(_)&&y){S=!0;break}m=o;break}const T=i.row-1;let C=T;for(;C>0&&h[C];)C--;let p=T;for(;p+1<l&&h[p+1];)p++;const I=a.slice(C,p+1).join("");if(c==="claude"&&/\b(?:esc to interrupt|background)\b/i.test(I)||S)return"content";if(m>=0){const o=u>=m?u:m;if(T>=m&&T<=o)return"input"}else if(T===u||T>=Math.max(0,l-window.CodemanTerminalInput.TUI_PROMPT_DEFAULT_ROWS_FROM_BOTTOM))return"input";return"content"},_blurMobileTerminalInput(){const e=document.activeElement;(e===this.terminal?.textarea||e?.classList?.contains("xterm-helper-textarea")||e?.id==="cjkInput")&&e.blur?.()},_installMobileKeyboardDismiss(){if(this._mobileKeyboardDismissHandler)return;let e=0,t=0,i=!1;this._mobileKeyboardDismissStart=s=>{if(s.touches.length!==1){i=!0;return}e=s.touches[0].clientX,t=s.touches[0].clientY,i=!1},this._mobileKeyboardDismissMove=s=>{if(i||!s.touches.length)return;const n=s.touches[0].clientX-e,r=s.touches[0].clientY-t,l=window.CodemanTerminalInput.MOBILE_KEYBOARD_DISMISS_TAP_SLOP;(Math.abs(n)>l||Math.abs(r)>l)&&(i=!0)},this._mobileKeyboardDismissHandler=s=>{if(i||!this._isMobileTerminalInputFocused())return;const n=s.target;!n||typeof n.closest!="function"||n.closest("#terminalContainer")||n.closest(window.CodemanTerminalInput.MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR)||this._blurMobileTerminalInput()},document.addEventListener("touchstart",this._mobileKeyboardDismissStart,{passive:!0}),document.addEventListener("touchmove",this._mobileKeyboardDismissMove,{passive:!0}),document.addEventListener("touchend",this._mobileKeyboardDismissHandler,{passive:!0})},_isActionableMobileTerminalTap(e,t){const i=this._clientPointToCell(e,t),s=this.terminal?.buffer?.active;if(!i||!s?.getLine)return!1;const n=Math.max(1,this.terminal.rows||1),r=[],l=[];for(let p=0;p<n;p++){const I=s.getLine(s.viewportY+p);r.push(I?.translateToString?.(!0)||""),l.push(!!I?.isWrapped)}const a=i.row-1;let h=a;for(;h>0&&l[h];)h--;let d=a;for(;d+1<n&&l[d+1];)d++;const u=r.slice(h,d+1).join(""),c=/\b(?:ctrl\+\w+|shift\+\w+|esc|enter|tab|tap)\s+to\s+(?:expand|collapse|view|open|interrupt|see)\b/i,m=Math.max(0,h-1),S=Math.min(n-1,d+1);for(let p=m;p<=S;p++)if(c.test(r[p]))return!0;const T=r.some(p=>/^\s*[❯›]\s+\d+[.)]\s/.test(p)),C=r.some(p=>/^\s+\d+[.)]\s/.test(p));return T&&C&&/^\s*(?:[❯›]\s*)?\d+[.)]\s/.test(u)},_focusMobileTerminalInput(){this._syncMobileHelperTextareaToCursor();const e=document.getElementById("cjkInput");e?.classList.contains("cjk-input-visible")?e.focus():this.terminal?.focus()},_handleMobileTerminalTap(e,t,i=null){if(!e||!this.terminal)return null;if(this._touchSelectionActive)return this._extendTouchSelection(e.clientX,e.clientY),"select";const s=i??this._classifyMobileTerminalTap(e.clientX,e.clientY),n=this._isActionableMobileTerminalTap(e.clientX,e.clientY);if(!n&&!this._tapIsOnCaretLine(e.clientX,e.clientY)&&this._activateTerminalLinkAtPoint(e.clientX,e.clientY))return"link";if(s==="history")return this._focusMobileTerminalInput(),s;const r=this.terminal.modes?.mouseTrackingMode,l=!!r&&r!=="none",a=s==="content"||t;return a&&l?this._dispatchSyntheticTerminalClick(e.clientX,e.clientY):a&&this._shouldReportMouseToCli()&&this._sendSyntheticSgrTap(e.clientX,e.clientY),s==="content"&&n?this._blurMobileTerminalInput():s==="content"&&t?this._blurMobileTerminalInput():this._focusMobileTerminalInput(),s},_dispatchSyntheticTerminalClick(e,t){const i=this.terminal?.element;if(!i||!Number.isFinite(e)||!Number.isFinite(t))return;const s={bubbles:!0,cancelable:!0,view:window,clientX:e,clientY:t,screenX:e,screenY:t,button:0,detail:1};try{i.dispatchEvent(new MouseEvent("mousedown",{...s,buttons:1})),i.dispatchEvent(new MouseEvent("mouseup",{...s,buttons:0}))}catch{}},_shouldReportMouseToCli(){const e=this.sessions?.get(this.activeSessionId),t=e?.mode||"claude";return t!=="claude"&&t!=="codex"&&t!=="gemini"?!1:e?.cliMouseTracking===!0},_terminalViewportAtBottom(){const e=this.terminal?.buffer?.active;return!e||e.viewportY>=e.baseY},_clientPointToCell(e,t){if(!this.terminal||!Number.isFinite(e)||!Number.isFinite(t))return null;const i=this.terminal.element?.querySelector(".xterm-screen"),s=this.terminal._core?._renderService?.dimensions?.css?.cell;if(!i||!s?.width||!s?.height)return null;const n=i.getBoundingClientRect(),r=Math.max(1,Math.min(this.terminal.cols,Math.floor((e-n.left)/s.width)+1)),l=Math.max(1,Math.min(this.terminal.rows,Math.floor((t-n.top)/s.height)+1));return{col:r,row:l}},_sendSyntheticSgrTap(e,t){if(!this.activeSessionId||!this._terminalViewportAtBottom())return;const i=this._clientPointToCell(e,t);i&&this._sendInputAsync(this.activeSessionId,`\x1B[<0;${i.col};${i.row}M\x1B[<0;${i.col};${i.row}m`)},_cliVersionAtLeast(e,t){if(typeof e!="string")return!1;const i=e.trim().replace(/^v/,"").split(".").map(Number);if(i.length!==3||i.some(n=>!Number.isFinite(n)))return!1;const s=t.split(".").map(Number);for(let n=0;n<3;n++)if(i[n]!==s[n])return i[n]>s[n];return!0},_wheelScrollLines(e){const t=this._wheelScrollLinesFloat(e);return t?Math.round(t)||(t>0?1:-1):0},_wheelScrollLinesFloat(e){const t=e.shiftKey&&Math.abs(e.deltaX)>Math.abs(e.deltaY)?e.deltaX:e.deltaY;return t?e.deltaMode===1?t:e.deltaMode===2?t*(this.terminal?.rows||24):t/25:0},_shouldForwardWheelToApp(e){if(e.shiftKey||this.loadAppSettingsFromStorage?.()?.terminalWheelLocalScrollback)return!1;const t=this.terminal?.modes?.mouseTrackingMode;if(t&&t!=="none")return!1;const i=this.sessions?.get(this.activeSessionId);return!((i?.mode||"claude")!=="claude"||!this._cliVersionAtLeast(i?.cliVersion,"2.1.187"))},_sendSyntheticSgrWheel(e,t,i){if(!this.activeSessionId||!i)return;const s=this._clientPointToCell(e,t);if(!s)return;const n=i<0?64:65,r=Math.min(Math.abs(i),5);this._queueScrollBytes(`\x1B[<${n};${s.col};${s.row}M`.repeat(r))},_queueScrollBytes(e){if(!e||!this.activeSessionId)return;const t=this._wheelSgrQueue||"";t.length>512||(this._wheelSgrQueue=t+e,!this._wheelSgrFlushTimer&&(this._wheelSgrFlushTimer=setTimeout(()=>this._flushWheelSgrQueue(),40)))},_localScrollbackIsHollow(){if((this.sessions?.get(this.activeSessionId)?.mode||"claude")!=="claude")return!1;const t=this.terminal?.buffer?.active;return!t||t.type==="alternate"?!1:(t.baseY||0)===0},_maybePageCliTranscript(e,t){if(!t||e?.shiftKey||!this.activeSessionId||!this._localScrollbackIsHollow())return!1;this._pageKeySession!==this.activeSessionId&&(this._pageKeySession=this.activeSessionId,this._pageKeyPending=0);const i=window.CodemanTerminalInput,s=Math.max(2,Math.round((this.terminal?.rows||24)*i.PAGE_KEY_SCREEN_FRACTION)),n=(this._pageKeyPending||0)+t,r=Math.trunc(n/s);if(this._pageKeyPending=n-r*s,r){const l=r<0?i.KEY_PAGE_UP:i.KEY_PAGE_DOWN;this._queueScrollBytes(l.repeat(Math.min(Math.abs(r),i.PAGE_KEY_MAX_PER_BATCH)))}return this._logScrollRouting("page-keys"),!0},_logScrollRouting(e){const t=this.activeSessionId||"(none)",i=this.sessions?.get(t),s=!!this.loadAppSettingsFromStorage?.()?.terminalWheelLocalScrollback,n=this.terminal?.modes?.mouseTrackingMode||"none",r=this.terminal?.buffer?.active?.baseY??-1,l=`${e}|${i?.mode}|${i?.cliVersion}|${s}|${n}|${r>0}`;this._scrollRoutingLogged||(this._scrollRoutingLogged=new Map),this._scrollRoutingLogged.get(t)!==l&&(this._scrollRoutingLogged.set(t,l),console.log(`[scroll] ${t} \u2192 ${e} (mode=${i?.mode||"?"}, cliVersion=${i?.cliVersion||"unknown"}, localScrollbackOptOut=${s}, mouseTracking=${n}, localScrollbackRows=${r})`))},_flushWheelSgrQueue(){this._wheelSgrFlushTimer=null;const e=this._wheelSgrQueue;this._wheelSgrQueue="",e&&this.activeSessionId&&this._sendInputEphemeral(this.activeSessionId,e)},_handleDesktopTerminalClick(e){if(!this.terminal||!e?.isTrusted||e.button!==0||e.detail!==1||e.shiftKey||e.altKey||e.ctrlKey||e.metaKey)return;const t=this.terminal.modes?.mouseTrackingMode;t&&t!=="none"||this._shouldReportMouseToCli()&&(this.terminal.hasSelection?.()||this._linkHovered||performance.now()<=(this._trustedTapMouseSuppressUntil||0)||e.target?.closest?.(".xterm-screen")&&this._sendSyntheticSgrTap(e.clientX,e.clientY))},_installShiftDragSelection(){const e=this.terminal?.element;!e||e._codemanShiftDragInstalled||(e._codemanShiftDragInstalled=!0,e.addEventListener("mousedown",t=>{if(!t.isTrusted||t.button!==0||!t.shiftKey||t.altKey||t.ctrlKey||t.metaKey||this.terminal?.hasSelection?.())return;const i=this._clientPointToCell(t.clientX,t.clientY);if(!i)return;const s=this.terminal.buffer?.active?.viewportY??0;this.terminal.select(i.col-1,i.row-1+s,0)},!0))},_installMobileTapMouseGuard(){const e=this.terminal?.element;if(!e||e._codemanTapMouseGuardInstalled||typeof MobileDetection<"u"&&MobileDetection.isTouchDevice&&!MobileDetection.isTouchDevice())return;e._codemanTapMouseGuardInstalled=!0;const t=i=>{const s=this._trustedTapMouseSuppressUntil||0;!i.isTrusted||performance.now()>s||(i.preventDefault(),i.stopImmediatePropagation())};e.addEventListener("mousedown",t,!0),e.addEventListener("mouseup",t,!0)},_suppressTrustedTapMouseEvents(){const e=window.CodemanTerminalInput?.TOUCH_COMPAT_MOUSE_SUPPRESS_MS||450;this._trustedTapMouseSuppressUntil=performance.now()+e},increaseFontSize(){const e=this.terminal.options.fontSize||14;this.setFontSize(Math.min(e+2,24))},decreaseFontSize(){const e=this.terminal.options.fontSize||14;this.setFontSize(Math.max(e-2,10))},setFontSize(e){this.terminal.options.fontSize=e,document.getElementById("fontSizeDisplay").textContent=e,this.fitAddon.fit(),localStorage.setItem("codeman-font-size",e),this._localEchoOverlay?.refreshFont(),this._predictiveEcho?.refreshFont()},applyTerminalFontFamily(e){const t=window.CodemanTerminalFont.resolve(e);!this.terminal||this.terminal.options.fontFamily===t||(this.terminal.options.fontFamily=t,this._terminalFontReady=this._awaitTerminalFont().then(()=>{this.terminal?.options?.fontFamily===t&&this.fitAddon?.fit()}),this.fitAddon?.fit(),this._localEchoOverlay?.refreshFont(),this._predictiveEcho?.refreshFont())},applyTerminalFontWeights(e){const{fontWeight:t,fontWeightBold:i}=window.CodemanTerminalFont.resolveWeights(e);if(this.terminal&&!(this.terminal.options.fontWeight===t&&this.terminal.options.fontWeightBold===i)){this.terminal.options.fontWeight=t,this.terminal.options.fontWeightBold=i,this._terminalFontReady=this._awaitTerminalFont().then(()=>{this.terminal?.options?.fontWeight===t&&this.fitAddon?.fit()}),this.fitAddon?.fit(),this._localEchoOverlay?.refreshFont(),this._predictiveEcho?.refreshFont();for(const[,s]of this.teammateTerminals||[])if(s?.terminal){s.terminal.options.fontWeight=t,s.terminal.options.fontWeightBold=i;try{s.fitAddon?.fit()}catch{}}}},loadFontSize(){const e=localStorage.getItem("codeman-font-size");if(e){const t=parseInt(e,10);t>=10&&t<=24&&(this.terminal.options.fontSize=t,document.getElementById("fontSizeDisplay").textContent=t)}},async _awaitTerminalFont(){try{if(typeof document>"u"||!document.fonts?.load)return;const e=this.terminal?.options?.fontSize||14,t=String(this.terminal?.options?.fontFamily||"").split(",").map(s=>s.trim().replace(/^["']|["']$/g,"")).filter(Boolean).filter(s=>!TERMINAL_FONT_UNMEASURED.has(s.toLowerCase())),i=Promise.all(t.map(s=>document.fonts.load(`${e}px "${s}"`).catch(()=>{}))).then(()=>document.fonts.ready);await Promise.race([i,new Promise(s=>setTimeout(s,TERMINAL_FONT_WAIT_MS))])}catch{}try{this.terminal?._core?._charSizeService?.measure()}catch{}},getTerminalDimensions(){const i=this.fitAddon?.proposeDimensions();return i?{cols:Math.max(i.cols,40),rows:Math.max(i.rows,10)}:null},async sendResize(e,t={}){if(this.fitAddon&&this.fitAddon.fit(),!this.isSoloWindow&&this.detachedSessions?.has(e))return!1;const i=this.getTerminalDimensions();if(!i)return!1;const s=this._lastResizeDims,n=!s||s.cols!==i.cols||s.rows!==i.rows;this._lastResizeDims={cols:i.cols,rows:i.rows};const r=typeof MobileDetection<"u"&&MobileDetection.getDeviceType?MobileDetection.getDeviceType():window.innerWidth<600?"mobile":window.innerWidth<768?"tablet":"desktop";if(!t.forceHttp&&this._wsReady&&this._wsSessionId===e)try{const a={t:"z",c:i.cols,r:i.rows,v:r};return t.force&&(a.f=!0),this._ws.send(JSON.stringify(a)),n}catch{}const l={...i,viewportType:r};return t.force&&(l.force=!0),await fetch(`/api/sessions/${e}/resize`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)}),n},async sendInput(e){!this.activeSessionId||!e||this._sendInputAsync(this.activeSessionId,e,{useMux:!0})},toggleDirInput(){const e=document.querySelector("#dirDisplay").parentElement,t=document.getElementById("dirInput");t.classList.contains("hidden")&&(t.classList.remove("hidden"),e.style.display="none",t.focus())},hideDirInput(){const e=document.querySelector("#dirDisplay").parentElement,t=document.getElementById("dirInput");setTimeout(()=>{t.classList.add("hidden"),e.style.display="";const i=t.value.trim();document.getElementById("dirDisplay").textContent=i||"No directory"},100)},applyTerminalSkin(e){const t={...window.CODEMAN_XTERM_THEMES[e]||window.CODEMAN_XTERM_THEMES["daylight-blue"]},i=window.codemanCurrentSkinIsLight(e)?4.5:1;if(this.terminal){this.terminal.options.minimumContrastRatio=i,this.terminal.options.theme=t,this._localEchoOverlay?.refreshFont(),this._predictiveEcho?.refreshFont();try{this.terminal.refresh(0,this.terminal.rows-1)}catch{}}if(this.teammateTerminals){for(const[,s]of this.teammateTerminals)if(s&&s.terminal){s.terminal.options.minimumContrastRatio=i,s.terminal.options.theme={...t};try{s.terminal.refresh(0,s.terminal.rows-1)}catch{}}}}}),(function(e){const s={session:"Sessions",event:"Events",file:"Files"};function n(r){if(!Number.isFinite(r))return"";const l=new Date(r);return l.toLocaleDateString("en",{month:"short",day:"numeric"})+" "+l.toLocaleTimeString("en",{hour:"2-digit",minute:"2-digit",hour12:!1})}e.CodemanSearch={SEARCH_DEBOUNCE_MS:250,SEARCH_LIMIT:60,SOURCE_LABELS:s,formatSearchTime:n}})(window),Object.assign(CodemanApp.prototype,{initSearchPanel(){const e=document.getElementById("searchInput");if(!e||this._searchPanelWired){this._searchPanelWired&&this._populateSearchCaseFilter();return}this._searchPanelWired=!0,this._searchTypes=new Set(["session","event","file"]),this._searchSecondary={caseLabel:"",status:"",days:""},this._searchDebounceTimer=null,this._searchSeq=0,this._searchLastData=null;const t=document.getElementById("searchClearBtn"),i=document.getElementById("searchResults");e.addEventListener("input",()=>{t&&(t.hidden=e.value.length===0),this._scheduleSearch()}),e.addEventListener("keydown",l=>{l.key==="Escape"&&e.value&&(l.stopPropagation(),this._clearSearch())}),t&&t.addEventListener("click",()=>this._clearSearch()),document.querySelectorAll("#searchFilters .search-filter-chip").forEach(l=>{l.addEventListener("click",()=>{const a=l.dataset.typeFilter;this._searchTypes.has(a)&&this._searchTypes.size===1||(this._searchTypes.has(a)?(this._searchTypes.delete(a),l.classList.remove("active")):(this._searchTypes.add(a),l.classList.add("active")),this._runSearch())})});const s=document.getElementById("searchCaseFilter"),n=document.getElementById("searchStatusFilter"),r=document.getElementById("searchDateFilter");s&&s.addEventListener("change",()=>{this._searchSecondary.caseLabel=s.value,this._renderSearch(this._searchLastData)}),n&&n.addEventListener("change",()=>{this._searchSecondary.status=n.value,this._renderSearch(this._searchLastData)}),r&&r.addEventListener("change",()=>{this._searchSecondary.days=r.value,this._renderSearch(this._searchLastData)}),this._populateSearchCaseFilter(),i&&(i.hidden=!0)},_populateSearchCaseFilter(){const e=document.getElementById("searchCaseFilter");if(!e)return;const t=Array.isArray(this.cases)?this.cases:[],i=Array.from(new Set(t.map(r=>r&&r.name).filter(Boolean))).sort(),s=e.value;e.innerHTML="";const n=document.createElement("option");n.value="",n.textContent="All cases",e.appendChild(n);for(const r of i){const l=document.createElement("option");l.value=r,l.textContent="#"+r,e.appendChild(l)}s&&i.includes(s)&&(e.value=s)},_scheduleSearch(){clearTimeout(this._searchDebounceTimer),this._searchDebounceTimer=setTimeout(()=>this._runSearch(),window.CodemanSearch.SEARCH_DEBOUNCE_MS)},_clearSearch(){const e=document.getElementById("searchInput"),t=document.getElementById("searchClearBtn");e&&(e.value=""),t&&(t.hidden=!0),this._searchLastData=null,this._renderSearch(null)},async _runSearch(){const e=document.getElementById("searchInput");if(!e)return;const t=e.value.trim();if(t.length===0){this._searchLastData=null,this._renderSearch(null);return}const i=Array.from(this._searchTypes),s=new URLSearchParams;s.set("q",t.slice(0,200)),i.length>0&&i.length<3&&s.set("types",i.join(",")),s.set("limit",String(window.CodemanSearch.SEARCH_LIMIT));const n=++this._searchSeq,r=await this._apiJson("/api/search?"+s.toString());n===this._searchSeq&&(r?this._searchLastData=r:this._searchLastData={query:t,groups:[],totalResults:0,truncated:!1,_error:!0},this._renderSearch(this._searchLastData))},_applySecondaryFilters(e){const{caseLabel:t,status:i,days:s}=this._searchSecondary;let n=e;if(t){const r="#"+t;n=n.filter(l=>(l.sessionName||"").includes(r)||l.sessionName===t)}if(i){const r=new Set((this.sessionOrder||[]).concat(Object.keys(this.sessions||{})));n=n.filter(l=>{const a=r.has(l.sessionId);return i==="active"?a:!a})}if(s){const r=Date.now()-Number(s)*24*60*60*1e3;n=n.filter(l=>Number.isFinite(l.timestamp)&&l.timestamp>=r)}return n},_renderSearch(e){const t=document.getElementById("searchResults"),i=document.getElementById("historyHeader")||document.getElementById("historyTitle"),s=document.getElementById("historyList");if(!t)return;const n=!!e;if(i&&(i.style.display=n?"none":""),s&&(s.style.display=n?"none":""),t.innerHTML="",!e){t.hidden=!0;return}if(t.hidden=!1,e._error){const a=document.createElement("div");a.className="search-empty",a.textContent="Search unavailable \u2014 check the query and try again.",t.appendChild(a);return}const r=(e.groups||[]).map(a=>({type:a.type,results:this._applySecondaryFilters(a.results||[])})).filter(a=>a.results.length>0);if(r.reduce((a,h)=>a+h.results.length,0)===0){const a=document.createElement("div");a.className="search-empty",a.textContent='No results for "'+(e.query||"")+'"',t.appendChild(a);return}for(const a of r){const h=document.createElement("div");h.className="search-group-header";const d=document.createElement("span");d.className="search-group-label",d.textContent=window.CodemanSearch.SOURCE_LABELS[a.type]||a.type;const u=document.createElement("span");u.className="search-group-count",u.textContent=String(a.results.length),h.append(d,u),t.appendChild(h);for(const c of a.results)t.appendChild(this._buildSearchResultCard(c))}if(e.truncated){const a=document.createElement("div");a.className="search-truncated",a.textContent="Showing the top matches \u2014 refine your search to narrow results.",t.appendChild(a)}},_buildSearchResultCard(e){const t=document.createElement("div");t.className="search-result-card",t.dataset.type=e.type,t.tabIndex=0,t.setAttribute("role","button");const i=document.createElement("div");i.className="search-result-top";const s=e.jumpTo&&e.jumpTo.kind==="resume-session",n=document.createElement("span");n.className="search-result-badge search-badge-"+e.type+(s?" search-badge-past":""),n.textContent=s?"Resume":(window.CodemanSearch.SOURCE_LABELS[e.type]||e.type).replace(/s$/,"");const r=document.createElement("span");r.className="search-result-name",r.textContent=e.sessionName||e.sessionId||"(session)";const l=document.createElement("span");l.className="search-result-time",l.textContent=window.CodemanSearch.formatSearchTime(e.timestamp),i.append(n,r,l);const a=document.createElement("div");a.className="search-result-snippet",a.textContent=e.snippet||"",t.append(i,a);const h=()=>this._jumpToSearchResult(e);return t.addEventListener("click",h),t.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),h())}),t},_jumpToSearchResult(e){const t=e&&e.jumpTo;if(t){if(t.kind==="resume-session"){this.resumeHistorySession(t.claudeSessionId||t.sessionId,t.workingDir||"",e.sessionName);return}typeof this.hideWelcome=="function"&&this.hideWelcome();try{t.kind==="run-summary"?this.openRunSummary(t.sessionId):t.kind==="file-preview"?this.openFilePreview(t.relativePath||"",t.sessionId,t.targetId||null):this.selectSession(t.sessionId)}catch(i){console.error("[search] jump failed",i)}}}});
Binary file
Binary file
Binary file
@@ -14,5 +14,178 @@
14
14
  * admin-configured, so this is defence in depth rather than the only gate.
15
15
  */
16
16
  import type { FastifyInstance } from 'fastify';
17
+ import { type CustomModelHost } from '../../custom-model-hosts.js';
18
+ import type { CliEntry } from '../../config/cli-registry/types.js';
19
+ /**
20
+ * Claude Code's own system prompt + tool schemas cost roughly this many tokens on EVERY
21
+ * request, before a single character of conversation history — confirmed live, twice, on
22
+ * requests reporting `in:0 out:0` (the very first exchange) failing at ~36.4K tokens. No
23
+ * `CLAUDE_CODE_MAX_CONTEXT_TOKENS` value fixes this: that setting only changes when Claude
24
+ * Code decides to COMPACT conversation history, and there is no history yet on the first
25
+ * message for it to trim. A model whose real context is below this floor will refuse
26
+ * Claude Code's very first message outright, unconditionally.
27
+ *
28
+ * Set well above the ~36.4K actually measured — CLAUDE.md size, active MCP servers, and
29
+ * enabled skills all add to a project's real baseline, so the observed figure is a floor
30
+ * for THAT one workspace, not a ceiling for every one. Erring conservative here means a
31
+ * borderline-safe model still gets warned about (the user can launch anyway), rather than
32
+ * this floor missing a genuinely-too-small one because a smaller test project happened to
33
+ * fit.
34
+ */
35
+ export declare const CLAUDE_MIN_SAFE_CONTEXT_TOKENS = 40000;
36
+ /**
37
+ * True when applying this model to this CLI is heading for a guaranteed first-message
38
+ * failure per `CLAUDE_MIN_SAFE_CONTEXT_TOKENS` above. Gated on `contextLengthVar` (today,
39
+ * only claude's registry entry declares one) rather than a hardcoded mode check: a CLI
40
+ * with a small enough baseline of its own to never trip this would have no reason to
41
+ * declare the field in the first place, so the check simply never applies to it.
42
+ */
43
+ export declare function exceedsSafeContextFloor(entry: Pick<CliEntry, 'capabilities'>, contextLength: number | undefined): boolean;
44
+ export interface DiscoveryResult {
45
+ models: string[];
46
+ /** See `CustomModelHost.modelContextLengths` — only ever populated for models already loaded. */
47
+ contextLengths: Record<string, number>;
48
+ /** See `CustomModelHost.modelSizesGB` — populated for every model whose own listing states one. */
49
+ sizesGB: Record<string, number>;
50
+ }
51
+ export interface LlamaSwapRunningModel {
52
+ model: string;
53
+ state: string;
54
+ /** The actual launch command llama-swap started this backend with, when it says one —
55
+ * see `parseCtxFromCmd`, which reads the real configured context size out of this. */
56
+ cmd?: string;
57
+ }
58
+ export interface LlamaSwapStatus {
59
+ /**
60
+ * Feature-detected via `GET /running`: true only when the server answered with
61
+ * llama-swap's own shape (`{ running: [...] }`). Plain llama.cpp (and any other
62
+ * OpenAI-compatible server) has no such endpoint and always runs the single model
63
+ * it was started with, so there is no "current model" to conflict with — every
64
+ * caller must treat `isLlamaSwap: false` as "nothing to check", never as an error.
65
+ */
66
+ isLlamaSwap: boolean;
67
+ running: LlamaSwapRunningModel[];
68
+ }
69
+ /**
70
+ * Distinguishes llama-swap from a plain llama.cpp/OpenAI-compatible server, and reports
71
+ * what llama-swap currently has loaded — llama.cpp only ever runs one GGUF at a time, and
72
+ * llama-swap unloads/reloads it on demand when a request asks for a different one, which
73
+ * can take anywhere from a few seconds to over a minute. Read-only: this never triggers a
74
+ * swap itself (unlike `/props?model=`, `/running` takes no `model` parameter to route by).
75
+ * Best-effort like `discoverModels()`'s siblings: any failure (unreachable, non-2xx,
76
+ * unexpected shape) reads as "not llama-swap", never thrown.
77
+ */
78
+ export declare function getLlamaSwapStatus(host: Pick<CustomModelHost, 'baseUrl' | 'apiKey' | 'authStyle'>): Promise<LlamaSwapStatus>;
79
+ /**
80
+ * Real-time "what is llama.cpp actually doing right now" for the loading banner
81
+ * (docs/custom-model-endpoints-plan.md): llama-swap's `GET /api/events` SSE stream
82
+ * carries the backend llama-server process's own stdout — `load_model: loading model
83
+ * '<path>'`, `load_model: initializing, n_slots = N, n_ctx_slot = N`, `llama_server:
84
+ * model loaded`, etc — tagged `source: "upstream"`, distinct from llama-swap's own
85
+ * `source: "proxy"` request-access lines (see `parseBackendLogDataEvent`). Confirmed
86
+ * live against a real llama-swap deployment, including through an actual forced model
87
+ * swap end-to-end.
88
+ *
89
+ * Held OPEN per endpoint rather than re-opened on every 1s poll — confirmed live to stay
90
+ * open indefinitely (read past 220KB over 8 seconds with no `done`), unlike `/logs`
91
+ * (see `parseBackendLogDataEvent`'s doc comment), so reconnecting each poll would be
92
+ * pure waste. One connection is reused across every session currently watching a load on
93
+ * that endpoint; since llama.cpp/llama-swap only ever runs one model at a time, a line
94
+ * seen while a load is in flight is safe to attribute to that load (a deployment that
95
+ * could load several models concurrently would need a per-model tag this format doesn't
96
+ * provide).
97
+ *
98
+ * Lazily started on first access and idle-closed rather than left open forever — see
99
+ * `pruneIdleLlamaSwapLogTails`.
100
+ */
101
+ export declare function getLatestLlamaSwapLogLine(host: Pick<CustomModelHost, 'id' | 'baseUrl' | 'apiKey' | 'authStyle'>): string | undefined;
102
+ /**
103
+ * Closes EVERY open log tail. The idle sweep above only runs on server.ts's periodic
104
+ * interval, and that interval is disposed on shutdown, so without this an outbound
105
+ * stream outlives `WebServer.stop()` against CLAUDE.md's "clear Maps in stop()" rule.
106
+ * Harmless today only because `cli.ts`'s shutdown handler reaches `process.exit(0)`,
107
+ * which is not a property to rely on: tests and any in-process restart do not.
108
+ */
109
+ export declare function closeAllLlamaSwapLogTails(): void;
110
+ /**
111
+ * Closes any log tail nothing has called `getLatestLlamaSwapLogLine` about in
112
+ * `LOG_TAIL_IDLE_MS` — a stream nobody is polling is an open connection with nothing to
113
+ * show for it. Called from the same periodic sweep as `detectCustomModelSwapDisplacements`
114
+ * in server.ts, not its own timer.
115
+ */
116
+ export declare function pruneIdleLlamaSwapLogTails(now?: number): void;
117
+ /**
118
+ * Actually kicks off llama-swap's lazy model load, rather than waiting for the launched
119
+ * CLI's own first prompt to do it. llama-swap has no separate "switch model" admin
120
+ * endpoint — the ONLY thing that starts a swap is a real inference request naming the
121
+ * model (confirmed live: applying a selection alone never appeared in the llama-swap
122
+ * server's own logs; nothing had actually asked it to load anything). This sends the
123
+ * smallest real request that will — `max_tokens: 1`, one throwaway user message — to
124
+ * `${baseUrl}/v1/chat/completions`, the OpenAI-compatible endpoint every supported
125
+ * harness already points at.
126
+ *
127
+ * Deliberately fire-and-forget: the caller (the apply/create routes) returns to the
128
+ * client immediately, and the frontend's own polling (`GET .../running-status`) is what
129
+ * actually confirms readiness — this call's response is never read, just its side
130
+ * effect. No abort/timeout of its own either: a real load can take well over a minute for
131
+ * a large model, and this is a normal long-running Node process, so there is nothing to
132
+ * clean up by cutting it short. Errors are swallowed for the same reason `discoverModels`'s
133
+ * siblings swallow theirs — one endpoint's hiccup here is a nice-to-have that failed, not
134
+ * something worth surfacing as a request failure four layers up.
135
+ */
136
+ export declare function triggerLlamaSwapLoad(host: Pick<CustomModelHost, 'baseUrl' | 'apiKey' | 'authStyle'>, modelId: string): void;
137
+ /**
138
+ * `customModelEndpointsEnabled` defaults OFF (unlike `showPlanUsageLimits`'s
139
+ * absent-means-on in `readPlanUsageTelemetryEnabled`), so mirror the frontend's
140
+ * own gate (`session-ui.js`'s `!settings.customModelEndpointsEnabled`) rather
141
+ * than that reader's default. Exists so the periodic re-discovery sweep in
142
+ * server.ts can skip entirely while the feature is off, instead of polling
143
+ * every saved endpoint forever regardless of the setting.
144
+ */
145
+ export declare function readCustomModelEndpointsEnabled(): Promise<boolean>;
146
+ /**
147
+ * Re-discovers every saved endpoint's models, best-effort. One endpoint being
148
+ * unreachable (powered off, wrong network) must not stop the others from
149
+ * refreshing, and a read-modify-write per host (rather than one batch write
150
+ * at the end) means a crash or restart mid-sweep loses at most the endpoints
151
+ * not yet reached, never a write already applied. Exported so both the
152
+ * periodic timer (server.ts) and a test can drive it directly.
153
+ */
154
+ export declare function refreshAllCustomModelHosts(): Promise<void>;
155
+ /** The subset of `Session` this sweep needs — kept minimal so a test can pass a plain object. */
156
+ export interface CustomModelSessionLike {
157
+ id: string;
158
+ name: string;
159
+ customModel?: {
160
+ endpointId: string;
161
+ modelId: string;
162
+ label?: string;
163
+ };
164
+ }
165
+ /** One session whose model was just found evicted, ready to broadcast as `CustomModelSwappedOut`. */
166
+ export interface CustomModelSwapDisplacement {
167
+ sessionId: string;
168
+ sessionName: string;
169
+ endpointId: string;
170
+ previousModel: string;
171
+ currentlyLoadedModel: string;
172
+ }
173
+ /**
174
+ * Detects when a live session's own custom-model selection is no longer the model
175
+ * llama-swap actually has loaded — evicted by ANOTHER session's activity on the same
176
+ * endpoint, since llama.cpp/llama-swap runs one model at a time (the apply/create routes'
177
+ * own swap-conflict check only ever runs at THAT session's own launch/apply moment, so it
178
+ * cannot catch a later eviction triggered by a different session's normal use — confirmed
179
+ * live: a session created while nothing else had a live conflict at that instant can still
180
+ * get silently displaced afterward). Read-only, and best-effort per endpoint exactly like
181
+ * `refreshAllCustomModelHosts`'s sibling sweep — one endpoint's hiccup here never blocks
182
+ * checking the others.
183
+ *
184
+ * `notifiedSessionIds` is the caller's own de-dupe state (`server.ts` keeps one `Set` across
185
+ * sweeps), mutated in place: a session id is added once displaced and removed again once its
186
+ * own model is loaded and ready — so a LATER, genuinely new displacement can notify again
187
+ * rather than the session staying silently un-notified forever after the first one.
188
+ */
189
+ export declare function detectCustomModelSwapDisplacements(sessions: Iterable<CustomModelSessionLike>, notifiedSessionIds: Set<string>): Promise<CustomModelSwapDisplacement[]>;
17
190
  export declare function registerCustomModelRoutes(app: FastifyInstance): void;
18
191
  //# sourceMappingURL=custom-model-routes.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"custom-model-routes.d.ts","sourceRoot":"","sources":["../../../src/web/routes/custom-model-routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAkB,MAAM,SAAS,CAAC;AAoD/D,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,eAAe,GAAG,IAAI,CA6EpE"}
1
+ {"version":3,"file":"custom-model-routes.d.ts","sourceRoot":"","sources":["../../../src/web/routes/custom-model-routes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,KAAK,EAAE,eAAe,EAAkB,MAAM,SAAS,CAAC;AAQ/D,OAAO,EAA+C,KAAK,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAChH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oCAAoC,CAAC;AAMnE;;;;;;;;;;;;;;;GAeG;AACH,eAAO,MAAM,8BAA8B,QAAQ,CAAC;AAEpD;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CACrC,KAAK,EAAE,IAAI,CAAC,QAAQ,EAAE,cAAc,CAAC,EACrC,aAAa,EAAE,MAAM,GAAG,SAAS,GAChC,OAAO,CAIT;AAsED,MAAM,WAAW,eAAe;IAC9B,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,iGAAiG;IACjG,cAAc,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACvC,mGAAmG;IACnG,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CACjC;AAyJD,MAAM,WAAW,qBAAqB;IACpC,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,MAAM,CAAC;IACd;2FACuF;IACvF,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,eAAe;IAC9B;;;;;;OAMG;IACH,WAAW,EAAE,OAAO,CAAC;IACrB,OAAO,EAAE,qBAAqB,EAAE,CAAC;CAClC;AAED;;;;;;;;GAQG;AACH,wBAAsB,kBAAkB,CACtC,IAAI,EAAE,IAAI,CAAC,eAAe,EAAE,SAAS,GAAG,QAAQ,GAAG,WAAW,CAAC,GAC9D,OAAO,CAAC,eAAe,CAAC,CAuB1B;AAgID;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,yBAAyB,CACvC,IAAI,EAAE,IAAI,CAAC,eAAe,EAAE,IAAI,GAAG,SAAS,GAAG,QAAQ,GAAG,WAAW,CAAC,GACrE,MAAM,GAAG,SAAS,CASpB;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,IAAI,IAAI,CAGhD;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,GAAG,SAAa,GAAG,IAAI,CAOjE;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,IAAI,CAAC,eAAe,EAAE,SAAS,GAAG,QAAQ,GAAG,WAAW,CAAC,EAC/D,OAAO,EAAE,MAAM,GACd,IAAI,CAcN;AA4BD;;;;;;;GAOG;AACH,wBAAsB,+BAA+B,IAAI,OAAO,CAAC,OAAO,CAAC,CAGxE;AAED;;;;;;;GAOG;AACH,wBAAsB,0BAA0B,IAAI,OAAO,CAAC,IAAI,CAAC,CAoBhE;AAED,iGAAiG;AACjG,MAAM,WAAW,sBAAsB;IACrC,EAAE,EAAE,MAAM,CAAC;IACX,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CACvE;AAED,qGAAqG;AACrG,MAAM,WAAW,2BAA2B;IAC1C,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,aAAa,EAAE,MAAM,CAAC;IACtB,oBAAoB,EAAE,MAAM,CAAC;CAC9B;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,kCAAkC,CACtD,QAAQ,EAAE,QAAQ,CAAC,sBAAsB,CAAC,EAC1C,kBAAkB,EAAE,GAAG,CAAC,MAAM,CAAC,GAC9B,OAAO,CAAC,2BAA2B,EAAE,CAAC,CAgDxC;AAED,wBAAgB,yBAAyB,CAAC,GAAG,EAAE,eAAe,GAAG,IAAI,CAsHpE"}